hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequence
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequence
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequence
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
79dadc482e9a7ec6097af0304d646f4986924e44
788
ex
Elixir
apps/app1/test/support/conn_case.ex
jschoch/umb
98e4ca8b883777c775d2b1115ae5116cc32570fe
[ "MIT" ]
null
null
null
apps/app1/test/support/conn_case.ex
jschoch/umb
98e4ca8b883777c775d2b1115ae5116cc32570fe
[ "MIT" ]
null
null
null
apps/app1/test/support/conn_case.ex
jschoch/umb
98e4ca8b883777c775d2b1115ae5116cc32570fe
[ "MIT" ]
null
null
null
defmodule App1.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 imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest import App1.Router.Helpers # The default endpoint for testing @endpoint App1.Endpoint end end setup tags do :ok end end
22.514286
56
0.717005
79dae45bfed8e5d9074f91c1bb702118d151a219
1,496
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/table_list_view.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/table_list_view.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/table_list_view.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.BigQuery.V2.Model.TableListView do @moduledoc """ Additional details for a view. ## Attributes - useLegacySql (boolean()): True if view is defined in legacy SQL dialect, false if in standard SQL. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :useLegacySql => any() } field(:useLegacySql) end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.TableListView do def decode(value, options) do GoogleApi.BigQuery.V2.Model.TableListView.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.TableListView do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
31.166667
123
0.743316
79daffd1da43bee4ce10c5068d7717db1786ffeb
1,125
exs
Elixir
config/config.exs
siddhantmittal7/Mitbits_Cryptocurrency
b02060b1fa6ccc14730433bc4b078b8e5c752a8a
[ "MIT" ]
2
2018-12-10T21:20:04.000Z
2020-07-07T07:28:14.000Z
config/config.exs
prafful13/Mitbits_Cryptocurrency
b02060b1fa6ccc14730433bc4b078b8e5c752a8a
[ "MIT" ]
null
null
null
config/config.exs
prafful13/Mitbits_Cryptocurrency
b02060b1fa6ccc14730433bc4b078b8e5c752a8a
[ "MIT" ]
1
2018-12-16T03:36:18.000Z
2018-12-16T03:36:18.000Z
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure your application as: # # config :mitbits, key: :value # # and access this configuration in your application as: # # Application.get_env(:mitbits, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env()}.exs"
36.290323
73
0.750222
79db1c0d5353000ed87b6098c018cd6dbf6da2ee
554
exs
Elixir
tests/elixir/ifsc_acceptance_test.exs
gyanesh-m/ifsc
7e07f3ea07cc819e90f4e908b68cc94b24a2c440
[ "MIT" ]
null
null
null
tests/elixir/ifsc_acceptance_test.exs
gyanesh-m/ifsc
7e07f3ea07cc819e90f4e908b68cc94b24a2c440
[ "MIT" ]
4
2020-12-31T09:10:55.000Z
2022-02-26T10:09:48.000Z
tests/elixir/ifsc_acceptance_test.exs
gyanesh-m/ifsc
7e07f3ea07cc819e90f4e908b68cc94b24a2c440
[ "MIT" ]
null
null
null
defmodule IFSCAcceptanceTest do use ExUnit.Case alias Razorpay.IFSC describe "acceptance" do tests = Poison.decode!(File.read!("tests/validator_asserts.json")) Enum.map(tests, fn({name, cases}) -> cases = Macro.escape(cases) test name do Enum.map(unquote(Macro.expand(cases, __MODULE__)), fn({ifsc, valid}) -> if valid do assert {:ok, %IFSC{}} = IFSC.validate(ifsc) else assert {:error, _reason} = IFSC.validate(ifsc) end end) end end) end end
25.181818
79
0.592058
79db1c56db51463112c938d13704a8498ded5064
30
ex
Elixir
testData/org/elixir_lang/parser_definition/interpolated_words_heredoc_parsing_test_case/WhitespaceEndPrefix.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/interpolated_words_heredoc_parsing_test_case/WhitespaceEndPrefix.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/interpolated_words_heredoc_parsing_test_case/WhitespaceEndPrefix.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
~w""" one two""" """
7.5
9
0.233333
79db56483d112418cc31d2ce7613655c13857faf
2,333
ex
Elixir
lib/2020/day7.ex
hallski/adventofcode
03efb385688e8072b0b44d35012297833498f799
[ "MIT" ]
null
null
null
lib/2020/day7.ex
hallski/adventofcode
03efb385688e8072b0b44d35012297833498f799
[ "MIT" ]
null
null
null
lib/2020/day7.ex
hallski/adventofcode
03efb385688e8072b0b44d35012297833498f799
[ "MIT" ]
null
null
null
defmodule AdventOfCode.Y2020.Day7 do defstruct type: "", children: [] alias AdventOfCode.Y2020.Day7 alias AdventOfCode.Helpers.Data def run() do IO.puts("Part1: #{run1()}") IO.puts("Part2: #{run2()}") end def run1() do process_input() |> get_valid("shiny gold") |> Enum.count() end def run2() do process_input() |> count_bags("shiny gold") end def process_input() do "2020/day7.txt" |> Data.read_from_file() |> Enum.map(&parse_input/1) |> Enum.reduce(%{}, fn bag, acc -> Map.put(acc, bag.type, bag) end) end def count_bags(_, %Day7{children: []}), do: 0 def count_bags(lookup, %Day7{children: children}) do children |> Enum.map(fn %{"quantity" => quantity, "type" => type} -> quantity * (1 + count_bags(lookup, type)) end) |> Enum.reduce(&(&1 + &2)) end def count_bags(lookup, type) when is_binary(type) do count_bags(lookup, lookup[type]) end @spec parse_bag_type_content(binary) :: nil | map def parse_bag_type_content(child_str) do %{"quantity" => quantity, "type" => type} = Regex.named_captures(~r/^(?<quantity>\d+)\s(?<type>.*)\sbags?$/, child_str) %{"quantity" => String.to_integer(quantity), "type" => type} end def parse_bag(%{"type" => type, "content" => "no other bags"}), do: %Day7{type: type} def parse_bag(%{"type" => type, "content" => content}) do children = content |> String.split(", ", trim: true) |> Enum.map(&parse_bag_type_content/1) %Day7{type: type, children: children} end def parse_input(line) when is_binary(line) do Regex.named_captures(~r/^(?<type>.*)\sbags contain\s(?<content>.*)\.$/, line) |> parse_bag() end def get_valid(lookup, looking_for) do lookup |> Map.values() |> Enum.filter(fn bag -> bag.type != looking_for end) |> Enum.filter(&is_valid(&1, looking_for, lookup)) end def is_valid(type, looking_for, lookup) when is_binary(type) do is_valid(lookup[type], looking_for, lookup) end def is_valid(%Day7{type: type}, looking_for, _) when type == looking_for, do: true def is_valid(%Day7{children: []}, _, _), do: false def is_valid(%Day7{} = bag, looking_for, lookup) do bag.children |> Enum.any?(fn child -> is_valid(child["type"], looking_for, lookup) end) end end
26.816092
87
0.624946
79db5fbcd13a4bffbb2ff519eb1ca6691daf607b
311
exs
Elixir
apps/train_loc/lib/mix/tasks/infer_blocks.exs
paulswartz/commuter_rail_boarding
6be34c192d6a1ee980307d9f3d027bf4cdafa53f
[ "MIT" ]
1
2022-01-30T20:53:07.000Z
2022-01-30T20:53:07.000Z
apps/train_loc/lib/mix/tasks/infer_blocks.exs
paulswartz/commuter_rail_boarding
6be34c192d6a1ee980307d9f3d027bf4cdafa53f
[ "MIT" ]
47
2021-05-05T10:31:05.000Z
2022-03-30T22:18:14.000Z
apps/train_loc/lib/mix/tasks/infer_blocks.exs
paulswartz/commuter_rail_boarding
6be34c192d6a1ee980307d9f3d027bf4cdafa53f
[ "MIT" ]
1
2021-05-14T00:35:08.000Z
2021-05-14T00:35:08.000Z
defmodule Mix.Tasks.InferBlocks do use Mix.Task alias TrainLoc.LogAnalyzer.BlockInferrer @shortdoc "Infers blocks from vehicle assignment logs" def run(logs_file_path) do blocks = logs_file_path |> File.read!() |> BlockInferrer.run() IO.puts(Jason.encode!(blocks)) end end
20.733333
56
0.697749
79db7d53b24c6a0beed7f6432b67f83d02e067f2
74
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/DecimalFloat.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
1,668
2015-01-03T05:54:27.000Z
2022-03-25T08:01:20.000Z
testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/DecimalFloat.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
2,018
2015-01-01T22:43:39.000Z
2022-03-31T20:13:08.000Z
testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/DecimalFloat.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
1.2e3 ++ 4.5+6 7.8e9 -- 10.11e-12 13.14e15..16.17e18 19.20e21 <> 22.23e24
14.8
20
0.621622
79db8d69dc6ee372fef3e22025a9f95a37b935b7
705
exs
Elixir
priv/repo/migrations/20210312220005_create_activity_registrations_projects.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
priv/repo/migrations/20210312220005_create_activity_registrations_projects.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
priv/repo/migrations/20210312220005_create_activity_registrations_projects.exs
malav2110/oli-torus
8af64e762a7c8a2058bd27a7ab8e96539ffc055f
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Repo.Migrations.CreateActivityRegistrationsProjects do use Ecto.Migration def change do create table(:activity_registration_projects, primary_key: false) do timestamps(type: :timestamptz) add :activity_registration_id, references(:activity_registrations), primary_key: true add :project_id, references(:projects), primary_key: true end create index(:activity_registration_projects, [:activity_registration_id]) create index(:activity_registration_projects, [:project_id]) create unique_index(:activity_registration_projects, [:activity_registration_id, :project_id], name: :index_activity_registration_project ) end end
37.105263
98
0.765957
79dbe608fedf0b8c95b0f9dc11faba6f80f411a0
5,314
exs
Elixir
test/ecto/model/callbacks_test.exs
aforward/ecto
74bf4528abf198b25ff261d127fe7cf54a1ff044
[ "Apache-2.0" ]
null
null
null
test/ecto/model/callbacks_test.exs
aforward/ecto
74bf4528abf198b25ff261d127fe7cf54a1ff044
[ "Apache-2.0" ]
null
null
null
test/ecto/model/callbacks_test.exs
aforward/ecto
74bf4528abf198b25ff261d127fe7cf54a1ff044
[ "Apache-2.0" ]
null
null
null
Code.require_file "../../support/mock_repo.exs", __DIR__ alias Ecto.MockRepo defmodule Ecto.Model.CallbacksTest do use ExUnit.Case, async: true defmodule SomeCallback do use Ecto.Model schema "some_callback" do field :x, :string, default: "" end before_delete __MODULE__, :add_to_x before_delete __MODULE__, :add_to_x, [%{str: "2"}] before_delete :add_to_x before_delete :add_to_x, [%{str: "2"}] before_update :bad_callback def add_to_x(changeset, %{str: str} \\ %{str: "1"}) do update_in changeset.model.x, &(&1 <> "," <> str) end defp bad_callback(_changeset) do nil end end test "defines functions for callbacks" do assert function_exported?(SomeCallback, :before_delete, 1) end test "doesn't define callbacks for not-registered events" do refute function_exported?(SomeCallback, :after_delete, 1) end test "applies callbacks" do changeset = %Ecto.Changeset{model: %SomeCallback{x: "x"}} assert Ecto.Model.Callbacks.__apply__(SomeCallback, :before_delete, changeset) == %Ecto.Changeset{model: %SomeCallback{x: "x,1,2,1,2"}} end test "raises on bad callbacks" do msg = "expected `before_update` callbacks to return a Ecto.Changeset, got: nil" assert_raise ArgumentError, msg, fn -> Ecto.Model.Callbacks.__apply__(SomeCallback, :before_update, %Ecto.Changeset{}) end end ## Repo integration defmodule AllCallback do use Ecto.Model schema "all_callback" do field :x, :string, default: "" field :y, :string, default: "" field :z, :string, default: "" field :before, :any, virtual: true field :after, :any, virtual: true field :xyz, :string, virtual: true end before_insert __MODULE__, :changeset_before after_insert __MODULE__, :changeset_after before_update __MODULE__, :changeset_before after_update __MODULE__, :changeset_after before_delete __MODULE__, :changeset_before after_delete __MODULE__, :changeset_after after_load __MODULE__, :changeset_load def changeset_before(%{repo: MockRepo} = changeset) do put_in(changeset.model.before, changeset.changes) |> delete_change(:z) end def changeset_after(%{repo: MockRepo} = changeset) do put_in(changeset.model.after, changeset.changes) end def changeset_load(model) do Map.put(model, :xyz, model.x <> model.y <> model.z) end end test "wraps operations into transactions if callback present" do model = %SomeCallback{x: "x"} MockRepo.insert model refute_received {:transaction, _fun} model = %AllCallback{x: "x"} MockRepo.insert model assert_received {:transaction, _fun} end test "before_insert and after_insert with model" do model = %AllCallback{x: "x"} model = MockRepo.insert model assert model.before == %{x: "x", y: "", z: ""} assert model.after == %{x: "x", y: ""} model = %AllCallback{id: 1, x: "x"} model = MockRepo.insert model assert model.before == %{id: 1, x: "x", y: "", z: ""} assert model.after == %{id: 1, x: "x", y: ""} end test "before_update and after_update with model" do model = %AllCallback{id: 1, x: "x"} model = MockRepo.update model assert model.before == %{x: "x", y: "", z: ""} assert model.after == %{x: "x", y: ""} end test "before_delete and after_delete with model" do model = %AllCallback{id: 1, x: "x"} model = MockRepo.delete model assert model.before == %{} assert model.after == %{} end test "before_insert and after_insert with changeset" do changeset = Ecto.Changeset.cast(%AllCallback{x: "x", y: "z"}, %{"y" => "y", "z" => "z"}, ~w(y z), ~w()) model = MockRepo.insert changeset assert model.before == %{x: "x", y: "y", z: "z"} assert model.after == %{x: "x", y: "y"} assert model.x == "x" assert model.y == "y" assert model.z == "" end test "before_update and after_update with changeset" do changeset = Ecto.Changeset.cast(%AllCallback{id: 1, x: "x", y: "z"}, %{"y" => "y", "z" => "z"}, ~w(y z), ~w()) model = MockRepo.update changeset assert model.before == %{y: "y", z: "z"} assert model.after == %{y: "y"} assert model.x == "x" assert model.y == "y" assert model.z == "" end test "before_insert and after_insert with id in changeset" do changeset = Ecto.Changeset.cast(%AllCallback{}, %{"id" => 1}, ~w(id), ~w()) model = MockRepo.insert changeset assert model.before == %{id: 1, x: "", y: "", z: ""} assert model.after == %{id: 1, x: "", y: ""} end test "before_update and after_update with id in changeset" do changeset = Ecto.Changeset.cast(%AllCallback{id: 0}, %{"id" => 1}, ~w(id), ~w()) model = MockRepo.update changeset assert model.before == %{id: 1} assert model.after == %{id: 1} end test "after_load with model" do model = AllCallback.__schema__(:load, "hello", 2, {nil, nil, 1, "x", "y", "z"}, %{}) assert model.id == 1 assert model.xyz == "xyz" assert model.__meta__ == %Ecto.Schema.Metadata{source: "hello", state: :loaded} end end
31.443787
88
0.615544
79dc03e24212ebac9c39c21915d5ccc909774122
19,961
ex
Elixir
lib/nebulex_redis_adapter.ex
lucas-cegatti/nebulex_redis_adapter
6d21323a00248f0a9dfa831b5110b1ee591ef39c
[ "MIT" ]
null
null
null
lib/nebulex_redis_adapter.ex
lucas-cegatti/nebulex_redis_adapter
6d21323a00248f0a9dfa831b5110b1ee591ef39c
[ "MIT" ]
null
null
null
lib/nebulex_redis_adapter.ex
lucas-cegatti/nebulex_redis_adapter
6d21323a00248f0a9dfa831b5110b1ee591ef39c
[ "MIT" ]
null
null
null
defmodule NebulexRedisAdapter do @moduledoc ~S""" Nebulex adapter for Redis. This adapter is implemented using `Redix`, a Redis driver for Elixir. **NebulexRedisAdapter** provides three setup alternatives: * **Standalone** - The adapter establishes a pool of connections with a single Redis node. The `:standalone` is the default mode. * **Redis Cluster** - [Redis Cluster](https://redis.io/topics/cluster-tutorial) is a built-in feature in Redis since version 3, and it may be the most convenient and recommendable way to set up Redis in a cluster and have a distributed cache storage out-of-box. This adapter provides the `:redis_cluster` mode to set up **Redis Cluster** from the client-side automatically and be able to use it transparently. * **Built-in client-side cluster based on sharding** - This adapter provides a simple client-side cluster implementation based on Sharding distribution model via `:client_side_cluster` mode. ## Shared Options In addition to `Nebulex.Cache` shared options, this adapters supports the following options: * `:mode` - Defines the mode Redis will be set up. It can be one of the next values: `:standalone`, `:client_side_cluster`, `:redis_cluster`. Defaults to `:standalone`. * `:pool_size` - Number of connections in the pool. Defaults to `System.schedulers_online()`. * `:conn_opts` - Redis client options (`Redix` options in this case). For more information about connection options, see `Redix` docs. ## TTL or Expiration Time As is explained in `Nebulex.Cache`, most of the write-like functions support the `:ttl` option to define the expiration time, and it is defined in **milliseconds**. Despite Redis work with **seconds**, the conversion logic is handled by the adapter transparently, so when using a cache even with the Redis adapter, be sure you pass the `:ttl` option in **milliseconds**. ## Data Types This adapter only works with strings internally, which means the given Elixir terms are encoded to binaries before executing the Redis command. The encoding/decoding process is performed by the adapter under-the-hood, so it is completely transparent for the user. **NOTE:** Support for other Redis Data Types is in the roadmap. ## Standalone We can define a cache to use Redis as follows: defmodule MyApp.RedisCache do use Nebulex.Cache, otp_app: :nebulex, adapter: NebulexRedisAdapter end The configuration for the cache must be in your application environment, usually defined in your `config/config.exs`: config :my_app, MyApp.RedisCache, conn_opts: [ host: "127.0.0.1", port: 6379 ] ## Redis Cluster We can define a cache to use Redis Cluster as follows: defmodule MyApp.RedisClusterCache do use Nebulex.Cache, otp_app: :nebulex, adapter: NebulexRedisAdapter end The config: config :my_app, MyApp.RedisClusterCache, mode: :redis_cluster, master_nodes: [ [ host: "127.0.0.1", port: 7000 ], [ url: "redis://127.0.0.1:7001" ], [ url: "redis://127.0.0.1:7002" ] ], conn_opts: [ # Redix options, except `:host` and `:port`; unless we have a cluster # of nodes with the same host and/or port, which doesn't make sense. ] ### Redis Cluster Options In addition to shared options, `:redis_cluster` mode supports the following options: * `:master_nodes` - The list with the configuration for the Redis cluster master nodes. The configuration for each master nodes contains the same options as `:conn_opts`. The adapter traverses the list trying to establish connection at least with one of them and get the cluster slots to finally setup the Redis cluster from client side properly. If one fails, the adapter retries with the next in the list, that's why at least one master node must be set. * `:conn_opts` - Same as shared options (optional). The `:conn_opts` will be applied to each connection pool with the cluster (they will override the host and port retrieved from cluster slots info). For that reason, be careful when setting `:host` or `:port` options since they will be used globally and can cause connection issues. Normally, we add here the desired client options except `:host` and `:port`. If you have a cluster with the same host for all nodes, in that case make sense to add also the `:host` option. * `:pool_size` - Same as shared options (optional). It applies to all cluster slots, meaning all connection pools will have the same size. ## Client-side cluster We can define a cache with "client-side cluster mode" as follows: defmodule MyApp.ClusteredCache do use Nebulex.Cache, otp_app: :nebulex, adapter: NebulexRedisAdapter end The config: config :my_app, MyApp.ClusteredCache, mode: :client_side_cluster, nodes: [ node1: [ pool_size: 10, conn_opts: [ host: "127.0.0.1", port: 9001 ] ], node2: [ pool_size: 4, conn_opts: [ url: "redis://127.0.0.1:9002" ] ], node3: [ conn_opts: [ host: "127.0.0.1", port: 9003 ] ] ] By default, the adapter uses `NebulexRedisAdapter.ClientCluster.Keyslot` for the keyslot. Besides, if `:jchash` is defined as dependency, the adapter will use consistent-hashing automatically. However, you can also provide your own implementation by implementing the `Nebulex.Adapter.Keyslot` and set it into the `:keyslot` option. For example: defmodule MyApp.ClusteredCache.Keyslot do use Nebulex.Adapter.Keyslot @impl true def hash_slot(key, range) do # your implementation goes here end end And the config: config :my_app, MyApp.ClusteredCache, mode: :client_side_cluster, keyslot: MyApp.ClusteredCache.Keyslot, nodes: [ ... ] ### Client-side cluster options In addition to shared options, `:client_side_cluster` mode supports the following options: * `:nodes` - The list of nodes the adapter will setup the cluster with; a pool of connections is established per node. The `:client_side_cluster` mode enables resilience to be able to survive in case any node(s) gets unreachable. For each element of the list, we set the configuration for each node, such as `:conn_opts`, `:pool_size`, etc. * `:keyslot` - Defines the module implementing `Nebulex.Adapter.Keyslot` behaviour, used to compute the node where the command will be applied to. It is highly recommendable to provide a consistent hashing implementation. ## Queryable API Since the queryable API is implemented by using `KEYS` command: * Only strings (`String.t()`) are allowed as query parameter. * Only keys can be queried. ### Examples iex> MyApp.RedisCache.put_all(%{ ...> "firstname" => "Albert", ...> "lastname" => "Einstein", ...> "age" => 76 ...> }) :ok iex> MyApp.RedisCache.all("**name**") ["firstname", "lastname"] iex> MyApp.RedisCache.all("a??") ["age"] iex> MyApp.RedisCache.all() ["age", "firstname", "lastname"] iex> stream = TestCache.stream("**name**") iex> stream |> Enum.to_list() ["firstname", "lastname"] # get the values for the returned queried keys iex> "**name**" |> MyApp.RedisCache.all() |> MyApp.RedisCache.get_all() %{"firstname" => "Albert", "lastname" => "Einstein"} ## Using the cache for executing a Redis command or pipeline Since `NebulexRedisAdapter` works on top of `Redix` and provides features like connection pools and "Redis Cluster" support, it may be seen also as a sort of Redis client, but it is meant to be used mainly with the Nebulex cache API. However, Redis API is quite extensive and there are a lot of useful commands we may want to run taking advantage of the `NebulexRedisAdapter` features. Therefore, the adapter injects two additional/extended functions to the defined cache: `command!/3` and `pipeline!/3`. ### `command!(key \\ nil, name \\ __MODULE__, command)` iex> MyCache.command!("mylist", ["LPUSH", "mylist", "world"]) 1 iex> MyCache.command!("mylist", ["LPUSH", "mylist", "hello"]) 2 iex> MyCache.command!("mylist", ["LRANGE", "mylist", "0", "-1"]) ["hello", "world"] ### `pipeline!(key \\ nil, name \\ __MODULE__, commands)` iex> cache.pipeline!("mylist", [ ...> ["LPUSH", "mylist", "world"], ...> ["LPUSH", "mylist", "hello"], ...> ["LRANGE", "mylist", "0", "-1"] ...> ]) [1, 2, ["hello", "world"]] Arguments for `command!/3` and `pipeline!/3`: * `key` - it is required when used the adapter in mode `:redis_cluster` or `:client_side_cluster` so that the node where the commands will take place can be selected properly. For `:standalone` it is optional. * `name` - The name of the cache in case you are using dynamic caches, otherwise it is not required. * `commands` - Redis commands. ## Transactions This adapter doesn't provide support for transactions, since there is no way to guarantee its execution on Redis itself, at least not in the way the `c:Nebulex.Adapter.Transaction.transaction/3` works, because the anonymous function can have any kind of logic, which cannot be translated easily into Redis commands. > In the future, it is planned to add to Nebulex a `multi`-like function to perform multiple commands at once, perhaps that will be the best way to perform [transactions via Redis](https://redis.io/topics/transactions). """ # Provide Cache Implementation @behaviour Nebulex.Adapter @behaviour Nebulex.Adapter.Entry @behaviour Nebulex.Adapter.Queryable import Nebulex.Helpers import NebulexRedisAdapter.Encoder alias Nebulex.Adapter alias NebulexRedisAdapter.{ClientCluster, Command, Connection, RedisCluster} ## Nebulex.Adapter @impl true defmacro __before_compile__(_env) do quote do @doc """ A convenience function for executing a Redis command. """ def command!(key \\ nil, name \\ __MODULE__, command) do Adapter.with_meta(name, fn _, meta -> Command.exec!(meta, command, key) end) end @doc """ A convenience function for executing a Redis pipeline. """ def pipeline!(key \\ nil, name \\ __MODULE__, commands) do Adapter.with_meta(name, fn _, meta -> Command.pipeline!(meta, commands, key) end) end end end @impl true def init(opts) do # required cache name name = opts[:name] || Keyword.fetch!(opts, :cache) # adapter mode mode = Keyword.get(opts, :mode, :standalone) # pool size pool_size = get_option( opts, :pool_size, "an integer > 0", &(is_integer(&1) and &1 > 0), System.schedulers_online() ) # init the specs according to the adapter mode {children, default_keyslot} = do_init(mode, name, pool_size, opts) # keyslot module for selecting nodes keyslot = opts |> Keyword.get(:keyslot, default_keyslot) |> assert_behaviour(Nebulex.Adapter.Keyslot, "keyslot") # cluster nodes nodes = for {node_name, node_opts} <- Keyword.get(opts, :nodes, []) do {node_name, Keyword.get(node_opts, :pool_size, System.schedulers_online())} end child_spec = Nebulex.Adapters.Supervisor.child_spec( name: normalize_module_name([name, Supervisor]), strategy: :rest_for_one, children: children ) meta = %{ name: name, mode: mode, keyslot: keyslot, nodes: nodes, pool_size: pool_size, default_dt: Keyword.get(opts, :default_data_type, :object) } {:ok, child_spec, meta} end defp do_init(:standalone, name, pool_size, opts) do {:ok, children} = Connection.init(name, pool_size, opts) {children, ClientCluster.Keyslot} end defp do_init(:client_side_cluster, _name, _pool_size, opts) do {:ok, children} = ClientCluster.init(opts) {children, ClientCluster.Keyslot} end defp do_init(:redis_cluster, name, pool_size, opts) do {:ok, children} = RedisCluster.init(name, pool_size, opts) {children, RedisCluster.Keyslot} end ## Nebulex.Adapter.Entry @impl true def get(adapter_meta, key, _opts) do with_pipeline(adapter_meta, key, [["GET", encode(key)]]) end @impl true def get_all(%{mode: :standalone} = adapter_meta, keys, _opts) do mget(nil, adapter_meta, keys) end def get_all(adapter_meta, keys, _opts) do keys |> group_keys_by_hash_slot(adapter_meta) |> Enum.reduce(%{}, fn {hash_slot, keys}, acc -> return = mget(hash_slot, adapter_meta, keys) Map.merge(acc, return) end) end defp mget(hash_slot_key, adapter_meta, keys) do adapter_meta |> Command.exec!(["MGET" | for(k <- keys, do: encode(k))], hash_slot_key) |> Enum.reduce({keys, %{}}, fn nil, {[_key | keys], acc} -> {keys, acc} value, {[key | keys], acc} -> {keys, Map.put(acc, key, decode(value))} end) |> elem(1) end @impl true def put(adapter_meta, key, value, ttl, on_write, opts) do cmd_opts = cmd_opts(action: on_write, ttl: fix_ttl(ttl)) redis_k = encode(key) redis_v = encode(value, opts) case Command.exec!(adapter_meta, ["SET", redis_k, redis_v | cmd_opts], key) do "OK" -> true nil -> false end end @impl true def put_all(%{mode: :standalone} = adapter_meta, entries, ttl, on_write, opts) do do_put_all(adapter_meta, nil, entries, fix_ttl(ttl), on_write, opts) end def put_all(adapter_meta, entries, ttl, on_write, opts) do ttl = fix_ttl(ttl) entries |> group_keys_by_hash_slot(adapter_meta) |> Enum.reduce(:ok, fn {hash_slot, group}, acc -> acc && do_put_all(adapter_meta, hash_slot, group, ttl, on_write, opts) end) end defp do_put_all(adapter_meta, hash_slot, entries, ttl, on_write, opts) do cmd = case on_write do :put -> "MSET" :put_new -> "MSETNX" end {mset, expire} = Enum.reduce(entries, {[cmd], []}, fn {key, val}, {acc1, acc2} -> redis_k = encode(key) acc2 = if is_integer(ttl), do: [["EXPIRE", redis_k, ttl] | acc2], else: acc2 {[encode(val, opts), redis_k | acc1], acc2} end) adapter_meta |> Command.pipeline!([Enum.reverse(mset) | expire], hash_slot) |> hd() |> case do "OK" -> :ok 1 -> true 0 -> false end end @impl true def delete(adapter_meta, key, _opts) do _ = Command.exec!(adapter_meta, ["DEL", encode(key)], key) :ok end @impl true def take(adapter_meta, key, _opts) do redis_k = encode(key) with_pipeline(adapter_meta, key, [["GET", redis_k], ["DEL", redis_k]]) end @impl true def has_key?(adapter_meta, key) do case Command.exec!(adapter_meta, ["EXISTS", encode(key)], key) do 1 -> true 0 -> false end end @impl true def ttl(adapter_meta, key) do case Command.exec!(adapter_meta, ["TTL", encode(key)], key) do -1 -> :infinity -2 -> nil ttl -> ttl * 1000 end end @impl true def expire(adapter_meta, key, :infinity) do redis_k = encode(key) case Command.pipeline!(adapter_meta, [["TTL", redis_k], ["PERSIST", redis_k]], key) do [-2, 0] -> false [_, _] -> true end end def expire(adapter_meta, key, ttl) do case Command.exec!(adapter_meta, ["EXPIRE", encode(key), fix_ttl(ttl)], key) do 1 -> true 0 -> false end end @impl true def touch(adapter_meta, key) do case Command.exec!(adapter_meta, ["TOUCH", encode(key)], key) do 1 -> true 0 -> false end end @impl true def update_counter(adapter_meta, key, incr, :infinity, default, _opts) do redis_k = encode(key) adapter_meta |> maybe_incr_default(key, redis_k, default) |> Command.exec!(["INCRBY", redis_k, incr], key) end def update_counter(adapter_meta, key, incr, ttl, default, _opts) do redis_k = encode(key) adapter_meta |> maybe_incr_default(key, redis_k, default) |> Command.pipeline!([["INCRBY", redis_k, incr], ["EXPIRE", redis_k, fix_ttl(ttl)]], key) |> hd() end defp maybe_incr_default(adapter_meta, key, redis_k, default) when is_integer(default) and default > 0 do case Command.exec!(adapter_meta, ["EXISTS", redis_k], key) do 1 -> adapter_meta 0 -> _ = Command.exec!(adapter_meta, ["INCRBY", redis_k, default], key) adapter_meta end end defp maybe_incr_default(adapter_meta, _, _, _), do: adapter_meta ## Nebulex.Adapter.Queryable @impl true def execute(%{mode: mode} = adapter_meta, :count_all, nil, _opts) do exec!(mode, [adapter_meta, ["DBSIZE"]], [0, &Kernel.+(&2, &1)]) end def execute(%{mode: mode} = adapter_meta, :delete_all, nil, _opts) do size = exec!(mode, [adapter_meta, ["DBSIZE"]], [0, &Kernel.+(&2, &1)]) _ = exec!(mode, [adapter_meta, ["FLUSHDB"]], []) size end def execute(adapter_meta, :all, query, _opts) do execute_query(query, adapter_meta) end @impl true def stream(adapter_meta, query, _opts) do Stream.resource( fn -> execute_query(query, adapter_meta) end, fn [] -> {:halt, []} elems -> {elems, []} end, & &1 ) end ## Private Functions defp with_pipeline(adapter_meta, key, pipeline) do adapter_meta |> Command.pipeline!(pipeline, key) |> hd() |> decode() end defp cmd_opts(keys), do: Enum.reduce(keys, [], &cmd_opts/2) defp cmd_opts({:action, :put}, acc), do: acc defp cmd_opts({:action, :put_new}, acc), do: ["NX" | acc] defp cmd_opts({:action, :replace}, acc), do: ["XX" | acc] defp cmd_opts({:ttl, :infinity}, acc), do: acc defp cmd_opts({:ttl, ttl}, acc), do: ["EX", "#{ttl}" | acc] defp fix_ttl(:infinity), do: :infinity defp fix_ttl(ttl) when is_integer(ttl) and ttl >= 1000, do: div(ttl, 1000) defp fix_ttl(ttl) do raise ArgumentError, "expected ttl: to be an integer >= 1000 or :intinity, got: #{inspect(ttl)}" end defp execute_query(nil, adapter_meta) do for key <- execute_query("*", adapter_meta), do: decode(key) end defp execute_query(pattern, %{mode: mode} = adapter_meta) when is_binary(pattern) do exec!(mode, [adapter_meta, ["KEYS", pattern]], [[], &Kernel.++(&1, &2)]) end defp execute_query(pattern, _adapter_meta) do raise Nebulex.QueryError, message: "invalid pattern", query: pattern end defp exec!(:standalone, args, _extra_args) do apply(Command, :exec!, args) end defp exec!(:client_side_cluster, args, extra_args) do apply(ClientCluster, :exec!, args ++ extra_args) end defp exec!(:redis_cluster, args, extra_args) do apply(RedisCluster, :exec!, args ++ extra_args) end defp group_keys_by_hash_slot(enum, %{mode: :client_side_cluster, nodes: nodes, keyslot: keyslot}) do ClientCluster.group_keys_by_hash_slot(enum, nodes, keyslot) end defp group_keys_by_hash_slot(enum, %{mode: :redis_cluster, keyslot: keyslot}) do RedisCluster.group_keys_by_hash_slot(enum, keyslot) end end
30.474809
102
0.637543
79dc0765ef5586ac7d61c1df1ae73539db1fa925
2,115
exs
Elixir
test/glimesh_web/live/user_live_components/subscribe_button_test.exs
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
1
2020-08-02T00:12:28.000Z
2020-08-02T00:12:28.000Z
test/glimesh_web/live/user_live_components/subscribe_button_test.exs
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
test/glimesh_web/live/user_live_components/subscribe_button_test.exs
Darkhax-Forked/glimesh.tv
9566f0ec6909ecc5151f0e092f3e08b63d911fa8
[ "MIT" ]
null
null
null
defmodule GlimeshWeb.UserLive.Components.SubscribeButtonTest do use GlimeshWeb.ConnCase import Phoenix.LiveViewTest import Glimesh.AccountsFixtures @component GlimeshWeb.UserLive.Components.SubscribeButton defp create_streamer(_) do %{streamer: streamer_fixture(%{can_payments: true})} end describe "subscription button unauthed user" do setup :create_streamer test "shows a subscription button that links to register", %{conn: conn, streamer: streamer} do {:ok, view, html} = live_isolated(conn, @component, session: %{"user" => nil, "streamer" => streamer}) assert html =~ "href=\"/users/register\"" assert html =~ "Subscribe" end end describe "subscription button authed user" do setup [:register_and_log_in_user, :create_streamer] test "shows a disabled subscription button for user without can_payments", %{ conn: conn, user: user, streamer: streamer } do {:ok, view, html} = live_isolated(conn, @component, session: %{"user" => user, "streamer" => streamer}) assert html =~ "Subscribe" assert html =~ "btn btn-secondary disabled" end test "shows a disabled subscription button for when the user is the streamer", %{ conn: conn, user: user, streamer: streamer } do {:ok, view, html} = live_isolated(conn, @component, session: %{"user" => streamer, "streamer" => streamer}) assert html =~ "Subscribe" assert html =~ "btn btn-secondary disabled" end test "shows a subscription button for user with can_payments", %{ conn: conn, streamer: streamer } do user = user_fixture(%{can_payments: true}) {:ok, view, html} = live_isolated(conn, @component, id: "subscribe-button", session: %{"user" => user, "streamer" => streamer} ) assert html =~ "Subscribe" assert html =~ "class=\"btn btn-secondary\"" modal = view |> element("button", "Subscribe") |> render_click() assert modal =~ "<strong>$5.00</strong>/ monthly" end end end
29.375
99
0.638771
79dc5b458bcb85e04b0fffe2d71efd84516deaff
7,202
exs
Elixir
test/towwwer/websites/websites_test.exs
juhalehtonen/towwwer
552fe57e93adc9c521a4c6a8ef550b84efec32ca
[ "MIT" ]
1
2019-05-03T13:39:40.000Z
2019-05-03T13:39:40.000Z
test/towwwer/websites/websites_test.exs
juhalehtonen/towwwer
552fe57e93adc9c521a4c6a8ef550b84efec32ca
[ "MIT" ]
13
2019-03-27T05:40:41.000Z
2019-05-24T10:43:31.000Z
test/towwwer/websites/websites_test.exs
juhalehtonen/towwwer
552fe57e93adc9c521a4c6a8ef550b84efec32ca
[ "MIT" ]
null
null
null
defmodule Towwwer.WebsitesTest do use Towwwer.DataCase alias Towwwer.Websites def unload_relations(obj, to_remove \\ nil) do assocs = if to_remove == nil, do: obj.__struct__.__schema__(:associations), else: Enum.filter(obj.__struct__.__schema__(:associations), &(&1 in to_remove)) Enum.reduce(assocs, obj, fn assoc, obj -> assoc_meta = obj.__struct__.__schema__(:association, assoc) Map.put(obj, assoc, %Ecto.Association.NotLoaded{ __field__: assoc, __owner__: assoc_meta.owner, __cardinality__: assoc_meta.cardinality }) end) end describe "sites" do alias Towwwer.Websites.Site @valid_attrs %{ base_url: "someurl", token: "sometoken", wp_content_dir: "dir", wp_plugins_dir: "dir", monitors: %{"0" => %{"path" => "/"}} } @update_attrs %{ base_url: "someupdatedurl", token: "someupdatedtoken", wp_content_dir: "dirr", wp_plugins_dir: "dirr", monitors: %{"0" => %{"path" => "/"}} } @invalid_attrs %{ base_url: nil, token: nil, wp_content_dir: nil, wp_plugins_dir: nil, monitors: nil } def site_fixture(attrs \\ %{}) do {:ok, site} = attrs |> Enum.into(@valid_attrs) |> Websites.create_site() site end test "list_sites/0 returns all sites" do site = site_fixture() assert Websites.list_sites() == [unload_relations(site)] end test "get_site!/1 returns the site with given id" do site = site_fixture() assert unload_relations(Websites.get_site!(site.id)) == unload_relations(site) end test "create_site/1 with valid data creates a site" do assert {:ok, %Site{} = site} = Websites.create_site(@valid_attrs) assert site.base_url == "someurl" assert site.token == "sometoken" end test "create_site/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Websites.create_site(@invalid_attrs) end # test "update_site/2 with valid data updates the site" do # site = site_fixture() # assert {:ok, %Site{} = site} = Websites.update_site(site, @update_attrs) # assert site.base_url == "someupdatedurl" # assert site.token == "someupdatedtoken" # end test "update_site/2 with invalid data returns error changeset" do site = site_fixture() assert {:error, %Ecto.Changeset{}} = Websites.update_site(site, @invalid_attrs) assert unload_relations(site) == unload_relations(Websites.get_site!(site.id)) end test "delete_site/1 deletes the site" do site = site_fixture() assert {:ok, %Site{}} = Websites.delete_site(site) assert_raise Ecto.NoResultsError, fn -> Websites.get_site!(site.id) end end test "change_site/1 returns a site changeset" do site = site_fixture() assert %Ecto.Changeset{} = Websites.change_site(site) end end describe "monitors" do alias Towwwer.Websites.Monitor @valid_attrs %{path: "some path"} @update_attrs %{path: "some updated path"} @invalid_attrs %{path: nil} def monitor_fixture(attrs \\ %{}) do {:ok, monitor} = attrs |> Enum.into(@valid_attrs) |> Websites.create_monitor() monitor end test "list_monitors/0 returns all monitors" do monitor = monitor_fixture() [listed_monitor] = Websites.list_monitors() assert [unload_relations(listed_monitor)] == [unload_relations(monitor)] end test "get_monitor!/1 returns the monitor with given id" do monitor = monitor_fixture() assert unload_relations(Websites.get_monitor!(monitor.id)) == unload_relations(monitor) end test "create_monitor/1 with valid data creates a monitor" do assert {:ok, %Monitor{} = monitor} = Websites.create_monitor(@valid_attrs) assert monitor.path == "some path" end test "create_monitor/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Websites.create_monitor(@invalid_attrs) end test "update_monitor/2 with valid data updates the monitor" do monitor = monitor_fixture() assert {:ok, %Monitor{} = monitor} = Websites.update_monitor(monitor, @update_attrs) assert monitor.path == "some updated path" end test "update_monitor/2 with invalid data returns error changeset" do monitor = monitor_fixture() assert {:error, %Ecto.Changeset{}} = Websites.update_monitor(monitor, @invalid_attrs) assert unload_relations(monitor) == unload_relations(Websites.get_monitor!(monitor.id)) end test "delete_monitor/1 deletes the monitor" do monitor = monitor_fixture() assert {:ok, %Monitor{}} = Websites.delete_monitor(monitor) assert_raise Ecto.NoResultsError, fn -> Websites.get_monitor!(monitor.id) end end test "change_monitor/1 returns a monitor changeset" do monitor = monitor_fixture() assert %Ecto.Changeset{} = Websites.change_monitor(monitor) end end describe "reports" do alias Towwwer.Websites.Report @valid_attrs %{ data: %{}, wpscan_data: %{}, monitor: %{"path" => "/"} } # @update_attrs %{ # data: %{}, # wpscan_data: %{}, # monitor: %{"path" => "/abc"} # } @invalid_attrs %{data: nil} def report_fixture(attrs \\ %{}) do {:ok, report} = attrs |> Enum.into(@valid_attrs) |> Websites.create_report() report end test "list_reports/0 returns all reports" do report = report_fixture() assert Websites.list_reports() == [unload_relations(report)] end test "get_report!/1 returns the report with given id" do report = report_fixture() assert unload_relations(Websites.get_report!(report.id)) == unload_relations(report) end test "create_report/1 with valid data creates a report" do assert {:ok, %Report{} = report} = Websites.create_report(@valid_attrs) assert report.data == %{} end test "create_report/1 with invalid data returns error changeset" do assert {:error, %Ecto.Changeset{}} = Websites.create_report(@invalid_attrs) end # test "update_report/2 with valid data updates the report" do # report = report_fixture() # assert {:ok, %Report{} = report} = Websites.update_report(report, @update_attrs) # assert report.data == %{} # end test "update_report/2 with invalid data returns error changeset" do report = report_fixture() assert {:error, %Ecto.Changeset{}} = Websites.update_report(report, @invalid_attrs) assert unload_relations(report) == unload_relations(Websites.get_report!(report.id)) end test "delete_report/1 deletes the report" do report = report_fixture() assert {:ok, %Report{}} = Websites.delete_report(report) assert_raise Ecto.NoResultsError, fn -> Websites.get_report!(report.id) end end test "change_report/1 returns a report changeset" do report = report_fixture() assert %Ecto.Changeset{} = Websites.change_report(report) end end end
31.449782
93
0.650514
79dc77e66160d1d76eb30d2e78cdf480cd7e4d18
10,155
exs
Elixir
priv/repo/seeds.exs
OpenFermentor/Local-Monitor
4b356e8ac3f154ec72bdd23b3a501d5f1645241c
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
OpenFermentor/Local-Monitor
4b356e8ac3f154ec72bdd23b3a501d5f1645241c
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
OpenFermentor/Local-Monitor
4b356e8ac3f154ec72bdd23b3a501d5f1645241c
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # BioMonitor.Repo.insert!(%BioMonitor.SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. routine = BioMonitor.Routine.changeset(%BioMonitor.Routine{}, %{ title: "Fermentación E.Coli en medio de hongos", estimated_time_seconds: 28_800_000, extra_notes: "Fermentación de prueba para el fermentador automatizado.", medium: "Medio de nutrientes consistente de hongos", strain: "E.Coli 123", target_ph: 6, target_temp: 35, target_density: 0, balance_ph: true, loop_delay: 900_000, triger_after: 7_200_000, trigger_for: 60_000, temp_ranges: [ %{ temp: 38, from_second: 3600 }, %{ temp: 32, from_second: 7200 } ], tags: [ %{value: "E.Coli"}, %{value: "Juan"}] }) |> BioMonitor.Repo.insert!() routine = routine |> BioMonitor.Repo.preload([:temp_ranges, :tags, :log_entries, :readings]) BioMonitor.Routine.started_changeset(routine, %{started: true, started_date: DateTime.utc_now}) |> BioMonitor.Repo.update!() # ==================== 1st hour =================================== :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 31, ph: 6, biomass: 20, substratum: 23, product: 34 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por debajo del rango establecido.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 21, substratum: 22, product: 37 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por debajo del rango establecido.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 34, ph: 6, }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por debajo del rango establecido.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 35, ph: 6, biomass: 25, substratum: 29, product: 20 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.temp_change, "Cambio de temperatura objetivo a 37 grados.") :timer.sleep(5000) # ============================ 2nd hour ================================================================================================ BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 36, ph: 6, biomass: 30, substratum: 33, product: 36 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por debajo del rango establecido.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 36.5, ph: 6, biomass: 35, substratum: 36, product: 38 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por debajo del rango establecido.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 37, ph: 6, biomass: 40, substratum: 39, product: 40 }) |> BioMonitor.Repo.insert!() BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 37, ph: 5, biomass: 45, substratum: 39, product: 40 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "El ph esta por debajo del rango establecido.") BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.base_cal, "Balanceando el ph a base.") BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.temp_change, "Cambio de temperatura objetivo a 32 grados.") :timer.sleep(5000) # ======================== 3rd hour =============================================== BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 35, ph: 5.5, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por encima del rango establecido.") BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "El ph esta por debajo del rango establecido.") BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.base_cal, "Balanceando el ph a base.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 34.5, ph: 5.8, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por encima del rango establecido.") BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "El ph esta por debajo del rango establecido.") BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.base_cal, "Balanceando el ph a base.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 33, ph: 6.1, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() BioMonitor.Routine.log_entry(routine, BioMonitor.Routine.log_types.reading_error, "La temperatura esta por encima del rango establecido.") :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32.5, ph: 6.1, biomass: 51, substratum: 41, product: 42 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) # =============== 4th hour ===================================== BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) # =============== 5th hour ===================================== BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) # =============== 6th hour ===================================== BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 50, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) # =============== 7th hour ===================================== BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 45, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 40, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 38, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, biomass: 36, substratum: 40, product: 41 }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) # =============== 8th hour ===================================== BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, }) |> BioMonitor.Repo.insert!() :timer.sleep(5000) BioMonitor.Reading.changeset(%BioMonitor.Reading{}, %{ routine_id: routine.id, temp: 32, ph: 6, }) |> BioMonitor.Repo.insert!()
25.261194
138
0.670704
79dc85a0fb41a17ab1f2e28e195b196c4782f352
1,298
ex
Elixir
lib/rak/module/instance.ex
rak/rak
cdfcd7227b38d9c6cac10bd778b03361b28f67df
[ "MIT" ]
2
2018-09-30T02:59:33.000Z
2018-10-08T19:55:38.000Z
lib/rak/module/instance.ex
rak/rak
cdfcd7227b38d9c6cac10bd778b03361b28f67df
[ "MIT" ]
null
null
null
lib/rak/module/instance.ex
rak/rak
cdfcd7227b38d9c6cac10bd778b03361b28f67df
[ "MIT" ]
null
null
null
defmodule Rak.Module.Instance do @moduledoc """ Defines the behavior expected from Rak module instances. Module instances can represent one of the following: 1. A *sharding unit*, which takes care offloading asynchronous operations; 2. An *isolation unit*, responsible of preserving a certain state that concerns only a certain number of players; 3. A *logical unit*, responsible of separating code into clearly defined concerns; Module instances are often GenServers, but may also be Rak modules themselves in certain cases; thanks to this, you may use Rak modules to create supervision trees as deep as you may like. """ @callback create(config :: any, supervise? :: boolean) :: pid @callback get(hashkey :: any, create? :: boolean) :: pid @callback destroy(pid) :: nil defmacro __using__(config) do state = get_state(config[:state]) quote do use GenServer import Supervisor.Spec @behaviour Rak.Module.Instance def child_spec(args), do: worker(__MODULE__, args) def start_link(args) do GenServer.start_link(__MODULE__, args, name: __MODULE__) end def init(_), do: {:ok, unquote(state)} end end defp get_state(nil), do: %{} defp get_state(state), do: state end
28.217391
64
0.691063
79dcd1de9e3a75cf59fd352af2188b76171d0e3a
2,787
ex
Elixir
deps/credo/lib/credo/check/warning/lazy_logging.ex
BandanaPandey/nary_tree
fb1eeb69e38e43c9f9ffb54297cef52dff5c928d
[ "MIT" ]
13
2018-09-19T21:03:29.000Z
2022-01-27T04:06:32.000Z
deps/credo/lib/credo/check/warning/lazy_logging.ex
BandanaPandey/nary_tree
fb1eeb69e38e43c9f9ffb54297cef52dff5c928d
[ "MIT" ]
1
2020-05-26T04:16:57.000Z
2020-05-26T04:16:57.000Z
deps/credo/lib/credo/check/warning/lazy_logging.ex
BandanaPandey/nary_tree
fb1eeb69e38e43c9f9ffb54297cef52dff5c928d
[ "MIT" ]
3
2020-05-21T04:32:08.000Z
2021-07-28T05:14:01.000Z
defmodule Credo.Check.Warning.LazyLogging do @moduledoc """ Ensures laziness of Logger calls. You will want to wrap expensive logger calls into a zero argument function (`fn -> "string that gets logged" end`). Example: # preferred Logger.debug fn -> "This happened: \#{expensive_calculation(arg1, arg2)}" end # NOT preferred # the interpolation is executed whether or not the info is logged Logger.debug "This happened: \#{expensive_calculation(arg1, arg2)}" """ @explanation [ check: @moduledoc, params: [ ignore: "Do not raise an issue for these Logger calls." ] ] @logger_functions [:debug, :info, :warn, :error] @default_params [ ignore: [:error, :warn, :info] ] use Credo.Check, base_priority: :high @doc false def run(source_file, params \\ []) do issue_meta = IssueMeta.for(source_file, params) state = {false, []} # {<Logger import seen?>, <list of issues>} {_, issues} = Credo.Code.prewalk(source_file, &traverse(&1, &2, issue_meta), state) issues end defp traverse({{:., _, [{:__aliases__, _, [:Logger]}, fun_name]}, meta, arguments} = ast, state, issue_meta) when fun_name in @logger_functions do issue = find_issue(fun_name, arguments, meta, issue_meta) {ast, add_issue_to_state(state, issue)} end defp traverse({fun_name, meta, arguments} = ast, {true, _issues} = state, issue_meta) when fun_name in @logger_functions do issue = find_issue(fun_name, arguments, meta, issue_meta) {ast, add_issue_to_state(state, issue)} end defp traverse({:import, _meta, arguments} = ast, {_module_contains_import?, issues} = state, _issue_meta) do if logger_import?(arguments) do {ast, {true, issues}} else {ast, state} end end defp traverse(ast, state, _issue_meta) do {ast, state} end defp add_issue_to_state(state, nil), do: state defp add_issue_to_state({module_contains_import?, issues}, issue) do {module_contains_import?, [issue | issues]} end defp find_issue(fun_name, arguments, meta, issue_meta) do params = IssueMeta.params(issue_meta) ignored_functions = Params.get(params, :ignore, @default_params) unless Enum.member?(ignored_functions, fun_name) do issue_for_call(arguments, meta, issue_meta) end end defp issue_for_call([{:<<>>, _, [_ | _]} | _] = _args, meta, issue_meta) do issue_for(issue_meta, meta[:line]) end defp issue_for_call(_args, _meta, _issue_meta) do nil end defp logger_import?([{:__aliases__, _meta, [:Logger]}]), do: true defp logger_import?(_), do: false defp issue_for(issue_meta, line_no) do format_issue issue_meta, message: "Prefer lazy Logger calls.", line_no: line_no end end
28.731959
148
0.673843
79dcdc120ba8d30bc0d470ab96d37409e79ed514
2,433
ex
Elixir
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_transformation_error_handling.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_transformation_error_handling.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dlp/lib/google_api/dlp/v2/model/google_privacy_dlp_v2_transformation_error_handling.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.DLP.V2.Model.GooglePrivacyDlpV2TransformationErrorHandling do @moduledoc """ How to handle transformation errors during de-identification. A transformation error occurs when the requested transformation is incompatible with the data. For example, trying to de-identify an IP address using a `DateShift` transformation would result in a transformation error, since date info cannot be extracted from an IP address. Information about any incompatible transformations, and how they were handled, is returned in the response as part of the `TransformationOverviews`. ## Attributes * `leaveUntransformed` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2LeaveUntransformed.t`, *default:* `nil`) - Ignore errors * `throwError` (*type:* `GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ThrowError.t`, *default:* `nil`) - Throw an error """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :leaveUntransformed => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2LeaveUntransformed.t() | nil, :throwError => GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ThrowError.t() | nil } field(:leaveUntransformed, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2LeaveUntransformed) field(:throwError, as: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2ThrowError) end defimpl Poison.Decoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2TransformationErrorHandling do def decode(value, options) do GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2TransformationErrorHandling.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DLP.V2.Model.GooglePrivacyDlpV2TransformationErrorHandling do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
47.705882
487
0.774353
79dce400cd84ee893fa665dd8327401daaedec3a
739
ex
Elixir
lib/error_messages.ex
steven-solomon/exdoubles
9650dcf75775de492141648fcee39c3317f722ae
[ "Apache-2.0" ]
1
2019-11-08T21:02:59.000Z
2019-11-08T21:02:59.000Z
lib/error_messages.ex
steven-solomon/elephant
9650dcf75775de492141648fcee39c3317f722ae
[ "Apache-2.0" ]
5
2019-11-08T21:05:31.000Z
2019-12-07T03:41:42.000Z
lib/error_messages.ex
steven-solomon/exdoubles
9650dcf75775de492141648fcee39c3317f722ae
[ "Apache-2.0" ]
1
2019-10-23T18:13:06.000Z
2019-10-23T18:13:06.000Z
defmodule ExDoubles.ErrorMessages do def not_called_error(name, args, []) do "#{inspect name} was never called with #{inspect args}" end def not_called_error(name, args, calls) do """ #{inspect name} was never called with #{inspect args} but was called with: #{format_calls(calls)} """ end def arity_not_supported do "Arity greater than 6 is not supported." end def unsupported_call() do "called_with cannot have more arguments than the mocked function." end def call_count_incorrect(expected, actual) do "expected #{expected} times but was #{actual}" end defp format_calls(calls) do calls |> Enum.map(fn call -> "#{inspect call}" end) |> Enum.join("\n") end end
23.83871
70
0.67253
79dd0d39cb892b1f7fd63bed81cbef5cb9a8da38
1,239
exs
Elixir
2020/liveview/dazzle/config/prod.secret.exs
herminiotorres/programmer_passport
d1786518a3a5f82471457e0ace41c4c33343739a
[ "MIT" ]
null
null
null
2020/liveview/dazzle/config/prod.secret.exs
herminiotorres/programmer_passport
d1786518a3a5f82471457e0ace41c4c33343739a
[ "MIT" ]
null
null
null
2020/liveview/dazzle/config/prod.secret.exs
herminiotorres/programmer_passport
d1786518a3a5f82471457e0ace41c4c33343739a
[ "MIT" ]
null
null
null
# In this file, we load production configuration and secrets # from environment variables. You can also hardcode secrets, # although such is generally not recommended and you have to # remember to add this file to your .gitignore. use Mix.Config database_url = System.get_env("DATABASE_URL") || raise """ environment variable DATABASE_URL is missing. For example: ecto://USER:PASS@HOST/DATABASE """ config :dazzle, Dazzle.Repo, # ssl: true, url: database_url, pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10") secret_key_base = System.get_env("SECRET_KEY_BASE") || raise """ environment variable SECRET_KEY_BASE is missing. You can generate one by calling: mix phx.gen.secret """ config :dazzle, DazzleWeb.Endpoint, http: [ port: String.to_integer(System.get_env("PORT") || "4000"), transport_options: [socket_opts: [:inet6]] ], secret_key_base: secret_key_base # ## Using releases (Elixir v1.9+) # # If you are doing OTP releases, you need to instruct Phoenix # to start each relevant endpoint: # # config :dazzle, DazzleWeb.Endpoint, server: true # # Then you can assemble a release by calling `mix release`. # See `mix help release` for more information.
29.5
67
0.717514
79dd564db96e3a227977634d971f1cfacefe7f7a
1,544
ex
Elixir
2020/liveview/dazzle/lib/dazzle_web/views/error_helpers.ex
herminiotorres/programmer_passport
d1786518a3a5f82471457e0ace41c4c33343739a
[ "MIT" ]
null
null
null
2020/liveview/dazzle/lib/dazzle_web/views/error_helpers.ex
herminiotorres/programmer_passport
d1786518a3a5f82471457e0ace41c4c33343739a
[ "MIT" ]
null
null
null
2020/liveview/dazzle/lib/dazzle_web/views/error_helpers.ex
herminiotorres/programmer_passport
d1786518a3a5f82471457e0ace41c4c33343739a
[ "MIT" ]
null
null
null
defmodule DazzleWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "invalid-feedback", phx_feedback_for: input_id(form, field) ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(DazzleWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(DazzleWeb.Gettext, "errors", msg, opts) end end end
32.166667
75
0.664508
79dd93154ecfe2198be23c46b24ef4a2f6747e29
65
ex
Elixir
apps/grenadier/lib/grenadier_web/views/page_view.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
4
2019-10-04T16:11:15.000Z
2021-08-18T21:00:13.000Z
apps/grenadier/lib/grenadier_web/views/page_view.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
5
2020-03-16T23:52:25.000Z
2021-09-03T16:52:17.000Z
apps/grenadier/lib/grenadier_web/views/page_view.ex
allen-garvey/phoenix-umbrella
1d444bbd62a5e7b5f51d317ce2be71ee994125d5
[ "MIT" ]
null
null
null
defmodule GrenadierWeb.PageView do use GrenadierWeb, :view end
16.25
34
0.815385
79dd9f5fc42fd1d09cabfa066f43e59a40b8ec3e
1,351
ex
Elixir
apps/admin_api/lib/admin_api/v1/plugs/admin_api_auth_plug.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
1
2018-12-07T06:21:21.000Z
2018-12-07T06:21:21.000Z
apps/admin_api/lib/admin_api/v1/plugs/admin_api_auth_plug.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
apps/admin_api/lib/admin_api/v1/plugs/admin_api_auth_plug.ex
vanmil/ewallet
6c1aca95a83e0a9d93007670a40d8c45764a8122
[ "Apache-2.0" ]
null
null
null
defmodule AdminAPI.V1.AdminAPIAuthPlug do @moduledoc """ This module is responsible for dispatching the authentication of the given request to the appropriate authentication plug based on the provided scheme. """ import Plug.Conn import AdminAPI.V1.ErrorHandler alias AdminAPI.V1.AdminAPIAuth def init(opts), do: opts def call(conn, _opts) do %{headers: conn.req_headers} |> AdminAPIAuth.authenticate() |> handle_auth_result(conn) end defp handle_auth_result(%{authenticated: false} = auth, conn) do conn |> assign(:authenticated, false) |> handle_error(auth[:auth_error]) end defp handle_auth_result( %{authenticated: true, auth_scheme: :admin, admin_user: admin_user} = auth, conn ) do conn |> assign(:authenticated, true) |> assign(:auth_scheme, :admin) |> assign(:admin_user, admin_user) |> put_private(:auth_user_id, auth[:auth_user_id]) |> put_private(:auth_auth_token, auth[:auth_auth_token]) end defp handle_auth_result(%{authenticated: true, auth_scheme: :provider, key: key} = auth, conn) do conn |> assign(:authenticated, true) |> assign(:auth_scheme, :provider) |> assign(:key, key) |> put_private(:auth_access_key, auth[:auth_access_key]) |> put_private(:auth_secret_key, auth[:auth_secret_key]) end end
30.022222
99
0.694301
79ddb11b7b7aec22801416b7f7fc76e6040aeb5d
4,875
ex
Elixir
lib/protobuf/wire.ex
wojtekmach/protobuf
3b251d286dc94745fc6a92fcbf9be03f44bb9b46
[ "MIT" ]
null
null
null
lib/protobuf/wire.ex
wojtekmach/protobuf
3b251d286dc94745fc6a92fcbf9be03f44bb9b46
[ "MIT" ]
null
null
null
lib/protobuf/wire.ex
wojtekmach/protobuf
3b251d286dc94745fc6a92fcbf9be03f44bb9b46
[ "MIT" ]
null
null
null
defmodule Protobuf.Wire do @moduledoc """ Utilities to convert data from wire format to protobuf and back. """ alias Protobuf.Wire.{Varint, Zigzag} require Logger @type proto_type :: :int32 | :int64 | :fixed32 | :fixed64 | :uint32 | :uint64 | :sfixed32 | :sfixed64 | :sint32 | :sint64 | :float | :double | :bool | :string | :bytes | {:enum, any} @type proto_float :: :infinity | :negative_infinity | :nan | float @type proto_value :: binary | integer | boolean | proto_float | atom @sint32_range -0x80000000..0x7FFFFFFF @sint64_range -0x8000000000000000..0x7FFFFFFFFFFFFFFF @uint32_range 0..0xFFFFFFFF @uint64_range 0..0xFFFFFFFFFFFFFFFF @spec from_proto(proto_type, proto_value) :: iodata # Returns improper list, but still valid iodata. def from_proto(type, binary) when type in [:string, :bytes] do len = binary |> IO.iodata_length() |> Varint.encode() len ++ binary end def from_proto(:int32, n) when n in @sint32_range, do: Varint.encode(n) def from_proto(:int64, n) when n in @sint64_range, do: Varint.encode(n) def from_proto(:uint32, n) when n in @uint32_range, do: Varint.encode(n) def from_proto(:uint64, n) when n in @uint64_range, do: Varint.encode(n) def from_proto(:bool, true), do: Varint.encode(1) def from_proto(:bool, false), do: Varint.encode(0) def from_proto({:enum, enum}, key) when is_atom(key), do: Varint.encode(enum.value(key)) def from_proto({:enum, _}, n) when is_integer(n), do: Varint.encode(n) def from_proto(:float, :infinity), do: [0, 0, 128, 127] def from_proto(:float, :negative_infinity), do: [0, 0, 128, 255] def from_proto(:float, :nan), do: [0, 0, 192, 127] def from_proto(:float, n), do: <<n::32-float-little>> def from_proto(:double, :infinity), do: [0, 0, 0, 0, 0, 0, 240, 127] def from_proto(:double, :negative_infinity), do: [0, 0, 0, 0, 0, 0, 240, 255] def from_proto(:double, :nan), do: [1, 0, 0, 0, 0, 0, 248, 127] def from_proto(:double, n), do: <<n::64-float-little>> def from_proto(:sint32, n) when n in @sint32_range, do: Varint.encode(Zigzag.encode(n)) def from_proto(:sint64, n) when n in @sint64_range, do: Varint.encode(Zigzag.encode(n)) def from_proto(:fixed32, n) when n in @uint32_range, do: <<n::32-little>> def from_proto(:fixed64, n) when n in @uint64_range, do: <<n::64-little>> def from_proto(:sfixed32, n) when n in @sint32_range, do: <<n::32-signed-little>> def from_proto(:sfixed64, n) when n in @sint64_range, do: <<n::64-signed-little>> def from_proto(type, n) do raise Protobuf.TypeEncodeError, message: "#{inspect(n)} is invalid for type #{type}" end @spec to_proto(proto_type, binary | integer) :: proto_value def to_proto(type, val) when type in [:string, :bytes], do: val def to_proto(:int32, val) do <<n::signed-integer-32>> = <<val::32>> n end def to_proto(:int64, val) do <<n::signed-integer-64>> = <<val::64>> n end def to_proto(:uint32, val) do <<n::unsigned-integer-32>> = <<val::32>> n end def to_proto(:uint64, val) do <<n::unsigned-integer-64>> = <<val::64>> n end def to_proto(:bool, val), do: val != 0 def to_proto({:enum, enum}, val) do enum.key(val) rescue FunctionClauseError -> Logger.warn("unknown enum value #{val} when decoding for #{inspect(enum)}") val end def to_proto(:float, <<n::little-float-32>>), do: n # little endianness, should be 0b0_11111111_000000000... def to_proto(:float, <<0, 0, 0b1000_0000::8, 0b01111111::8>>), do: :infinity # little endianness, should be 0b1_11111111_000000000... def to_proto(:float, <<0, 0, 0b1000_0000::8, 0b11111111::8>>), do: :negative_infinity # should be 0b*_11111111_not_zero... def to_proto(:float, <<a::16, 1::1, b::7, _::1, 0b1111111::7>>) when a != 0 or b != 0, do: :nan def to_proto(:double, <<n::little-float-64>>), do: n # little endianness, should be 0b0_11111111111_000000000... def to_proto(:double, <<0::48, 0b1111::4, 0::4, 0b01111111::8>>), do: :infinity # little endianness, should be 0b1_11111111111_000000000... def to_proto(:double, <<0::48, 0b1111::4, 0::4, 0b11111111::8>>), do: :negative_infinity def to_proto(:double, <<a::48, 0b1111::4, b::4, _::1, 0b1111111::7>>) when a != 0 or b != 0, do: :nan def to_proto(type, val) when type in [:sint32, :sint64], do: Zigzag.decode(val) def to_proto(:fixed32, <<n::little-32>>), do: n def to_proto(:fixed64, <<n::little-64>>), do: n def to_proto(:sfixed32, <<n::little-signed-32>>), do: n def to_proto(:sfixed64, <<n::little-signed-64>>), do: n def to_proto(type, val) do raise Protobuf.DecodeError, message: "can't decode #{inspect(val)} into type #{type}" end end
35.583942
94
0.636718
79dddee16bbbe240da75b16529f02029a4a46b05
1,254
ex
Elixir
clients/dns/lib/google_api/dns/v1/model/resource_record_sets_delete_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dns/lib/google_api/dns/v1/model/resource_record_sets_delete_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dns/lib/google_api/dns/v1/model/resource_record_sets_delete_response.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DNS.V1.Model.ResourceRecordSetsDeleteResponse do @moduledoc """ ## Attributes """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{} end defimpl Poison.Decoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsDeleteResponse do def decode(value, options) do GoogleApi.DNS.V1.Model.ResourceRecordSetsDeleteResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsDeleteResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
29.857143
87
0.767145
79de14081ee89e295807a19eb1b19e052fd5e8e6
91
ex
Elixir
lib/bitcoin_simulator_web/views/blockchain_viewer_view.ex
hojason117/BitcoinSimulator
f85e623eec1923a2c0d418388f440cc06b6a5283
[ "MIT" ]
1
2021-12-16T08:31:24.000Z
2021-12-16T08:31:24.000Z
lib/bitcoin_simulator_web/views/blockchain_viewer_view.ex
hojason117/BitcoinSimulator
f85e623eec1923a2c0d418388f440cc06b6a5283
[ "MIT" ]
null
null
null
lib/bitcoin_simulator_web/views/blockchain_viewer_view.ex
hojason117/BitcoinSimulator
f85e623eec1923a2c0d418388f440cc06b6a5283
[ "MIT" ]
null
null
null
defmodule BitcoinSimulatorWeb.BlockchainViewerView do use BitcoinSimulatorWeb, :view end
22.75
53
0.868132
79de3d52a47cc743efb479cf07e010a6885d858b
1,995
ex
Elixir
lib/trot/auth_check.ex
Tony1928/trot
0b4a0faff6fc6eca1cc14e35bcdef45127a7cbb5
[ "Apache-2.0" ]
442
2015-05-20T14:41:34.000Z
2022-02-26T05:41:02.000Z
lib/trot/auth_check.ex
Tony1928/trot
0b4a0faff6fc6eca1cc14e35bcdef45127a7cbb5
[ "Apache-2.0" ]
35
2015-05-20T09:45:23.000Z
2019-10-08T06:13:14.000Z
lib/trot/auth_check.ex
Tony1928/trot
0b4a0faff6fc6eca1cc14e35bcdef45127a7cbb5
[ "Apache-2.0" ]
32
2015-05-26T20:24:48.000Z
2022-02-25T13:31:36.000Z
defmodule Trot.AuthCheck do @moduledoc """ Checks that a user has an authorized session before allowing them to access certain routes. By default, all routes are allowed. ## Options `routes`: List of URLs to check authorization on. Defaults to `[]`. `match_fun`: Function to run when a request matches the routes. Defaults to returning a 403. `match_default`: Function to run when a request does not match any configured routes. Defaults to passing the connection through. ## Example: defmodule PiedPiper do use Plug.Builder plug Trot.AuthCheck, [routes: ["/secrets"]] use Trot.AuthCheck get "/marketing", do: "We are amazing, srsly you guys." get "/secrets", do: "We're actually about to go bankrupt" end """ import Plug.Conn @behaviour Plug @doc false def init(opts) do routes = opts |> Keyword.get(:routes, []) |> Enum.map(fn(route) -> route |> Plug.Router.Utils.build_path_match |> elem(1) end) opts |> Keyword.put(:routes, routes) |> Keyword.put_new(:match_fun, &__MODULE__.private_route/1) |> Keyword.put_new(:default_fun, &__MODULE__.public_route/1) end @doc false def call(conn, opts) do conn.path_info |> Enum.map(&URI.decode/1) |> check_route(opts[:routes], opts, conn) end defp check_route(_, [], opts, conn), do: apply(opts[:default_fun], [conn]) defp check_route(path, [path | _], opts, conn), do: apply(opts[:match_fun], [conn]) defp check_route(path, [_ | routes], opts, conn), do: check_route(path, routes, opts, conn) @doc """ Called when a given route is publicly accessible. This will simply pass the connection through to the next plug. """ def public_route(conn), do: conn @doc """ Called when a route needs to be authenticated. Returns a 403 if there is no authentication, and passes the conn through untouched otherwise. """ def private_route(conn) do conn |> send_resp(403, "") |> halt end end
30.692308
131
0.671679
79de3f1b19b36a650f81f32bca3c00fea4335e8f
4,026
ex
Elixir
lib/explorer/backend/series.ex
srowley/explorer
f17dd01d0b60f7d00718c94a8b0779befb1c8e82
[ "MIT" ]
null
null
null
lib/explorer/backend/series.ex
srowley/explorer
f17dd01d0b60f7d00718c94a8b0779befb1c8e82
[ "MIT" ]
null
null
null
lib/explorer/backend/series.ex
srowley/explorer
f17dd01d0b60f7d00718c94a8b0779befb1c8e82
[ "MIT" ]
null
null
null
defmodule Explorer.Backend.Series do @moduledoc """ The behaviour for series backends. """ @type t :: struct() @type s :: Explorer.Series.t() @type df :: Explorer.DataFrame.t() @type dtype :: :integer | :float | :boolean | :string | :date | :datetime # Conversion @callback from_list(list(), dtype()) :: s @callback to_list(s) :: list() @callback to_enum(s) :: Enumerable.t() @callback cast(s, dtype) :: s # Introspection @callback dtype(s) :: dtype() @callback size(s) :: integer() @callback inspect(s, opts :: Inspect.Opts.t()) :: Inspect.Algebra.t() # Slice and dice @callback head(s, n :: integer()) :: s @callback tail(s, n :: integer()) :: s @callback sample(s, n :: integer(), replacement :: boolean(), seed :: integer()) :: s @callback take_every(s, integer()) :: s @callback filter(s, mask :: s) :: s @callback filter(s, function()) :: s @callback slice(s, offset :: integer(), length :: integer()) :: s @callback take(s, indices :: list()) :: s @callback get(s, idx :: integer()) :: s @callback concat(s, s) :: s @callback coalesce(s, s) :: s # Aggregation @callback sum(s) :: number() @callback min(s) :: number() | Date.t() | NaiveDateTime.t() @callback max(s) :: number() | Date.t() | NaiveDateTime.t() @callback mean(s) :: float() @callback median(s) :: float() @callback var(s) :: float() @callback std(s) :: float() @callback quantile(s, float()) :: number | Date.t() | NaiveDateTime.t() # Cumulative @callback cumulative_max(s, reverse? :: boolean()) :: s @callback cumulative_min(s, reverse? :: boolean()) :: s @callback cumulative_sum(s, reverse? :: boolean()) :: s # Local minima/maxima @callback peaks(s, :max | :min) :: s # Arithmetic @callback add(s, s | number()) :: s @callback subtract(s, s | number()) :: s @callback multiply(s, s | number()) :: s @callback divide(s, s | number()) :: s @callback pow(s, number()) :: s # Comparisons @callback eq(s, s | number()) :: s @callback neq(s, s | number()) :: s @callback gt(s, s | number()) :: s @callback gt_eq(s, s | number()) :: s @callback lt(s, s | number()) :: s @callback lt_eq(s, s | number()) :: s @callback all_equal?(s, s) :: boolean() @callback binary_and(s, s) :: s @callback binary_or(s, s) :: s # Coercion # Sort @callback sort(s, reverse? :: boolean()) :: s @callback argsort(s, reverse? :: boolean()) :: s @callback reverse(s) :: s # Distinct @callback distinct(s) :: s @callback unordered_distinct(s) :: s @callback n_distinct(s) :: integer() @callback count(s) :: df # Rolling @type window_option :: {:weights, [float()] | nil} | {:min_periods, integer() | nil} | {:center, boolean()} @callback window_sum(s, window_size :: integer(), [window_option()]) :: s @callback window_min(s, window_size :: integer(), [window_option()]) :: s @callback window_max(s, window_size :: integer(), [window_option()]) :: s @callback window_mean(s, window_size :: integer(), [window_option()]) :: s # Nulls @callback fill_missing(s, strategy :: :backward | :forward | :min | :max | :mean) :: s @callback nil?(s) :: s @callback not_nil?(s) :: s # Escape hatch @callback transform(s, fun) :: s | list() # Functions import Inspect.Algebra alias Explorer.Series @doc """ Default inspect implementation for backends. """ def inspect(series, backend, n_rows, inspect_opts, opts \\ []) when is_binary(backend) and (is_integer(n_rows) or is_nil(n_rows)) and is_list(opts) do open = color("[", :list, inspect_opts) close = color("]", :list, inspect_opts) dtype = color("#{Series.dtype(series)}", :atom, inspect_opts) data = container_doc( open, series |> Series.slice(0, inspect_opts.limit + 1) |> Series.to_list(), close, inspect_opts, &Explorer.Shared.to_string/2 ) concat([dtype, open, "#{n_rows || "???"}", close, line(), data]) end end
27.958333
93
0.60159
79de4dea9b0b8b1925c5fd86bffe2b6fe1ff7b13
1,007
ex
Elixir
lib/nostrum/struct/embed/thumbnail.ex
defnorep/nostrum
daf869afc0f98fd132460296a2c999fea033fd63
[ "MIT" ]
null
null
null
lib/nostrum/struct/embed/thumbnail.ex
defnorep/nostrum
daf869afc0f98fd132460296a2c999fea033fd63
[ "MIT" ]
null
null
null
lib/nostrum/struct/embed/thumbnail.ex
defnorep/nostrum
daf869afc0f98fd132460296a2c999fea033fd63
[ "MIT" ]
null
null
null
defmodule Nostrum.Struct.Embed.Thumbnail do @moduledoc """ Struct representing a Discord embed thumbnail. """ alias Nostrum.Util defstruct [ :url, :proxy_url, :height, :width ] defimpl Poison.Encoder do def encode(thumbnail, options) do thumbnail |> Map.from_struct() |> Enum.filter(fn {_, v} -> v != nil end) |> Map.new() |> Poison.Encoder.encode(options) end end @typedoc "Source URL of the thumbnail" @type url :: String.t() | nil @typedoc "URL of thumbnail icon" @type proxy_url :: String.t() | nil @typedoc "Height of the thumbnail" @type height :: integer | nil @typedoc "Width of the thumbnail" @type width :: integer | nil @type t :: %__MODULE__{ url: url, proxy_url: proxy_url, height: height, width: width } @doc false def to_struct(map) do new = Map.new(map, fn {k, v} -> {Util.maybe_to_atom(k), v} end) struct(__MODULE__, new) end end
19.745098
67
0.597815
79de601182e2b4f72f3d39f891667449aa24b3a5
5,396
ex
Elixir
lib/versioned/helpers.ex
rossvz/versioned
22fd40ce7833d0ede80ac9c3dd2e2b8482b50322
[ "MIT" ]
null
null
null
lib/versioned/helpers.ex
rossvz/versioned
22fd40ce7833d0ede80ac9c3dd2e2b8482b50322
[ "MIT" ]
null
null
null
lib/versioned/helpers.ex
rossvz/versioned
22fd40ce7833d0ede80ac9c3dd2e2b8482b50322
[ "MIT" ]
null
null
null
defmodule Versioned.Helpers do @moduledoc "Tools shared between modules. (For internal use.)" alias Ecto.{Changeset, Schema} @doc "Wrap a line of AST in a block if it isn't already wrapped." @spec normalize_block(Macro.t()) :: Macro.t() def normalize_block({x, m, _} = line) when x != :__block__, do: {:__block__, m, [line]} def normalize_block(block), do: block @doc """ Create a `version_mod` struct to insert from a new instance of the record. ## Options * `:deleted` - If `true`, records will marked as deleted. * `:change` - For updates, an `t:Ecto.Changeset.t/0` should be provided to inform which records were inserted vs updated vs deleted. """ @spec build_version(Schema.t(), keyword) :: Changeset.t() | nil def build_version(%mod{} = struct, opts) do with params when params != nil <- build_params(struct, opts) do mod |> Module.concat(Version) |> struct() |> Changeset.change(params) end end @doc """ Recursively crawl changeset and compile a list of version structs with is_deleted set to true. """ @spec deleted_versions(Changeset.t(), keyword) :: [Ecto.Schema.t()] def deleted_versions(%{action: action, data: %mod{}} = changeset, opts) do deletes = if action == :replace do changeset |> Changeset.apply_changes() |> maybe_build_version_params(Keyword.put(opts, :deleted, true)) |> case do nil -> [] params -> [struct(Module.concat(mod, Version), params)] end else [] end Enum.reduce(mod.__schema__(:associations), deletes, fn assoc, acc -> %{cardinality: cardinality} = mod.__schema__(:association, assoc) change = Changeset.get_change(changeset, assoc) case {cardinality, change} do {_, nil} -> acc {:one, change} -> acc ++ deleted_versions(change, opts) {:many, changes} -> acc ++ Enum.flat_map(changes, &deleted_versions(&1, opts)) end end) end @spec build_params(Schema.t(), keyword) :: map | nil defp build_params(%mod{} = struct, opts) do with params when params != nil <- maybe_build_version_params(struct, opts) do Enum.reduce(mod.__schema__(:associations), params, fn assoc_name, acc -> :association |> mod.__schema__(assoc_name) |> do_build_params(struct, opts, acc) end) end end @spec do_build_params(Ecto.Association.t(), Schema.t(), keyword, map) :: map defp do_build_params( %{cardinality: cardinality, field: field, owner: owner, queryable: queryable} = assoc_info, struct, opts, acc ) do child = Map.get(struct, field) v? = Versioned.versioned?(queryable) finish = fn _, params, false -> Map.put(acc, field, params) ver_key, params, true -> Map.put(acc, ver_key, params) end case {cardinality, build_assoc_params(assoc_info, child, opts)} do {_, nil} -> acc {:one, params} -> finish.(:"#{field}_version", params, v?) {:many, list} -> finish.(owner.__versioned__(:has_many_field, field), list, v?) end end defp do_build_params(_, _, _, acc), do: acc # If the struct is versioned, build parameters for the corresponding version # record to insert. nil otherwise. @spec maybe_build_version_params(Schema.t(), keyword) :: map | nil defp maybe_build_version_params(%mod{} = struct, opts) do change = opts[:change] if Versioned.versioned?(mod) and (not is_map(change) or 0 < map_size(change.changes)) do :fields |> mod.__schema__() |> Enum.reject(&(&1 in [:id, :inserted_at, :updated_at])) |> Enum.filter(&(&1 in Module.concat(mod, Version).__schema__(:fields))) |> Map.new(&{&1, Map.get(struct, &1)}) |> Map.put(:"#{mod.__versioned__(:source_singular)}_id", struct.id) |> Map.put(:is_deleted, Keyword.get(opts, :deleted, false)) |> Map.put(:inserted_at, opts[:inserted_at]) else nil end end # Build parameters for an association if data is present. @spec build_assoc_params(Ecto.Association.t(), Schema.t() | [Schema.t()], keyword) :: list | nil defp build_assoc_params(_, %Ecto.Association.NotLoaded{}, _) do nil end defp build_assoc_params(%{cardinality: :one, field: field}, data, opts) do change = with %{} = cs <- opts[:change] do Changeset.get_change(cs, field) end build_params(data, Keyword.put(opts, :change, change)) end defp build_assoc_params(%{cardinality: :many, field: field}, data, opts) when is_list(data) do {inserted_params_list, change_fn} = with %{} = change <- opts[:change], cs_list when is_list(cs_list) <- Changeset.get_change(change, field) do change_fn = fn record -> Enum.find(cs_list, &(Changeset.get_field(&1, :id) == record.id)) end inserted_css = Enum.filter(cs_list, &(&1.action == :insert)) inserted_params_list = inserted_css |> Enum.map(&build_params(&1, opts)) |> Enum.filter(& &1) {inserted_params_list, change_fn} else true_or_nil -> {[], fn _ -> true_or_nil end} end Enum.reduce(data, inserted_params_list, fn record, acc -> case build_params(record, Keyword.put(opts, :change, change_fn.(record))) do nil -> acc params -> [params | acc] end end) end end
34.151899
98
0.630838
79de65c09b904faeb226996205e9a06d2e618cb4
1,556
exs
Elixir
test/resource/actions/read_test.exs
regularfellow/ash
179495fecb141e0eb8eaf35bbb4d04000eab694b
[ "MIT" ]
null
null
null
test/resource/actions/read_test.exs
regularfellow/ash
179495fecb141e0eb8eaf35bbb4d04000eab694b
[ "MIT" ]
null
null
null
test/resource/actions/read_test.exs
regularfellow/ash
179495fecb141e0eb8eaf35bbb4d04000eab694b
[ "MIT" ]
null
null
null
defmodule Ash.Test.Dsl.Resource.Actions.ReadTest do @moduledoc false use ExUnit.Case, async: true defmacrop defposts(do: body) do quote do defmodule Post do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets attributes do uuid_primary_key :id end unquote(body) end end end describe "representation" do test "it creates an action" do defposts do actions do defaults [] read :default end end assert [ %Ash.Resource.Actions.Read{ name: :default, primary?: true, type: :read } ] = Ash.Resource.actions(Post) end end describe "validation" do test "it fails if `name` is not an atom" do assert_raise( Ash.Error.Dsl.DslError, "[Ash.Resource.Dsl.Read]\n actions -> read -> default:\n expected :name to be an atom, got: \"default\"", fn -> defposts do actions do read "default" end end end ) end test "it fails if `primary?` is not a boolean" do assert_raise( Ash.Error.Dsl.DslError, "[Ash.Resource.Dsl.Read]\n actions -> read -> default:\n expected :primary? to be a boolean, got: 10", fn -> defposts do actions do read :default, primary?: 10 end end end ) end end end
22.228571
114
0.514139
79de675be4ea7d80516e18b6ca38c8cea593a6c6
731
ex
Elixir
lib/commanded/shredder/public_api/impl.ex
KazW/commanded-shredder-middleware
ab4494db84983acfe7cd2d47a9b81dbec7c36a9d
[ "MIT" ]
1
2020-07-30T18:40:11.000Z
2020-07-30T18:40:11.000Z
lib/commanded/shredder/public_api/impl.ex
KazW/commanded-shredder-middleware
ab4494db84983acfe7cd2d47a9b81dbec7c36a9d
[ "MIT" ]
null
null
null
lib/commanded/shredder/public_api/impl.ex
KazW/commanded-shredder-middleware
ab4494db84983acfe7cd2d47a9b81dbec7c36a9d
[ "MIT" ]
null
null
null
defmodule Commanded.Shredder.Impl do @type expiry :: NaiveDateTime.t() | nil @type error :: {:error, String.t()} @type key_return :: :ok | error @type crypto_return :: struct | error @callback create_encryption_key( encryption_key_uuid :: String.t(), expiry :: expiry ) :: key_return @callback update_encryption_key( encryption_key_uuid :: String.t(), expiry :: expiry ) :: key_return @callback encrypt_event( event :: struct, opts :: Keyword.t() ) :: crypto_return @callback decrypt_event( event :: struct, opts :: Keyword.t() ) :: crypto_return end
27.074074
48
0.547196
79de6b322521510ae0c560357d835118bc967971
451
exs
Elixir
test/models/column_test.exs
sahilpaudel/AfterGlow
0859ec14b47c8c5704cc8e5cba86d39aa258fff5
[ "MIT" ]
null
null
null
test/models/column_test.exs
sahilpaudel/AfterGlow
0859ec14b47c8c5704cc8e5cba86d39aa258fff5
[ "MIT" ]
null
null
null
test/models/column_test.exs
sahilpaudel/AfterGlow
0859ec14b47c8c5704cc8e5cba86d39aa258fff5
[ "MIT" ]
null
null
null
defmodule AfterGlow.ColumnTest do use AfterGlow.ModelCase alias AfterGlow.Column @valid_attrs %{name: "some content", type: "some content"} @invalid_attrs %{} test "changeset with valid attributes" do changeset = Column.changeset(%Column{}, @valid_attrs) assert changeset.valid? end test "changeset with invalid attributes" do changeset = Column.changeset(%Column{}, @invalid_attrs) refute changeset.valid? end end
23.736842
60
0.727273
79de91e81d01f853f5ea482290ba9b3ef49ddfde
1,491
ex
Elixir
examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.ex
RudolfMan/opentelemetry-erlang-contrib
44fd2a6871742380dd6adc112f9776cda501ff1f
[ "Apache-2.0" ]
null
null
null
examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.ex
RudolfMan/opentelemetry-erlang-contrib
44fd2a6871742380dd6adc112f9776cda501ff1f
[ "Apache-2.0" ]
null
null
null
examples/basic_phoenix_ecto/lib/demo_web/live/user_live/form_component.ex
RudolfMan/opentelemetry-erlang-contrib
44fd2a6871742380dd6adc112f9776cda501ff1f
[ "Apache-2.0" ]
1
2022-02-07T20:48:50.000Z
2022-02-07T20:48:50.000Z
defmodule DemoWeb.UserLive.FormComponent do use DemoWeb, :live_component alias Demo.Accounts @impl true def update(%{user: user} = assigns, socket) do changeset = Accounts.change_user(user) {:ok, socket |> assign(assigns) |> assign(:changeset, changeset)} end @impl true def handle_event("validate", %{"user" => user_params}, socket) do changeset = socket.assigns.user |> Accounts.change_user(user_params) |> Map.put(:action, :validate) {:noreply, assign(socket, :changeset, changeset)} end def handle_event("save", %{"user" => user_params}, socket) do save_user(socket, socket.assigns.action, user_params) end defp save_user(socket, :edit, user_params) do case Accounts.update_user(socket.assigns.user, user_params) do {:ok, _user} -> {:noreply, socket |> put_flash(:info, "User updated successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, :changeset, changeset)} end end defp save_user(socket, :new, user_params) do case Accounts.create_user(user_params) do {:ok, _user} -> {:noreply, socket |> put_flash(:info, "User created successfully") |> push_redirect(to: socket.assigns.return_to)} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, changeset: changeset)} end end end
26.625
67
0.636486
79dea5bc95a71295626eefcf705ade1d1e01f23d
1,741
ex
Elixir
lib/kube/worker.ex
satom99/kube
c71c11b50ef582f4e345f6668eef86b9ba156070
[ "Apache-2.0" ]
null
null
null
lib/kube/worker.ex
satom99/kube
c71c11b50ef582f4e345f6668eef86b9ba156070
[ "Apache-2.0" ]
1
2019-10-16T09:20:44.000Z
2019-10-16T09:20:44.000Z
lib/kube/worker.ex
satom99/kube
c71c11b50ef582f4e345f6668eef86b9ba156070
[ "Apache-2.0" ]
null
null
null
defmodule Kube.Worker do use GenServer alias Kube.Config def start_link(state) do GenServer.start_link(__MODULE__, state) end def init(state) do handle_info(:timeout, state) send(self(), :timeout) {:ok, state} end def handle_info(:timeout, state) do base = Config.master() token = Config.token() selector = Config.selector() namespace = Config.namespace() path = "api/v1/namespaces/#{namespace}/pods" final = "#{base}/#{path}?labelSelector=#{selector}" headers = [{'authorization', 'Bearer #{token}'}] options = [ssl: [verify: :verify_none]] request = {'https://#{final}', headers} :httpc.request(:get, request, options, []) |> handle_response |> Enum.filter(&healthy?/1) |> Enum.map(&to_node/1) |> Enum.each(&Node.connect/1) {:noreply, state, 5000} end defp handle_response({:ok, response}) do handle_response(response) end defp handle_response({:error, reason}) do raise List.to_string(reason) end defp handle_response({{_version, status, _reason}, _headers, body}) do handle_response({status, body}) end defp handle_response({200, body}) do Jason.decode!(body)["items"] end defp handle_response({status, body}) do reason = [status: status, body: body] handle_response({:error, reason}) end defp healthy?(%{"status" => %{"phase" => "Running", "containerStatuses" => containers}}) do containers |> Enum.reject(&healthy?/1) |> length == 0 end defp healthy?(%{"state" => %{"running" => _object}, "ready" => true}), do: true defp healthy?(_other), do: false defp to_node(%{"status" => %{"podIP" => ip}, "metadata" => %{"name" => name}}) do :"#{name}@#{ip}" end end
25.985075
93
0.626651
79deb8e254f63f8dff8b0b12078dbe74ecfd9e13
2,277
exs
Elixir
benchmark/queries.exs
amclain/jylis_ex
cff66a5881ebc1f76403e2b8a60fba25f5b73bec
[ "MIT" ]
3
2018-08-09T12:02:29.000Z
2019-12-08T21:10:17.000Z
benchmark/queries.exs
amclain/jylis_ex
cff66a5881ebc1f76403e2b8a60fba25f5b73bec
[ "MIT" ]
1
2018-08-06T17:10:13.000Z
2018-08-08T19:16:47.000Z
benchmark/queries.exs
amclain/jylis_ex
cff66a5881ebc1f76403e2b8a60fba25f5b73bec
[ "MIT" ]
null
null
null
defmodule Benchmark.Queries do def before_scenario(_) do {:ok, connection} = Jylis.start_link("jylis://localhost") connection end def after_scenario(connection) do connection |> Jylis.stop end def treg_set_get(connection) do {:ok, _} = connection |> Jylis.TREG.set("temperature", 68, 10) {:ok, _} = connection |> Jylis.TREG.get("temperature") connection end def tlog_ins_get(connection) do # TODO: increment timestamp ################################################ {:ok, _} = connection |> Jylis.TLOG.ins("temperature", 68, 10) {:ok, _} = connection |> Jylis.TLOG.get("temperature") connection end def gcount_inc_get(connection) do {:ok, _} = connection |> Jylis.GCOUNT.inc("mileage", 10) {:ok, _} = connection |> Jylis.GCOUNT.get("mileage") connection end def pncount_inc_dec_get(connection) do {:ok, _} = connection |> Jylis.PNCOUNT.inc("subscribers", 9) {:ok, _} = connection |> Jylis.PNCOUNT.dec("subscribers", 4) {:ok, _} = connection |> Jylis.PNCOUNT.get("subscribers") connection end def mvreg_set_get(connection) do {:ok, _} = connection |> Jylis.MVREG.set("temperature", 68) {:ok, _} = connection |> Jylis.MVREG.get("temperature") connection end def ujson_set_get(connection) do {:ok, _} = connection |> Jylis.UJSON.set(["user", "alice", "admin"], true) {:ok, _} = connection |> Jylis.UJSON.get("user") connection end end compose_file = "benchmark/docker/docker-compose.yml" System.cmd("docker-compose", ["-f", compose_file, "up", "-d"]) benchmarks = %{ "TREG set/get" => &Benchmark.Queries.treg_set_get/1, "TLOG ins/get" => &Benchmark.Queries.tlog_ins_get/1, "GCOUNT inc/get" => &Benchmark.Queries.gcount_inc_get/1, "PNCOUNT inc/dec/get" => &Benchmark.Queries.pncount_inc_dec_get/1, "MVREG set/get" => &Benchmark.Queries.mvreg_set_get/1, "UJSON set/get" => &Benchmark.Queries.ujson_set_get/1, } Benchee.run benchmarks, warmup: 5, console: %{comparison: false, extended_statistics: true}, before_scenario: &Benchmark.Queries.before_scenario/1, after_scenario: &Benchmark.Queries.after_scenario/1 System.cmd("docker-compose", ["-f", compose_file, "down"])
29.960526
80
0.645147
79debbe6d84844f0d610f3491419768afd41e9d2
3,380
ex
Elixir
lib/client/detecting.ex
jmerriweather/pn532
ec072d9270deec19b9acbe15d45b28222a651189
[ "MIT" ]
null
null
null
lib/client/detecting.ex
jmerriweather/pn532
ec072d9270deec19b9acbe15d45b28222a651189
[ "MIT" ]
null
null
null
lib/client/detecting.ex
jmerriweather/pn532
ec072d9270deec19b9acbe15d45b28222a651189
[ "MIT" ]
null
null
null
defmodule PN532.Client.Detecting do @moduledoc """ Functions for when we are in the connected state """ require Logger require PN532.Connection.Frames import PN532.Connection.Frames def detecting(:cast, :stop_target_detection, data) do {:next_state, :connected, data} end def detecting(:internal, :poll_for_cards, data = %{connection: connection, connection_options: connection_options, poll_number: poll_number, poll_period: period, poll_type: type}) do new_power_mode = connection.wakeup(data) connection.in_auto_poll(connection_options, poll_number, period, type) {:keep_state, %{data | connection_options: %{connection_options | power_mode: new_power_mode}}} end def detecting(:state_timeout, :poll_for_cards, _data) do {:keep_state_and_data, [{:next_event, :internal, :poll_for_cards}]} #:keep_state_and_data end def detecting(:info, {:circuits_uart, com_port, <<0xD5, 0x61, 0, _rest::bitstring>>}, data = %{current_cards: current_cards, handler: handler, connection: connection, connection_options: connection_options}) do Logger.debug("Received in_auto_poll frame on #{inspect com_port} with no cards") {:noreply, client} = if current_cards != nil do apply(handler, :handle_event, [:cards_lost, current_cards, PN532.HandlerClient, PN532.HandlerClient.new(connection, connection_options)]) end {:keep_state, %{data | current_cards: nil, detected_cards: nil, poll_number: 255, connection: client.connection, connection_options: client.connection_options}, [{:state_timeout, 100, :poll_for_cards}]} end def detecting(:info, {:circuits_uart, com_port, <<0xD5, 0x61, 1, in_auto_poll_response(_type, message), _padding::bitstring>>}, data = %{handler: handler}) do Logger.debug("Received in_auto_poll frame on #{inspect com_port} with message: #{inspect message}") detected = apply(handler, :handle_detection, [1, [message]]) with {:ok, cards} <- detected do {:next_state, :detected, %{data | poll_number: 7}, [{:next_event, :internal, {:cards_detected, cards}}]} else _ -> {:keep_state, %{data | current_cards: nil, detected_cards: nil, poll_number: 255}, [{:state_timeout, 100, :poll_for_cards}]} end end def detecting(:info, {:circuits_uart, com_port, <<0xD5, 0x61, 2, in_auto_poll_response(_type1, message1), in_auto_poll_response(_type2, message2), _padding::bitstring>>}, data = %{handler: handler}) do Logger.debug("Received in_auto_poll frame on #{inspect com_port} with two cards with message: #{inspect message1} and #{inspect message2}") detected = apply(handler, :handle_detection, [2, [message1, message2]]) with {:ok, cards} <- detected do {:next_state, :detected, %{data | poll_number: 7}, [{:next_event, :internal, {:cards_detected, cards}}]} else _ -> {:keep_state, %{data | current_cards: nil, detected_cards: nil, poll_number: 255}, [{:state_timeout, 100, :poll_for_cards}]} end end def detecting(type, event, data) do case PN532.Client.Connected.connected(type, event, data) do {option, data, actions} when is_list(actions) -> {option, data, actions ++ [{:state_timeout, 100, :poll_for_cards}]} {option, actions} when is_list(actions) -> {option, actions ++ [{:state_timeout, 100, :poll_for_cards}]} end end end
46.30137
212
0.702663
79ded0874b38b21cfab83aebfdacb1eef8c8a806
337
exs
Elixir
priv/repo/migrations/20190819140756_add_social_volume_query_table.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
81
2017-11-20T01:20:22.000Z
2022-03-05T12:04:25.000Z
priv/repo/migrations/20190819140756_add_social_volume_query_table.exs
rmoorman/sanbase2
226784ab43a24219e7332c49156b198d09a6dd85
[ "MIT" ]
359
2017-10-15T14:40:53.000Z
2022-01-25T13:34:20.000Z
priv/repo/migrations/20190819140756_add_social_volume_query_table.exs
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
16
2017-11-19T13:57:40.000Z
2022-02-07T08:13:02.000Z
defmodule Sanbase.Repo.Migrations.AddSocialVolumeQueryTable do use Ecto.Migration @table "project_social_volume_query" def change do create table(@table) do add(:project_id, references(:project, on_delete: :nothing), null: false) add(:query, :text) end create(unique_index(@table, :project_id)) end end
24.071429
78
0.721068
79dedddfccedcc2bbb64d93edcc184f9e6fe6e2a
1,567
exs
Elixir
mix.exs
namredip/facebook.ex
a50ed04ba52e8c4d2322336928bd0183d7b93bcd
[ "MIT" ]
null
null
null
mix.exs
namredip/facebook.ex
a50ed04ba52e8c4d2322336928bd0183d7b93bcd
[ "MIT" ]
null
null
null
mix.exs
namredip/facebook.ex
a50ed04ba52e8c4d2322336928bd0183d7b93bcd
[ "MIT" ]
1
2018-09-10T15:35:53.000Z
2018-09-10T15:35:53.000Z
Code.ensure_loaded?(Hex) and Hex.start defmodule Facebook.Mixfile do use Mix.Project def project do [ app: :facebook, version: "0.21.0", elixir: "~> 1.0", description: description(), package: package(), aliases: aliases(), deps: deps(), source_url: "https://github.com/mweibel/facebook.ex" ] end # Configuration for the OTP application def application do [ mod: { Facebook, [] }, applications: [:httpoison, :json, :logger], env: [ env: :dev, graph_url: "https://graph.facebook.com", graph_video_url: "https://graph-video.facebook.com", app_secret: nil, app_id: nil, app_access_token: nil ] ] end defp description do """ Facebook Graph API Wrapper written in Elixir. Please note, this is very much a work in progress. Feel free to contribute using pull requests. """ end defp package do [ licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/mweibel/facebook.ex" }, maintainers: [ "mweibel", "jovannypcg" ] ] end defp deps do [ {:json, ">= 0.3.3"}, {:httpoison, "~> 0.13"}, {:mock, "~> 0.2.0", only: :test}, {:mix_test_watch, "~> 0.3", only: :dev, runtime: false}, {:credo, "~> 0.8", only: [:dev, :test], runtime: false}, {:ex_doc, ">= 0.13.0", only: :dev} ] end defp aliases do [ quality: [ "test", "credo --strict" ] ] end end
20.350649
99
0.529675
79dee2b30748fa3eb82479151e916f2aa75b8f23
8,719
ex
Elixir
lib/footprint.ex
zven21/footprint
ebbc4ba6c7b95cdfab28ea406146f2de90e58211
[ "MIT" ]
2
2018-08-23T08:30:01.000Z
2019-06-17T08:09:19.000Z
lib/footprint.ex
zven21/footprint
ebbc4ba6c7b95cdfab28ea406146f2de90e58211
[ "MIT" ]
3
2020-07-17T07:15:56.000Z
2021-05-09T04:18:19.000Z
lib/footprint.ex
zven21/footprint
ebbc4ba6c7b95cdfab28ea406146f2de90e58211
[ "MIT" ]
null
null
null
defmodule Footprint do @moduledoc """ ## TODO - [x] insert! and insert func. - [x] update! and update func. - [x] delete! and delete func. - [ ] insert_or_update! and insert_or_update func. - [x] get_version and get_versions func. - [ ] version diff and apply func. - [x] footprint.inspect func. """ alias Ecto.Multi alias Footprint.Version alias Footprint.Client, as: FC defdelegate get_version(record), to: Footprint.VersionQueries defdelegate get_version(model_or_record, id_or_options), to: Footprint.VersionQueries defdelegate get_version(model, id, options), to: Footprint.VersionQueries defdelegate get_versions(record), to: Footprint.VersionQueries defdelegate get_versions(model_or_record, id_or_options), to: Footprint.VersionQueries defdelegate get_versions(model, id, options), to: Footprint.VersionQueries defdelegate get_current_model(version), to: Footprint.VersionQueries @doc """ Same as insert/2 ## Example iex> Post.changeset(%Post{}, %{title: "t1", body: "b1"}) |> Footprint.insert() {:ok, %{model: %Dummy.CMS.Post{}, version: %Footprint.Version{}} iex> Post.changeset(%Post{}, %{title: "t1"}) |> Footprint.insert {:error, :model, #Ecto.Changeset<>, %{}} """ @spec insert(Ecto.Changeset.t()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def insert(changeset, options \\ [meta: nil, originator: nil, origin: nil]) do repo = FC.repo() Multi.new() |> Multi.insert(:model, changeset) |> Multi.run(:version, fn repo, %{model: model} -> make_version_struct(%{event: "insert"}, changeset, model, options) |> repo.insert() end) |> repo.transaction() end @doc """ Same as insert/2 but returns only the model struct or raises if the changeset is invalid. ## Examples iex> Post.changeset(%Post{}, %{title: "t1", body: "b1"}) |> Footprint.insert!() %Dummy.CMS.Post{} iex> Post.changeset(%Post{}, %{title: "t1"}) |> Footprint.insert!() ** (Ecto.InvalidChangesetError) """ def insert!(changeset, options \\ [meta: nil, originator: nil, origin: nil]) do repo = FC.repo() repo.transaction(fn -> model = repo.insert!(changeset) make_version_struct(%{event: "insert"}, changeset, model, options) |> repo.insert!() model end) |> elem(1) end @doc """ Same as update/2 ## Examples iex> p1 = Repo.get(Post, 1) iex> Post.changeset(p1, %{title: "t2"}) |> Footprint.update() {:ok, %{model: %Dummy.CMS.Post{}, version: %Footprint.Version{}} iex> Post.changeset(p1, %{title: "tttttt7"}) |> Footprint.update() {:error, :model, #Ecto.Changeset<>, %{}} """ @spec update(Ecto.Changeset.t()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def update(changeset, options \\ [meta: nil, originator: nil, origin: nil]) do repo = FC.repo() Multi.new() |> Multi.update(:model, changeset) |> Multi.run(:version, fn repo, %{model: model} -> make_version_struct(%{event: "update"}, changeset, model, options) |> repo.insert() end) |> repo.transaction() end @doc """ Same as update!/2 ## Examples iex> p1 = Repo.get(Post, 1) iex> Post.changeset(p1, %{title: "t2"}) |> Footprint.update() %Dummy.CMS.Post{} iex> Post.changeset(p1, %{title: "tttttt7"}) |> Footprint.update!() ** (Ecto.InvalidChangesetError) """ def update!(changeset, options \\ [meta: nil, originator: nil, origin: nil]) do repo = FC.repo() repo.transaction(fn -> model = repo.update!(changeset) make_version_struct(%{event: "update"}, changeset, model, options) |> repo.insert!() model end) |> elem(1) end @doc """ Same as delete/2 ## Examples iex> p1 = Repo.get(Post, 1) iex> p1 |> Footprint.delete() {:ok, %{model: %Dummy.CMS.Post{}, version: %Footprint.Version{}} """ @spec delete(Ecto.Schema.t()) :: {:ok, Ecto.Schema.t()} | {:error, Ecto.Changeset.t()} def delete(struct, options \\ [meta: nil, originator: nil, origin: nil]) do repo = FC.repo() Multi.new() |> Multi.delete(:model, struct) |> Multi.run(:version, fn repo, %{} -> make_version_struct(%{event: "delete"}, struct, options) |> repo.insert() end) |> repo.transaction() end @doc """ Sames as delete!/2 ## Examples iex> p1 = Repo.get(Post, 1) iex> p1 |> Footprint.delete!() %Dummy.CMS.Post{} """ def delete!(struct, options \\ [meta: nil, originator: nil, origin: nil]) do repo = FC.repo() repo.transaction(fn -> model = repo.delete!(struct, options) make_version_struct(%{event: "delete"}, struct, options) |> repo.insert!() model end) |> elem(1) end @doc """ Prepase add footprint_fields_labels to origin Module. ## Examples Post.footprint_field_labels = %{title: "Title", body: "Body"} iex> version1 |> Footprint.inspect %{"Body" => [nil, "body2"], "Title" => [nil, "title1"]} """ def inspect(version) do module_base = version |> Map.get(:item_base) |> String.to_atom() item_changes = version |> Map.get(:item_changes) module_base |> apply(:__info__, [:functions]) |> Keyword.has_key?(:footprint_field_labels) |> case do true -> footprint_labels = module_base |> apply(:footprint_field_labels, []) item_changes |> Enum.into(%{}, fn {k, v} -> {Map.get(footprint_labels, String.to_atom(k), k), v} end) _ -> item_changes end end @doc """ Sames as insert_or_udpate/2. """ def insert_or_update(changeset, options) do case changeset.data.id do nil -> insert(changeset, options) _ -> update(changeset, options) end end @doc """ Sames as insert_or_udpate!/2. """ def insert_or_update!(changeset, options) do case changeset.data.id do nil -> insert!(changeset, options) _ -> update!(changeset, options) end end defp make_version_struct(%{event: "insert"}, changeset, model, options) do %Version{ no: 1, event: "insert", item_base: model.__struct__ |> to_string(), item_type: model.__struct__ |> Module.split() |> List.last(), item_id: model.id, item_prev: build_item_prev(changeset), item_changes: bulid_item_changes(changeset), item_current: build_item_current(changeset), meta: options[:meta], originator_id: case options[:originator] do nil -> nil _ -> options[:originator] |> Map.get(:id) end, origin: options[:origin] } end defp make_version_struct(%{event: "update"}, changeset, model, options) do %Version{ no: build_item_version_no(model), event: "update", item_base: changeset.data.__struct__ |> to_string(), item_type: changeset.data.__struct__ |> Module.split() |> List.last(), item_id: changeset.data.id, item_prev: build_item_prev(changeset), item_changes: bulid_item_changes(changeset), item_current: build_item_current(changeset), meta: options[:meta], originator_id: case options[:originator] do nil -> nil _ -> options[:originator] |> Map.get(:id) end, origin: options[:origin] } end defp make_version_struct(%{event: "delete"}, model, options) do %Version{ no: build_item_version_no(model), event: "delete", item_base: model.__struct__ |> to_string(), item_type: model.__struct__ |> Module.split() |> List.last(), item_id: model.id, item_prev: model |> Map.from_struct() |> Map.delete(:__meta__), item_changes: model |> Map.from_struct() |> Map.delete(:__meta__), item_current: %{}, meta: options[:meta], originator_id: case options[:originator] do nil -> nil _ -> options[:originator] |> Map.get(:id) end, origin: options[:origin] } end defp bulid_item_changes(changeset) do changeset |> build_item_current() |> Enum.into(%{}, fn {k, v} -> {k, [Map.get(changeset.data, k), v]} end) end defp build_item_current(changeset) do changeset |> serialize() end defp build_item_prev(changeset) do changeset |> build_item_current() |> Enum.into(%{}, fn {k, _v} -> {k, Map.get(changeset.data, k)} end) end defp serialize(changeset) do relationships = changeset.data.__struct__.__schema__(:associations) Map.drop(changeset.changes, relationships) end defp build_item_version_no(model) do model |> get_version() |> Map.get(:no) |> Kernel.+(1) end end
27.945513
96
0.614864
79defe323b3db2d9b299073d568770cc363bfb22
1,440
exs
Elixir
mix.exs
brauliobz/excoveralls
8108405bda1c6ef27253edc294415f02d78760f4
[ "MIT" ]
null
null
null
mix.exs
brauliobz/excoveralls
8108405bda1c6ef27253edc294415f02d78760f4
[ "MIT" ]
null
null
null
mix.exs
brauliobz/excoveralls
8108405bda1c6ef27253edc294415f02d78760f4
[ "MIT" ]
null
null
null
defmodule ExCoveralls.Mixfile do use Mix.Project def project do [ app: :excoveralls, version: "0.11.2", elixir: "~> 1.3", elixirc_paths: elixirc_paths(Mix.env()), deps: deps(), description: description(), package: package(), test_coverage: [tool: ExCoveralls], preferred_cli_env: cli_env_for(:test, [ "coveralls", "coveralls.detail", "coveralls.html", "coveralls.json", "coveralls.post", ]) ] end defp cli_env_for(env, tasks) do Enum.reduce(tasks, [], fn(key, acc) -> Keyword.put(acc, :"#{key}", env) end) end # Configuration for the OTP application def application do [] end # Specifies which paths to compile per environment. defp elixirc_paths(:test), do: ["lib", "test/fixtures/test_missing.ex"] defp elixirc_paths(_), do: ["lib"] # Returns the list of dependencies in the format: # { :foobar, "~> 0.1", git: "https://github.com/elixir-lang/foobar.git" } def deps do [ {:mock, "~> 0.2", only: :test}, {:meck, "~> 0.8", only: :test}, {:jason, "~> 1.0"}, {:hackney, "~> 1.0"}, {:ex_doc, "~> 0.18.0", only: :dev} ] end defp description do """ Coverage report tool for Elixir with coveralls.io integration. """ end defp package do [ maintainers: ["parroty"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/parroty/excoveralls"} ] end end
25.714286
94
0.590972
79df02242c403ca426f64167fa1cd2449d33614d
191
exs
Elixir
lib/mix/test/fixtures/umbrella_dep/mix.exs
guilleiguaran/elixir
952052869ff7af0e293d2a7160b1aebc68fc46be
[ "Apache-2.0" ]
4
2016-04-05T05:51:36.000Z
2019-10-31T06:46:35.000Z
lib/mix/test/fixtures/umbrella_dep/mix.exs
guilleiguaran/elixir
952052869ff7af0e293d2a7160b1aebc68fc46be
[ "Apache-2.0" ]
null
null
null
lib/mix/test/fixtures/umbrella_dep/mix.exs
guilleiguaran/elixir
952052869ff7af0e293d2a7160b1aebc68fc46be
[ "Apache-2.0" ]
5
2015-02-01T06:01:19.000Z
2019-08-29T09:02:35.000Z
defmodule UmbrellaDep.Mixfile do use Mix.Project def project do [ app: :umbrella_dep, deps: deps ] end defp deps do [ { :umbrella, path: "deps/umbrella" } ] end end
14.692308
44
0.628272
79df204b028e747c0bf5ccd95c8cc121b0be70cd
560
ex
Elixir
elixir/langxpay/lib/langxpay/account.ex
ednailson/languages-experiments
309a0360c6c26a3c95f3c8e25fe37bc7a5cbb8d4
[ "MIT" ]
null
null
null
elixir/langxpay/lib/langxpay/account.ex
ednailson/languages-experiments
309a0360c6c26a3c95f3c8e25fe37bc7a5cbb8d4
[ "MIT" ]
null
null
null
elixir/langxpay/lib/langxpay/account.ex
ednailson/languages-experiments
309a0360c6c26a3c95f3c8e25fe37bc7a5cbb8d4
[ "MIT" ]
null
null
null
defmodule Langxpay.Account do use Ecto.Schema import Ecto.Changeset alias Ecto.Changeset alias Langxpay.User @primary_key {:id, :binary_id, autogenerate: true} @foreign_key_type :binary_id @required_params [:balance, :user_id] schema "accounts" do field :balance, :decimal belongs_to :user, User timestamps() end def changeset(params) do %__MODULE__{} |> cast(params, @required_params) |> validate_required(@required_params) |> check_constraint(:balance, name: :balance_must_be_positive_or_zero) end end
20.740741
74
0.719643
79df3a6c7761c7538fa8796047c40dab7b3baf38
111
ex
Elixir
test/support/repo.ex
jnylen/geo_postgis
ac21d16c64233abef8ebb19d096f6d196d67381e
[ "MIT" ]
220
2017-07-15T22:20:31.000Z
2022-03-30T22:22:57.000Z
test/support/repo.ex
jnylen/geo_postgis
ac21d16c64233abef8ebb19d096f6d196d67381e
[ "MIT" ]
100
2017-09-09T19:40:47.000Z
2022-03-23T12:26:56.000Z
test/support/repo.ex
jnylen/geo_postgis
ac21d16c64233abef8ebb19d096f6d196d67381e
[ "MIT" ]
60
2017-08-10T10:05:39.000Z
2022-01-25T21:53:25.000Z
defmodule Geo.PostGIS.Test.Repo do use Ecto.Repo, otp_app: :geo_postgis, adapter: Ecto.Adapters.Postgres end
27.75
71
0.792793
79df462aa7c60c316afaf28d8558bd571e5dfc8f
2,084
ex
Elixir
lib/advent_of_code/day_2_b.ex
rob-brown/AdventOfCode2017
cb8a56fba4b1999820b3aec4c4f03d7094836484
[ "MIT" ]
3
2017-12-26T20:51:47.000Z
2019-05-14T04:59:38.000Z
lib/advent_of_code/day_2_b.ex
rob-brown/AdventOfCode2017
cb8a56fba4b1999820b3aec4c4f03d7094836484
[ "MIT" ]
null
null
null
lib/advent_of_code/day_2_b.ex
rob-brown/AdventOfCode2017
cb8a56fba4b1999820b3aec4c4f03d7094836484
[ "MIT" ]
null
null
null
defmodule AdventOfCode.Day2B do def checksum(input) do input |> String.split("\n") |> Stream.drop(-1) |> Stream.map(&process_line/1) |> Enum.sum end def test do 9 = checksum(""" 5 9 2 8 9 4 7 3 3 8 6 5 """) IO.puts "Test Passed" end def solve do checksum """ 3093 749 3469 142 2049 3537 1596 3035 2424 3982 3290 125 249 131 118 3138 141 677 2705 2404 2887 2860 1123 2714 117 1157 2607 1800 153 130 1794 3272 182 93 2180 114 103 1017 95 580 2179 2470 2487 2806 1574 1325 1898 1706 3753 233 3961 3747 3479 3597 1303 2612 4043 1815 3318 737 197 3943 239 254 113 147 961 157 3514 3045 1270 3528 1369 3377 492 156 1410 3251 1839 1249 3948 3651 888 3631 253 220 4266 1284 3595 237 2138 3799 2319 254 267 1182 399 446 795 653 154 762 140 487 750 457 730 150 175 841 323 492 999 979 103 99 1544 1404 100 1615 840 92 1552 1665 1686 76 113 1700 4049 182 3583 1712 200 3326 3944 715 213 1855 2990 3621 2560 842 249 2082 2610 4749 2723 2915 2189 3911 124 164 1895 3095 3992 134 127 4229 3453 4428 105 692 101 150 193 755 84 185 622 851 706 251 86 408 774 831 238 217 224 1409 1850 2604 363 265 596 2933 2641 2277 803 2557 1399 237 304 247 192 4369 997 5750 85 1248 4718 3888 5228 5116 5880 5348 6052 245 238 373 228 395 86 59 289 87 437 384 233 79 470 403 441 352 151 3473 1435 87 1517 1480 140 2353 1293 118 163 3321 2537 3061 1532 3402 127 375 330 257 220 295 145 335 304 165 151 141 289 256 195 272 """ end defp process_line(line) do line |> String.split(~r"\D+") |> Stream.map(&String.to_integer/1) |> Enum.sort |> divisible_value end defp divisible_value([head | rest]) do rest |> Stream.map(& {rem(&1, head), div(&1, head)}) |> Stream.filter(fn {x, _} -> x == 0 end) |> Enum.at(0) |> case do nil -> divisible_value(rest) {_, value} -> value end end end
33.612903
90
0.612284
79df5f4603dbdf85a1393304d0d1e97b0e3ec39d
4,724
ex
Elixir
lib/minuet/format/json.ex
exstruct/minuet
2ca8f6da3000bfdf00f271eb695cb468b50b71bb
[ "MIT" ]
null
null
null
lib/minuet/format/json.ex
exstruct/minuet
2ca8f6da3000bfdf00f271eb695cb468b50b71bb
[ "MIT" ]
null
null
null
lib/minuet/format/json.ex
exstruct/minuet
2ca8f6da3000bfdf00f271eb695cb468b50b71bb
[ "MIT" ]
null
null
null
if Code.ensure_compiled?(Poison) do defprotocol Minuet.Format.JSON do def enter(type, vars) def exit(type, vars) end defimpl Minuet.Format.JSON, for: Minuet.Type.Root do def enter(%{line: line}, vars) do buffer = Macro.var(:buffer, __MODULE__) vars = Map.put(vars, :buffer, [buffer]) {quote line: line do unquote(buffer) = [] end, vars} end def exit(%{line: line}, %{buffer: [buffer]} = vars) do {quote line: line do _ = unquote(buffer) end, %{vars | buffer: buffer}} end end defimpl Minuet.Format.JSON, for: Minuet.Type.Constant do def enter(%{expression: expression, line: line}, vars) do %{buffer: [buffer | _]} = vars {quote line: line do unquote(buffer) = [ unquote(Poison.encode!(expression)) | unquote(buffer) ] end, vars} end def exit(_, vars) do {nil, vars} end end defimpl Minuet.Format.JSON, for: Minuet.Type.Enumerable do def enter(%{line: line}, vars) do %{enum_prefix: [enum_prefix | _], buffer: [buffer | _]} = vars = vars |> Map.update(:enum_prefix, [suffix_var(0)], fn suffixes -> [suffix_var(length(suffixes)) | suffixes] end) |> Map.update(:buffer, [buffer_var(0)], fn suffixes -> [buffer_var(length(suffixes)) | suffixes] end) {quote line: line do unquote(buffer) = [] unquote(enum_prefix) = [] end, vars} end def exit(%{line: line}, vars) do %{buffer: [items, buffer | rest], enum_prefix: [suffix | enum_prefix]} = vars {quote line: line do _ = unquote(suffix) unquote(buffer) = ["[", unquote(items), "]" | unquote(buffer)] end, %{vars | enum_prefix: enum_prefix, buffer: [buffer | rest]}} end defp suffix_var(id) do Macro.var(:"enum_prefix_#{id}", __MODULE__) end defp buffer_var(id) do Macro.var(:"enum_items_#{id}", __MODULE__) end end defimpl Minuet.Format.JSON, for: Minuet.Type.Enumerable.Item do def enter(%{line: line}, vars) do %{buffer: [buffer | _]} = vars = vars |> Map.update(:buffer, [buffer_var(0)], fn suffixes -> [buffer_var(length(suffixes)) | suffixes] end) {quote line: line do unquote(buffer) = [] end, vars} end def exit(%{line: line}, vars) do %{enum_prefix: [enum_prefix | _], buffer: [item_buffer, items | buffer]} = vars {quote line: line do unquote(item_buffer) = [unquote(enum_prefix) | unquote(item_buffer)] unquote(items) = [unquote(items), unquote(item_buffer)] unquote(enum_prefix) = "," end, %{vars | buffer: [items | buffer]}} end defp buffer_var(id) do Macro.var(:"enum_item_buffer_#{id}", __MODULE__) end end defimpl Minuet.Format.JSON, for: Minuet.Type.Map do def enter(%{line: line}, vars) do %{map_suffix: [map_suffix | _]} = vars = Map.update(vars, :map_suffix, [suffix_var(0)], fn suffixes -> [suffix_var(length(suffixes)) | suffixes] end) %{buffer: [buffer | _]} = vars {quote line: line do unquote(map_suffix) = [] unquote(buffer) = ["}" | unquote(buffer)] end, vars} end def exit(%{line: line}, vars) do %{buffer: [buffer | _], map_suffix: [suffix | map_suffix]} = vars {quote line: line do _ = unquote(suffix) unquote(buffer) = ["{" | unquote(buffer)] end, %{vars | map_suffix: map_suffix}} end defp suffix_var(id) do Macro.var(:"map_suffix_#{id}", __MODULE__) end end defimpl Minuet.Format.JSON, for: Minuet.Type.Map.Field do def enter(%{line: line}, vars) do %{map_suffix: [map_suffix | _], buffer: [buffer | _]} = vars {quote line: line do unquote(buffer) = [unquote(map_suffix) | unquote(buffer)] end, vars} end def exit(%{name: name, line: line}, vars) do %{map_suffix: [map_suffix | _], buffer: [buffer | _]} = vars {quote line: line do unquote(buffer) = [ unquote(Poison.encode!(name) <> ":") | unquote(buffer) ] unquote(map_suffix) = "," end, vars} end end defimpl Minuet.Format.JSON, for: Minuet.Type.Value do def enter(%{expression: expression, line: line}, vars) do %{buffer: [buffer | _]} = vars {quote line: line do unquote(buffer) = [ Poison.Encoder.encode(unquote(expression), []) | unquote(buffer) ] end, vars} end def exit(_, vars) do {nil, vars} end end end
26.994286
85
0.565199
79df77ad4b3cd3189b22a497af057f0a74f008f5
100
exs
Elixir
test/snek/board/point_test.exs
xtagon/snek
f659c66b586dcbec811c26e0a1f9a552b9878752
[ "MIT" ]
1
2020-09-06T18:56:49.000Z
2020-09-06T18:56:49.000Z
test/snek/board/point_test.exs
xtagon/snek
f659c66b586dcbec811c26e0a1f9a552b9878752
[ "MIT" ]
null
null
null
test/snek/board/point_test.exs
xtagon/snek
f659c66b586dcbec811c26e0a1f9a552b9878752
[ "MIT" ]
null
null
null
defmodule PointTest do use ExUnit.Case alias Snek.Board.Point doctest Point, import: true end
16.666667
29
0.77
79dfb16cf2d90686b1551ee6dcef8b8085b19b08
332
exs
Elixir
alvarocasadoc/day1/day1_demo.exs
jodoldar/AdventofCode18
c3872a64d767d8f0dab853f8dc4bb928fb90ee22
[ "MIT" ]
null
null
null
alvarocasadoc/day1/day1_demo.exs
jodoldar/AdventofCode18
c3872a64d767d8f0dab853f8dc4bb928fb90ee22
[ "MIT" ]
1
2018-12-04T17:59:39.000Z
2018-12-04T17:59:39.000Z
alvarocasadoc/day1/day1_demo.exs
jodoldar/AdventofCode18
c3872a64d767d8f0dab853f8dc4bb928fb90ee22
[ "MIT" ]
3
2018-12-02T10:04:51.000Z
2018-12-05T19:15:31.000Z
# AdventOfCode2018 # @alvarocasadoc # Day 1 Code.require_file("day1.exs") ## Test execution {:ok, file} = File.open("input1.txt", [:read, :write]) input = IO.read(file, :all) input = String.split(input, "\n", trim: true) # Exec part 1 IO.inspect Day1.sum_frequencies(input) # Exec part 2 IO.inspect Day1.find_first_cycle(input)
19.529412
54
0.704819
79dfc3ac7692657236a8252167594bacfb217c35
963
ex
Elixir
lib/tackle/exchange.ex
arfl/ex-tackle
b1ed825af900d983f2f945c4b16e7019d1c184e3
[ "MIT" ]
null
null
null
lib/tackle/exchange.ex
arfl/ex-tackle
b1ed825af900d983f2f945c4b16e7019d1c184e3
[ "MIT" ]
15
2019-08-12T14:21:51.000Z
2021-12-31T02:12:04.000Z
lib/tackle/exchange.ex
arfl/ex-tackle
b1ed825af900d983f2f945c4b16e7019d1c184e3
[ "MIT" ]
2
2021-06-28T06:48:10.000Z
2021-07-05T09:26:50.000Z
defmodule Tackle.Exchange do require Logger # FIXME: let the user configure this in every situation: consumer, publisher and so on. # Do not save the configuration in a module variable. Each change would then require to # recompile the deps @default_exchange_type Application.get_env(:tackle, :exchange_type, :direct) def create(channel, name, type \\ @default_exchange_type) do :ok = AMQP.Exchange.declare(channel, name, type, durable: true) end def bind_to_exchange(channel, destination, source, routing_key) do Logger.debug("Binding '#{destination}' to '#{source}' with '#{routing_key}' routing key") :ok = AMQP.Exchange.bind(channel, destination, source, routing_key: routing_key) end def bind_to_queue(channel, exchange, queue, routing_key) do Logger.debug("Binding '#{queue}' to '#{exchange}' with '#{routing_key}' routing key") :ok = AMQP.Queue.bind(channel, queue, exchange, routing_key: routing_key) end end
41.869565
93
0.735202
79dfd7c7447895caaf9a5a199ec2e2ba6e929782
902
exs
Elixir
config/prod.secret.exs
bokner/solverlview
52a527bc653619fd35977d951b36207ba0ebd9cc
[ "MIT" ]
10
2020-09-18T19:26:51.000Z
2021-07-08T19:26:00.000Z
config/prod.secret.exs
bokner/solverview
52a527bc653619fd35977d951b36207ba0ebd9cc
[ "MIT" ]
null
null
null
config/prod.secret.exs
bokner/solverview
52a527bc653619fd35977d951b36207ba0ebd9cc
[ "MIT" ]
null
null
null
# In this file, we load production configuration and secrets # from environment variables. You can also hardcode secrets, # although such is generally not recommended and you have to # remember to add this file to your .gitignore. use Mix.Config secret_key_length = 64 secret_key_base = :crypto.strong_rand_bytes(secret_key_length) |> Base.encode64 |> binary_part(0, secret_key_length) config :solverview, SolverViewWeb.Endpoint, http: [ port: String.to_integer(System.get_env("PORT") || "4000"), transport_options: [socket_opts: [:inet6]] ], secret_key_base: secret_key_base # ## Using releases (Elixir v1.9+) # # If you are doing OTP releases, you need to instruct Phoenix # to start each relevant endpoint: # # config :solverview, SolverViewWeb.Endpoint, server: true # # Then you can assemble a release by calling `mix release`. # See `mix help release` for more information.
33.407407
99
0.752772
79dff06487eb2dbc0f458ca5b3de5cbe85375f48
1,732
exs
Elixir
mix.exs
ckreiling/stargate
76f7d8a95314a842ac9340739fbd1f1f142ab383
[ "Apache-2.0" ]
null
null
null
mix.exs
ckreiling/stargate
76f7d8a95314a842ac9340739fbd1f1f142ab383
[ "Apache-2.0" ]
null
null
null
mix.exs
ckreiling/stargate
76f7d8a95314a842ac9340739fbd1f1f142ab383
[ "Apache-2.0" ]
null
null
null
defmodule Stargate.MixProject do use Mix.Project @github "https://github.com/jeffgrunewald/stargate" def project() do [ app: :stargate, version: "0.1.0", elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), docs: docs(), package: package(), description: description(), homepage_url: @github, source_url: @github, elixirc_paths: elixirc_paths(Mix.env()), test_paths: test_paths(Mix.env()), dialyzer: [plt_file: {:no_warn, ".dialyzer/#{System.version()}.plt"}] ] end def application() do [ extra_applications: [:logger] ] end defp deps() do [ {:dialyxir, "~> 1.0.0-rc.7", only: :dev, runtime: false}, {:divo, "~> 1.1", only: [:dev, :integration]}, {:divo_pulsar, "~> 0.1.1", only: [:dev, :integration]}, {:ex_doc, "~> 0.21.0", only: :dev}, {:gen_stage, "~> 0.14.0"}, {:jason, "~> 1.1"}, {:plug_cowboy, "~> 2.1.0", only: [:test, :integration]}, {:puid, "~> 1.0"}, {:websockex, "~> 0.4.0"} ] end defp elixirc_paths(env) when env in [:test, :integration], do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp test_paths(:integration), do: ["test/integration"] defp test_paths(_), do: ["test/unit"] defp description(), do: "An Apache Pulsar client written in Elixir using the Pulsar websocket API." defp package() do [ maintainers: ["jeffgrunewald"], licenses: ["Apache 2.0"], links: %{"GitHub" => @github} ] end defp docs() do [ source_url: @github, extras: ["README.md"], source_url_pattern: "#{@github}/blob/master/%{path}#L%{line}" ] end end
25.101449
88
0.557737
79dffebc2704ca4c74c126919d14558b3d51b596
749
exs
Elixir
test/plugs/current_user_test.exs
jespr/noegle
e14953085d38384c80993dd750aa85202db11418
[ "MIT" ]
null
null
null
test/plugs/current_user_test.exs
jespr/noegle
e14953085d38384c80993dd750aa85202db11418
[ "MIT" ]
1
2017-05-08T15:09:09.000Z
2017-05-10T06:05:24.000Z
test/plugs/current_user_test.exs
jespr/noegle
e14953085d38384c80993dd750aa85202db11418
[ "MIT" ]
null
null
null
defmodule Noegle.CurrentUserTest do use Noegle.ConnCase defmodule MockRepo do def get(MockUser, id) do if id == 42 do %{} else nil end end end test "current_user exists in conn.assigns if session contains user_id" do Mix.Config.persist([noegle: %{repo: MockRepo, user: MockUser}]) conn = Plug.Conn.put_session(conn(), :user_id, 42) |> Noegle.Plug.CurrentUser.call(%{}) assert conn.assigns.current_user end test "current_user isn't in conn.assigns when session doesn't contain user_id" do Mix.Config.persist([noegle: %{repo: MockRepo, user: MockUser}]) conn = Noegle.Plug.CurrentUser.call(conn(), %{}) refute Map.has_key?(conn.assigns, :current_user) end end
25.827586
83
0.667557
79e00bc57073c8ec9129eb76f743f8b60246a591
9,941
ex
Elixir
lib/hexpm/accounts/audit_log.ex
optikfluffel/hexpm
3b6c5f314ef5706d5d3c99830f39acba34867049
[ "Apache-2.0" ]
null
null
null
lib/hexpm/accounts/audit_log.ex
optikfluffel/hexpm
3b6c5f314ef5706d5d3c99830f39acba34867049
[ "Apache-2.0" ]
null
null
null
lib/hexpm/accounts/audit_log.ex
optikfluffel/hexpm
3b6c5f314ef5706d5d3c99830f39acba34867049
[ "Apache-2.0" ]
null
null
null
defmodule Hexpm.Accounts.AuditLog do use Hexpm.Schema schema "audit_logs" do field :user_agent, :string field :action, :string field :params, :map belongs_to :user, User belongs_to :organization, Organization timestamps(updated_at: false) end def build(nil, user_agent, action, params) when action in ~w(password.reset.init password.reset.finish) do params = extract_params(action, params) %AuditLog{ user_id: nil, organization_id: nil, user_agent: user_agent, action: action, params: params } end def build(%User{id: user_id}, user_agent, "organization.create", organization) do params = extract_params("organization.create", organization) %AuditLog{ user_id: user_id, organization_id: organization.id, user_agent: user_agent, action: "organization.create", params: params } end def build(%User{id: user_id}, user_agent, action, params) do params = extract_params(action, params) %AuditLog{ user_id: user_id, organization_id: params[:organization][:id] || params[:package][:organization_id], user_agent: user_agent, action: action, params: params } end def build(%Organization{id: organization_id}, user_agent, action, params) do params = extract_params(action, params) %AuditLog{ user_id: nil, organization_id: organization_id, user_agent: user_agent, action: action, params: params } end def audit({user, user_agent}, action, params) do build(user, user_agent, action, params) end def audit(multi, nil, _action, _fun) do multi end def audit(multi, {user, user_agent}, action, fun) when is_function(fun, 1) do Multi.merge(multi, fn data -> Multi.insert( Multi.new(), multi_key(multi, action), build(user, user_agent, action, fun.(data)) ) end) end def audit(multi, {user, user_agent}, action, params) do Multi.insert(multi, multi_key(multi, action), build(user, user_agent, action, params)) end def audit_many(multi, who, action, list, opts \\ []) def audit_many(multi, nil, _action, _list, _opts) do multi end def audit_many(multi, {user, user_agent}, action, list, opts) do fields = AuditLog.__schema__(:fields) -- [:id] extra = %{inserted_at: DateTime.utc_now()} entries = Enum.map(list, fn entry -> build(user, user_agent, action, entry) |> Map.take(fields) |> Map.merge(extra) end) Multi.insert_all(multi, multi_key(multi, action), AuditLog, entries, opts) end def audit_with_user(multi, nil, _action, _fun) do multi end def audit_with_user(multi, {_user, user_agent}, action, fun) do Multi.insert(multi, multi_key(multi, action), fn %{user: user} = data -> build(user, user_agent, action, fun.(data)) end) end defp extract_params("docs.publish", {package, release}), do: %{package: serialize(package), release: serialize(release)} defp extract_params("docs.revert", {package, release}), do: %{package: serialize(package), release: serialize(release)} defp extract_params("key.generate", key), do: serialize(key) defp extract_params("key.remove", key), do: serialize(key) defp extract_params("owner.add", {package, level, user}), do: %{package: serialize(package), level: level, user: serialize(user)} defp extract_params("owner.transfer", {package, level, user}), do: %{package: serialize(package), level: level, user: serialize(user)} defp extract_params("owner.remove", {package, level, user}), do: %{package: serialize(package), level: level, user: serialize(user)} defp extract_params("release.publish", {package, release}), do: %{package: serialize(package), release: serialize(release)} defp extract_params("release.revert", {package, release}), do: %{package: serialize(package), release: serialize(release)} defp extract_params("release.retire", {package, release}), do: %{package: serialize(package), release: serialize(release)} defp extract_params("release.unretire", {package, release}), do: %{package: serialize(package), release: serialize(release)} defp extract_params("email.add", {organization, email}), do: Map.merge(%{organization: serialize(organization)}, serialize(email)) defp extract_params("email.add", email), do: serialize(email) defp extract_params("email.remove", {organization, email}), do: Map.merge(%{organization: serialize(organization)}, serialize(email)) defp extract_params("email.remove", email), do: serialize(email) defp extract_params("email.primary", {old_email, new_email}), do: %{old_email: serialize(old_email), new_email: serialize(new_email)} defp extract_params("email.public", {organization, {old_email, new_email}}), do: %{ organization: serialize(organization), old_email: serialize(old_email), new_email: serialize(new_email) } defp extract_params("email.public", {old_email, new_email}), do: %{old_email: serialize(old_email), new_email: serialize(new_email)} defp extract_params("email.gravatar", {organization, {old_email, new_email}}), do: %{ organization: serialize(organization), old_email: serialize(old_email), new_email: serialize(new_email) } defp extract_params("email.gravatar", {old_email, new_email}), do: %{old_email: serialize(old_email), new_email: serialize(new_email)} defp extract_params("user.create", user), do: serialize(user) defp extract_params("user.update", user), do: serialize(user) defp extract_params("security.update", user), do: serialize(user) defp extract_params("security.rotate_recovery_codes", user), do: serialize(user) defp extract_params("organization.create", organization), do: serialize(organization) defp extract_params("organization.member.add", {organization, user}), do: %{organization: serialize(organization), user: serialize(user)} defp extract_params("organization.member.remove", {organization, user}), do: %{organization: serialize(organization), user: serialize(user)} defp extract_params("organization.member.role", {organization, user, role}), do: %{organization: serialize(organization), user: serialize(user), role: role} defp extract_params("password.reset.init", nil), do: %{} defp extract_params("password.reset.finish", nil), do: %{} defp extract_params("password.update", nil), do: %{} defp extract_params("billing.checkout", {organization, data}), do: %{ organization: serialize(organization), payment_source: data[:payment_source] } defp extract_params("billing.cancel", {organization, _params}), do: %{organization: serialize(organization)} defp extract_params("billing.create", {organization, params}), do: %{ organization: serialize(organization), email: params["email"], person: params["person"], company: params["company"], token: params["token"], quantity: params["quantity"] } defp extract_params("billing.update", {organization, params}), do: %{ organization: serialize(organization), email: params["email"], person: params["person"], company: params["company"], token: params["token"], quantity: params["quantity"] } defp extract_params("billing.change_plan", {organization, params}), do: %{ organization: serialize(organization), plan_id: params["plan_id"] } defp extract_params("billing.pay_invoice", {organization, invoice_id}), do: %{ organization: serialize(organization), invoice_id: invoice_id } defp serialize(%Key{} = key) do key |> do_serialize() |> Map.put(:permissions, Enum.map(key.permissions, &serialize/1)) |> Map.put(:user, serialize(key.user)) |> Map.put(:organization, serialize(key.organization)) end defp serialize(%Package{} = package) do package |> do_serialize() |> Map.put(:meta, serialize(package.meta)) end defp serialize(%Release{} = release) do release |> do_serialize() |> Map.put(:meta, serialize(release.meta)) |> Map.put(:retirement, serialize(release.retirement)) end defp serialize(%User{} = user) do user |> do_serialize() |> Map.put(:handles, serialize(user.handles)) end defp serialize(nil), do: nil defp serialize(schema), do: do_serialize(schema) defp do_serialize(schema), do: Map.take(schema, fields(schema)) defp fields(%Email{}), do: [:email, :primary, :public, :primary, :gravatar] defp fields(%Key{}), do: [:id, :name] defp fields(%KeyPermission{}), do: [:resource, :domain] defp fields(%Package{}), do: [:id, :name, :organization_id] defp fields(%PackageMetadata{}), do: [:description, :licenses, :links, :maintainers, :extra] defp fields(%Release{}), do: [:id, :version, :checksum, :has_docs, :package_id] defp fields(%ReleaseMetadata{}), do: [:app, :build_tools, :elixir] defp fields(%ReleaseRetirement{}), do: [:status, :message] defp fields(%Organization{}), do: [:id, :name, :public, :active, :billing_active] defp fields(%User{}), do: [:id, :username] defp fields(%UserHandles{}), do: [:github, :twitter, :freenode] defp multi_key(multi, action) do :"log.#{action}.#{length(Multi.to_list(multi))}" end def count_by(schema) do from(l in all_by(schema), select: count(l)) end def all_by(%Hexpm.Repository.Package{} = package) do from(l in AuditLog, where: fragment("(? -> 'package' ->> 'id')::integer", l.params) == ^package.id ) end def all_by(%Hexpm.Accounts.Organization{} = organization) do Ecto.assoc(organization, :audit_logs) end def all_by(%Hexpm.Accounts.User{} = user) do Ecto.assoc(user, :audit_logs) end def newest_first(query) do Ecto.Query.order_by(query, desc: :inserted_at) end end
32.171521
94
0.67619
79e015475dd7caa1e6db61ad0001b0784bda74e0
30,603
exs
Elixir
test/mac/hmac_test.exs
impl/ex_crypto
587aa8a63bd1768a361da207339b4a8d68560c22
[ "Apache-2.0" ]
2
2016-05-02T18:19:13.000Z
2016-05-03T16:11:58.000Z
test/mac/hmac_test.exs
impl/ex_crypto
587aa8a63bd1768a361da207339b4a8d68560c22
[ "Apache-2.0" ]
null
null
null
test/mac/hmac_test.exs
impl/ex_crypto
587aa8a63bd1768a361da207339b4a8d68560c22
[ "Apache-2.0" ]
null
null
null
defmodule Cryptex.Mac.HmacTest do use ExUnit.Case alias Cryptex.Hasher alias Cryptex.Mac.Hmac @golden_nist_test_vectors [ {:sha256, "0BB4127D89D9073EA425C303ADC3F9DB39E40ADAC23EA61FBA8B6E251D79390F", "C18BC28D496BEEDB25CA42D1B217BC81891D4C2BBB35380E5BB9BF7E3DBBFD37FEF70EF14407763447D6C06E915766430277F124165061236B9FCF057D785199B4381E49A2BCF3EF85D0", "28B18B862CE9541ED6DAF81199F9A331133B0EA3E48FF486C1ACC6D5C40E9F8F063B7A15704BA3D3CEA76B222511206D47E53C93A49EDD8D639B7551B224C3F65AA802189648607E259AB1FA9EA665910435B7DC9A4C28AEF8F32CF85F3A23E94A7E8A5945E9736702383261AAC15AE571B4E8466DA1BD31A83A5291745BA7AF"}, {:sha256, "1CBD4F923D683CA38ACA6CD0AD81151062FD642B155B2A950EB551CA8216B0CA", "76D8E0342011D2BCA953B26EE200E56685B721D50ED4DDA7CD3A05633A50F153884998E67DA901528004FB7DF4090E1EC4C0B11F3F10BD4727842215044FD9EF", "0EBAEFD2153DE2C70537CEB27E5EE70105AE85BD4DA38462B4ABEBED11DBCD36ADE16D808F3AA54FFDA5897A3FD74780A670521FCD2EBF231F60EF7D999E6E94D1B81BE038EC89B49C5CA65BF1BF9A675056F2464021FE16355477BA5605652E8327401797BB569FEA456C7F1B7DA85D0C48AF592DE60AE3FE6DCECFCF767CAB"}, {:sha256, "26DB47A48A10B9B0B697B793F5C0231AA35FE192C9D063D7B03A55E3C302850A", "62E3A735EDCD87FCA0DD1D2797CC0E574160DA9AC23F60E39501A5B77688D1287F947A0791922556F5B50AFC434818BC83433968931CD752C9DF9F04D8818531", "EC638734D336B8DA6DFAF3DA9E18C7131494FCC0709CD3A9A6618E9BA62533153C958E44345A7531C3EB503A22A5D8BF7C1D1E1D0AB5CFE07D6DB7349CFC859D2E20CEE81A325462CDFD8747DCD04C7DEAD2FE82CD96B2A4ECEFC070EB067F6C8BA94F09CBE6DDD354D9A2EB13C2ADB7285AA3D8FF68045CBC8FAF35DD6AA9EA"}, {:sha256, "2C723282159CEABC5B367B95CD807F249F1DFF7F9EBF5BA179A43081454E1B05", "08CCE7D7F3CCEA0212CF0299F27F3D3F393A97D3DD71CAF1954E67BC8D9A26DB5EDD7AC23DC7693372CE9B040D", "33AB861F089BAC0E5C886F66ADC568AE7BA331655A371DE7475E269138FF2725F7904C702FDCC62AC703C31D70C29D8A7AF451C8EC59342ED397E133DA7E76D41B90003635C1338D9F7B5F3C3CE59F3E2F6554C4F064D11F9F5158E199E8463F4AB48ABA42D25BFF8AF92B0B38B7D69241FD20A28FDE5E84539473E39DC4FE2F"}, {:sha256, "2D3A760595F3FB19293CC6D23651222A9F5A4F02284457A9C1ED4C43AC993CA5", "CEAB398E4107483EDE64CE107C9270E6022778B61F6A258D3B7045D4AD8506D32ECE0A738D2CB948A562DBCE8D7B66F30E6694D65AE439CFFAA454AF09ABE449", "6DDE9AE867E2FEB367008A975D7853ED8F89690F3C87A1107F2E98AA7736F477A527ED64956F0D64C1B23361B261DE78688EA865FCFF113C84817E5B377E829CD2D25BCF3ADBC06762CFDA736F5390D01A49079D56E969F03313E6C703E3F942BB87ED0F9C4D9F25120085B5DC75EF5D6D618DA0926D3293568DD7D8238DE3D0"}, {:sha256, "2F8321F416B9BB249F113B13FC12D70E1668DC332839C10DAA5717896CB70DDF", "992868504D2564C4FB47BCBD4AE482D8FB0E8E56D7B81864E61986A0E25682DAEB5B50177C095EDC9E971DA95C3210C376E723365AC33D1B4F391817F4C35124", "ED4F269A8851EB3154771516B27228155200778049B2DC1963F3AC32BA46EA1387CFBB9C39151A2CC406CDC13C3C9860A27EB0B7FE8A7201AD11552AFD041E33F70E53D97C62F17194B66117028FA9071CC0E04BD92DE4972CD54F719010A694E414D4977ABED7CA6B90BA612DF6C3D467CDED85032598A48546804F9CF2ECFE"}, {:sha256, "37F9F32918308210849DFEBF8DD456804BABD6845AF07218F9D9BE9DF9743D55", "BCE50CDFFF843885D4F364D69F93BF58A2322C707B82E878EEC96D11E5DB97BBB54606A3A3CCC3BBA716261070A6F759A70ED3CB785FD1354FE56648DF11863669B70C803B7A", "93B7EF0E470DDFAC6AEF93C0DCD37B8F1C4BAF5EADD978E3BF0512FA0BAEB099FF9EC1061B6172479B5674DB5606FFA7E6B5173309370E1647054AAFD5904816BAD5E1523032CCCD4D786505E241AC83A484911189666F287553D6A8164E8DCB0C85D75C4E29F624C97CEEA64A2C8B0C9DDFA560F70FA3FF91183E4B968F88A1"}, {:sha256, "4A34BD4DFEEF7FA1DC739280F16A3FE1281A51311C10A920AB43D406D4AE3370", "9319838432CA096960E2196A06398134EA06E4E8799BA470C54F0512CABB9045F529B6C4E749B6E27626C11DF4595BF5B47C04FFCBE218351485F49077405AD96A3F17BCB7B3E21E80CA", "57E1D3FF5FC4785F9370DF2E5ABF454579752EA934D2A9BAB568D5AEB22BA43E4BC7DF9F31366BB40D91CA822026E4E426CC088081732EF993FF7F676C571704A5B809278B50A3778108F4589FA18CAA9F0283B3FAD0BD594E406B950329D5242E5E5880B53AAA0EB57C66992055C4FFABC0A72AE712DE42ADD2A321C0CA6808"}, {:sha256, "4F2501D2A88CB13046A6549F90E4EA924773408BB684025B5126A8FC21F48670", "731EC9F365F28F1CB9C4EBCF89D8648732A6DFA958D2C0152B5E52FAE81F69EEA26D463E421FBA82CDB78F75E5D92304930256A54376A6EA107A995642C45C6F", "D98557504A21FC3A434C780C328EC239CF8D7C26F58D6AD7B23329C79A8E1E176058ACEBA778AA1215CC14E5A92600714F94D4D8B2E5B7F45268453ED6F787EEA3342264AD13CEC78D990AECD5E30F79A069024A6D846D132D2EF0479A093439CBA4218205F951A2D53AC4EA5BCDD599E9956C45CD73767C6A0C92AC8ECD0D40"}, {:sha256, "514BD18495F6DE0E237054B8E3BA1A74C3FADA4279AD6B8550F3A14712C528DF", "81574323C973540719D192833DDB51F13A52DCBAE294AEBEA51BE5F6AA47F3571F5D97FACDCF0C7BEFBE809F44BDC73963D8514E4FD559774BB96087EF8EDA6E7C64275D6D96C42B4E4E", "B9E944E0B42D0FF454F7F8AA24F00E9EE039058CE4094111E39731B6DC3ADE2A4ACEC4CF9C5BE078E4F10A72D3D685C1E5E4D5ABD92CD07B64DFF87F266F0853DDF1CD61D9C637A9B07AB0BE32ECAC119FAF827218B17AD4541A27519477F76ED918089F54B63D0E1E5A92982979AC187764B5E989E066A61B1065340E9CD203"}, {:sha256, "5717FC337916D66B4E292E69D507B1C81663D8140536670F3E70E33B04C83AC3", "E3D0C3ABDEF069E6E4FA35015797BD8A9D64BC9B75F20B028B12CCA04A4FE80FF1BBBD88E9EF1003564D499FEC88DF4503671188EEC5D7D089DD18B812C41DB43A3746F77B97", "934DC1EF76993AA82061CF67AAAC7714F12E25AA8F6F54840A2AE3D84AF32481511D300126DB7DC612A5B2AC0FDEB9C47EB316541846781E270C8EE5F6731C2E86C94E4482594C7E75D70EC43BFE7250B6778CB2C2FD3D176ABF07CA5C051FFB9A17C4C0735BD059B2BD8DB81553C94100412DCE73DBCAF63A0AF58F63F15571"}, {:sha256, "6C63BED6C6082BFB085CF2426EF3D0DEA97ACD717A57FF0AA624D0B803F2EA14", "85806FF2A642F729D28DED0734AEF4F6A3F0BB32771E77729B4391CAE4B49BD0A15089FE74071E576099A44D22A0E0E3C5D1450F717F68628460B4EAE3945F5893E39C5E8347", "DF073817D8687293257D7ED1816803AFE292D779F34E14B0C5BA6E0AC1E6C3B9E239F4F02110F4A430A71E906A3DCC7B0B7325BD9CF63600B25D4544D8556126CAFB3E61E4894095D935D647A8560929CCC9559CB393B77472C707FBB7AB8838FF16BE71091C7FEE8AED4D0022FBE3428F5B0E1F216EBE946DC05D3746305F79"}, {:sha256, "8E44D685FA79395B4761CAB89688E37509E69AD007A2794C8C0B4152B67036EA", "D8B994BB8DF02D7803CA2E09D601B918D6B5BDE90B611BEBF70E078D1AC7B152BC4C2528E60B70F6", "B31D11CB4F5C572CCF3405C65CBD218EE8ABDC08B6C82E5D1DA2BAAF8980F7A9C29B915A718B0D43E000ADAE01B29342B29B28D53F63BF81281C76FA252F5D1E6896DBCE224C4DFD4802EF0697140043D6BB21DB5B84FFDBD001318937BE64F52C76B5D06A875E8191A4957627CAB1B8DC758FC3121334949CB9B303C6155153"}, {:sha256, "9611E838FB1D816A0FF9CD269217D93258C34DF9E26B74476FE4DA0F7DEE2335", "8FA12BC017BFEB6C894020E420C5F76F9080E8733B998EF3A7D0B6563063B66AFA3200A82A21F6BA56BE003A3924DCBDAC1F3610D29079C19213E4E14AE0E009C1EF919B5E60AB4A9819", "FAA6CE40D931F3C0CB4538A82A22F0D4F3221F027B99D3D85DFFB729B751E57496B4FCADAE5C72404FAC2C54949E4C4CDE664B948052479ABCF59E1AEF84BB9F088030473E9505C603C350AD33BB06ED928C1196757EA3E5BF3EC97E0F3C43F638529394F2A65459CFD1CD3D7041C6BCF8DB9A91C1E58EC24E2461DC81412580"}, {:sha256, "974752B18D0DCBF29CC6104295E041259622CB7733CFF63DBCF6808B15A5AD45", "19FB88775A517BFEDEB2CDE7C9455CA58D40D150B0A47FFBD0288E42E4725822C48D130EEC98B13E7CBB044B846026F97F9F18531DF9A9FE464A99C75BF9FF7EBF72E80796D6", "892525A0F02AAE7F2264CB024632F11E8ADBDBECB7D0C7080832E2373C94014CEA02914C1542D1D000593FAB43524FCD1F3A63670F6FF8509F1B1DA881FB2ABBDE65AE27EA89A942BBF7FCB65B611D6E1CA20FB62B00929D68AE979E7595F6800D55637B98869F9CFC43EB6BB5E9C2CA281CC720340BFDB70BF5366340EDCE65"}, {:sha256, "A51F5988A8F0F3992F549EA7F8C370A06D5AE8D65880067997536385D632B206", "30BE326C2FFFF6D031AFFDAB0A27D5A8CBFC4BA9DEC626AD522615F77307E56D9E23F73E53C9F2C78CDEB5B84D2390727DB5B3B4F4DAE677D5FA7B161EEC81B27D743BD56609", "082E7B4CDE8914BF07C288441BE643E408F6CB5CA932F67E9B975BD54CA706885468708009AFAECD4D9EE846AB6C0D70A364C5A24131A766F558AD219E06E4F7E80C68E9D8289040A586662FCA865AB459C037BF92465596B4281178133E7A806B214DCD747B24E0B681EA459FBD9276D31108FCC3F968D781106F20D3D62FED"}, {:sha256, "A5772A3DA86365B46638F1E97037FC0D8351D2E19ED929F85448EBF4E8379A8E", "CA5F3EB9308604F9FCC2AF1C6A3175CD8A75045593B473BD7AE37933C345DDB0982E2DD7180DB31F", "8734E49E3E629DEB352C77F58FF4DCCE2AF3B1182E7D896AE68619F6CF66ED69EFD95913684AB1484D51BC06B47A67D70D48B7F9B27901BDBF8C5D2D238158F1F7E0E9740FFCA742CF7938B5400C0DD063824C6BC6040E905499CB2671EC12CC47507E085A01E5A163ACD2495B32367FD6AA5AB492A518AD50B54B28E23084C2"}, {:sha256, "A9C9D3993FE7EC4C2033CCF3B73B3407CD999D67455B43A75D6BA97EFDA3BE63", "B06F7CA7A5DD8BAF2CA940811EDAD87A33DA666DC427BCF4D54A8E03520DD5C399E9729D39BE1494", "32B45FBCBAF262BBE347360BD6076C43DC26BA9573FCABAEA14595DE886CCC793B09157DD0A85D74B6CCAB9C49335446A45C6E7CB64786E6997C96EF1E4E3123AD6101DB4C6A731DFD36B1BE4DEED1C92A994B25F5E2B171D81B9A335A83E03230C40B2056C00C7C5F8D2FB70ABE4B9615E53BD756569217072D8BF362923F6E"}, {:sha256, "B53DB6BF0C8317586AE6C1A1E2857F241BF55DDDD1B423578C6949D4BF014611", "C96C04A3BB0816FC47E05913A715FBAC9A3AD09DB75B48E8013D9F27BBE8532D7E63DBEA88BF968F575602F377552E35987872A4E3155DDB8E5CEF30AEDD08504D4B2123BD7F3AF62BBF", "B11389C7DC20FFD0C4A5F887F2576BDC302C7D2AF7089A012799C528FA7F2CE23BB10071B31C83D9E58D63E6FBD04670FF1AA6DE4EA4DFE94A9986A35032FDB7EA1F44F2452A1202E517257E97CED627A7BCF06E5476C236819F73DAAD0D96722527FE527891D4D42C0CE658AF97428890DA04E1EFC56C6F337534D7FB57209B"}, {:sha256, "C02C6022EE0DE099E3027850BE95A29CE800118ED3A97757DD8AB9E60F69A005", "98FFF7B5F77326C24471BB9C317490BE1FEBAD28E2E825AFC41C3B97CC03C963405CE3EC68DCB7B19523B76E62", "64A78A4D6FB8FF3813DF8DC022FAAF4415E4DF2949E16467683C6C47242E5A6B2C02610E5877528D2766B2266CA41000442A956C4B73DD6B10260570C6F506673CC541F50F0F5B021E864A753EFAB03E2F7C689ACFC35F928ECEA6C522CBC5687C38518BFA48C19EDE887D33FFC23806BE21803A3C9793E5CA7C75CFA1783F77"}, {:sha256, "CA0053D51F6CF6F9998FF1E0DB00B90E82C7B18CB5377ACC8EBE9AFE20DA1C3D", "44F71C2317CDE52151C84260D1D3C04A28CC15CE5B3802B2E5357E2BFCAF10AB15D77DFAAAD1A3883BADA502939948234C559DCD95E7E158338FA12AC6FD21874EC2FFABED051416EF77", "2AC0BB0524C22B902DE34CE64E6172D1B2074E159F517AB1ABD152622CD10669F03AED8E2EB51C65BD0F38D084E288C532724E512FD558DDD257D2B1D41C5EB6040767803DDBB18B95A035C5D8492D4D35936B7B3630EE20F625B70F8E71D9DCD0EFD0E3387D138C1F5EEDCE32DD88F223334B9A9EAB65017F04AA8442179F62"}, {:sha256, "D08563DAD7C32C02B305B87FAD504918FD566C433E98A1367A3DBBADB26E9B64", "F13794E5EA5E27507A7BAD638F8EB8B86CA5AD73B5A17424C63C74EF494BBFEA084189C6FFF5DFB2B6A5967CCE3A81F9D9CDE7A86F6B33927E15EE74E10BEB20344BC121E754", "CD3F17355A1E254B9821276141A850F0B71CB3CF4824A803B01C71D8DFC31D31FD33AD1CAC1776A98D18C6FD0598CAA241A3AF21772208D36F5270F4437570F963C8A323DBB41755D948F72369E7672B843EB0A849799D448AB7252E8ABB496D05E44074715FD2F6849B02FBF6FDEF3488D6FC8B45922FFF0832D7AF3EFC7234"}, {:sha256, "F15A210FCA2CEFC4D92BF14FF572D021463BCC28F60D034E87222DC6076EAFFE", "731BDC9FB219F3667C9A135ECF34C7F52CF638C39C554F1EF1691AE84E5A71ACE915D9E91043A8AE6A7B6A6780B684F77B0417072F7E279D597CFDF02508C97BF4928C505BE5", "12353BCA6B0F3D545EC4B470C69272F72BB5589793E6CA769A226018C5ACDE83145567A1D6FBEDE5C150EC3142DC58F81246D4A00ACF242A381FE51432447B7EAAF84C8D43222C0DA3A0175ACA442680A21CBCA1D7F70097E82491DB7F7D75A5FEA552555A8DE0122C3D9EB105D1C4D802C17963A1664706D3BACC345360B240"}, {:sha512, "0D73F53C10C029069A2D1D5733BC6BE8A1E94DE821573DAA290FBEE3F897F44297CFBD515CC5DDB0DF7BF44EF58C446EC085C32C8D6EF779A5518E63328DE957", "484BABC2861503D442448C3C43D7569A380EADD9EED2EEB4C651997867E9A80BB0471F2DF0D0E5FE5A3FD2C0B39009DF4E1E882E3A08FD74BAD8DB27F567AE77EFFBAC8FB8B38C17E4259BFD3A450C75B1898F3E984A2627146E34D3CF44D7B9EFAF786E4587A127C73C0E7A41BC06644797EC906E6111D6BC59CC035C", "B04BB381F91B8B64478391D6AB6AE306E796020418BF917899E85A9423EF924739625EB4C39496E2F9F0C8B5828E801DDD04C68D017FE9AF40127B56714D9DB44E127DCD1BA41C2B890155D3D9721B79446002F09B6900E42BB375CBE3806A19B90316B34973A7A7BF5D3F1AF83E3C82E451BC152FA66080207451DDC1B081DF"}, {:sha512, "1BC503398A25223FB9E93EA65228D2727B201F0A3FB544A300DC804340B6AB3676862B6320BCE35ADABEF387EC628DA38277F7DE6929C44810C47F2A7ACBEB03", "107ED9CA1F16FBDCBDFA5211B1A9EC8D9E03BBCB1F0A468715E99FDB403695A80D742A37AFDC4820715DAF6B4BE132F6B3D22316B5DC0C8146F59F6CD69BF0F0245DE2B2569DDFC34994CDC526973D503698E594F7EF503F6F5BD4A1C043C50DFD42E8833CE32A8DECA9926769537562CE5DE98A0BCA7B87372125C127B67AC83F2A24F28835904603A3E8", "204058177A61AA45BD666BD0F3870645FD6B9330CB91A89AD3F072CFBBDA04655926EE79DE8E123C4E56B3AF342FCFAA935AAF231F10BCADAD22943FE9DD5D3747305A9E3C11BBAEAD1CBA91A87DE36C5211B39C20C865404A4E09F77DEAD6EBD1A6C10EFAB04FA3C200A701B73BEB9320D7C82436814C5991BBF87FE1CA1787"}, {:sha512, "24D2DD3D082E6556DBE27381640837A23E5D4A4D6822066CD09217A677068E5B8901C1ECA7DA77A9595BE271ABFA76F9D40656CFBAE050FF6D8DDEDB0F4C82ED", "345479AE901ADBAC7223F5F9EDC419BB64665CBA4E3684B7371E28FF07F3124087F0E89A21630CF9E8A6C0A3D8518E0D5EAEE7F31B6D0AA7E59927AA0ECBC479E99E61A98B625736CF1506199D8F2F186BFC9FE2038F0E5B87754635B30888C063462B035581860B2F571083C4E5C6859338CDB09004597B2899CDC87F1224BDFCD08FCF07275F1F1156260AD5BD", "E4B38E556AA285688979A55EEACD7D953F1EE0AB8109444C7CC068488EB83AE9ACA1F783A59B944CABA75D6E0F5BDC5B4CDBFC6147046E7ED5EA4C757E85FC2181A7580A17310B36FC873E422C4175B1EA24B3830750E50961BA7DF9AADD5EBE6BADF81148CDB4CD850192FFC9E6103D22E14F3A4A557197291945FB9A292665"}, {:sha512, "2C537D0EDFA86126672CA6F0081E8C13FD161510D56C0BB6EF015EC35CDCBADF4FE68594FE70820EBFD99CFB83A1FD18FEBFDE2743BF408479A52C3334E39141", "CF44B9D057CC04899FDC5A32E48C043FD99862E3F761DC3115351C8138D07A15AC23B8FC5454F0373E05CA1B7AD9F2F62D34CAF5E1435C451F3D927940E8A92C805EE3E754117C45FE0DE0545E7D1B3F0B71912AA2DEEF5E5EE661A6E95A06F8727EA158000C91FA067B03A7378066619BD61F4AE33B7EC2FABBF1D0DC3078C3AB0A5919004C159F7FD79A", "FF24C8943C8E6D3DB40C7AC16776F756C44803EE07A3C95BC594AFB7C599D0031261AD0E4ED41F98495391B8D3416B7BCEC2D1CE87C28E9E463A4B3D23AE05081CFBBE47654F7254FF794C008C631A3262DCFFD1DE9B67E4FA8140F8221F68C24478610627084CB8FD0515603BE4EBC3A81FF3BFB4363D770CF4F7B06BF3E07B"}, {:sha512, "3780EF695742F09A160C8DD7D35E2758B08284E8150934D222DB31DF2767D40D7C815C526ECEE5F787030C8DC5F050C419EC6EA7563650DCCE1480892D3088E6", "8A0349D4D1ED8C4AF533E9E83468B5859BB68237798038171346684499C9DC2B5970730533EB2CA04D1680630820F58D32ECF0BD7DB7CAB72FFC27651C94831CD1220E2113AEBA6C889092ABB3904D8A264B2332F2D9DF0F63AC36D7EABB57C85BE0C331587F5F330D69C7C91F00E606DE9BC49EC22C9EA815203CA2ED867FB65D743A3BECA6427F4669C9C432B7", "035F55033DF01F670015A828EFF154A245E8CA7474B0B3330CABBE5FDD74E89560B8FA075347532AA46AE7AE907888B30CA4653A6419D0D9224944B43181A6A842C1CBC96FCC3B0F1E7B344C2956F2613C652EB27E44E5D773765A9521FB5E0C7125CF31D9A75F7F38EF96EA01B61B159CD52FC4095A7A94C7DB0AEAF40A9929"}, {:sha512, "38CA18D60F180FD2A40E342272190D9B84BA37BBCCF59B29BCBDB08762A90E1F8B28349CA634A6F955CC08C96835EE70A2267444FDE88B45B8E313B0DAF6E12F", "29F8EB9FC8AB58FEF681F9FAAF934E992D42046F0CCD2FC9AB23D42BD5F5AAFDA110218196EAA408137A1B66EE4DB5A35CD7E4F31107A9E8A81E11E744C000D9784B2D2264696ED721E1362B60B35B2B4D631DACBA95658179DA4AF109CAD9687653166C7A503ED3E85D4F334AEACA9BC98FB8804E9FEBFAE70086316C3AC01162CDE4461FC89C642F977065F71D", "3AC2FFBC5B6B2334809232C0F8151ED379A8634D70D3F5A1963A7637C421AD0F082F34A8F872702046A4C69C95AD0CEA8B683E6528AA731956810F28C1B9396DE8A5905E751C1937C9C17C55DC8771DF447575AC93A7C161E6967CDABB9930CC03AB7BA8796E07C23170BBB274AD33FACB566EEA5AD1C7C16F0127155BC77875"}, {:sha512, "39D94C4E1C8456BED8637E592E4231854DF3A6FFCE98463E4A85C477D9FD34D27035CDFCCFCFD385D91E4E38E8C75D9FF941DE80742E985BAA9C94DBEC5A6837", "EF71B7B3CA0F904DC50447AE548096B2B3603B312A5E59D490851B270EE99AEF259401BDF2C3EFC3B1531CE78176401666AA30DB94EC4A30EB281494BEF5205DD87F3350C1C4A56F3D040B12167214391B30B121697A7915E9224B871A3C355F111A9493BE7B7DF870FF5C589BDEDBC4DADA062B3072AC2C93590829AB26A09DD74D6EAF714E3E07532C57E09921", "50EC304FA342839457D7EB28791B671BA5C425F711C3A351CC76149D481F0547179540FFF239F054FF2C078454BFDD92B72B199AA783D562A1E6FD319CF9F8E4D6948B3ED2BCFA80A1D270396209A060051EADA0544347F3335C1872266D5E6C1553D9B54CB3E740C631EEF0ABE2FAAC1703A7B21DEB422D0C3E2B09F0647D06"}, {:sha512, "41A4C83777750D4FEA58645CEA32FF4456C44953B466A5980D2B8DA234603547A6259188F8693649DCEF85E85110026C006AB968297567CE823965A1DF6701FE", "21251DDBA377E48FA35AD148389C486A84E623F3DC49F9AF281AA0AF8D00F0F74A4BCA77E087593D765198E87B6A15608D0AF4C49A7736A445D53C718B408631A618C177319C01938EBB4B06852656392DAA926E10BD6AF68A57C6A47203D583FC3509C4DEDE63FAB23EF08A9CF9945C2C6E06D786441C0DC04549328B706453", "41DA7852D48D59FC2AD0FFFB9D64B9AE213F3266D5D4A2C7D89445725EB50DE1033294915F135467DAEE1A4DC1AEB81C9A93FABEB57ADC94045FFA152C2048B8DC8303145E7BE8466CA7A394441C8A50FF648BFE1EC663B966C811D2EEF38BBB76D6AF23FA4E7C63870482194E369712F7BBCC6E3741A0FEA5DA73F1C9B73DB0"}, {:sha512, "4459066109CB11E6870FA9C6BFD251ADFA304C0A2928CA915049704972EDC560CC7C0BC38249E9101AAE2F7D4DA62EAFF83FB07134EFC277DE72B9E4AB360425", "C367AEB5C02B727883FFE2A4CEEBF911B01454BEB328FB5D57FC7F11BF744576ABA421E2A63426EA8109BD28FF21F53CD2BF1A11C6C989623D6EC27CDB0BBF458250857D819FF84408B4F3DCE08B98B1587EE59683AF8852A0A5F55BDA3AB5E132B4010E", "1A7331C8FF1B748E3CEE96952190FDBBE4EE2F79E5753BBB368255EE5B19C05A4ED9F1B2C72FF1E9B9CB0348205087BEFA501E7793770FAF0606E9C901836A9BC8AFA00D7DB94EE29EB191D5CF3FC3E8DA95A0F9F4A2A7964289C3129B512BD890DE8700A9205420F28A8965B6C67BE28BA7FE278E5FCD16F0F22CF2B2EACBB9"}, {:sha512, "562B5EF3D5CEC882A2F54F8169612DBA2B033325CE5ED924024E7806C745DE9E7612DBCFCBB95EA3FDB93DE9C6460A866BD412B45EABA5139939FE43D20F9315", "FE27BBC87755AACC37F667F8CA37F8888FC9DC530FE4F8F38E8CD426E01307747EDFF012D96DA707EE96338D1B11FEBA313A865FCA115431DD8632268FF499224CEB69D31732DCD91E0CBD2B92BBD5B6B543A74735705DAAB81A0114B8A8F0BE91D38CD3D8AD328CEFE16C99D63C67C4446CA7D1F708F9A848D1A9B60238F6907420C3D9C5E48F67889CA7A1909C", "99841C3E4A41B53C30267DC056E7E9B8F9994494DFBBA363EA761C38EC2433D3BD10957D8B7C093472E9A3084C923AC5CB3A1DD2C5270259CE6F3FA80C723DD847A829AC409DECBB44395ED20045B694972B4663F2FD658458B9AC7D3ECC65C260D4409110AA481BCEA016E41A07446C86F5250F0F45B32AADDEC97F293993DB"}, {:sha512, "5F3422F586E6DBAE45DDC87F8D04B0C88152F90FABFC6DFBB0CCD7EDAE37DE528460A7BF16C4C0521355D5F28C88FFEB55986F8B919FEB756693B076C1690D5B", "F84D1361C51C3E50E245848383FCD37B2F7B0FD916010A7FA41BB1F256228302CD0548AE2148FF42774D18C2D6D3E38B36BC4938DA13BAC3E04D66EC17CFB0DF10B1DF1178C2176BA4CC89AA6E19E606403519116EF635E3C9BAAC7471F0C349EADA42537290701492493E03F4D6C332746FE82E79B2652686E9EC500C8CA389", "2BAC5A6BD9DC5EE714606E2262BBD3D3EF73C9D578688321676370FA40F2BD673B741BE63370C25FBE2BB5579E79486658D3E0EB22AAFBFE02FB70A63524F74CCEF6EB709F0B4F9B5C591095FE0889D766814C4343C82013350B4610337B01042A5A5571E6550E83361504444B119E0F62A69547A369FA4848BC7B9E019FE276"}, {:sha512, "6E989EC9CBF010AD6691A672FF4CA90A00275F9BA4C81CD147CC506E1DBC8BC93B1D96A375E493503C0AC697F7C45E4FADF138242DF7E06E677DE245AFA97780", "95AF10920DC788269E70B8560B73135CF7F6F5B04A502C7BD61CB74F3B8CCD160701224922D865636A860D949AE755B970D3858C0FF37418A2D24B7142378BA11AB352E5C876DA1A076642728B73916B2D24F8024876572363E7036510CEC7F413ED28CEC749ED33BE3ADF56A8BECE597612D478BF84DE85628367946DF887F73DD92D6DE7FAA896D7276D", "61D91F317A902EA0944E11E92E6657A589E17ABC027FCD869FF8B030E8870662F8A9E91ED3239CECFA42C0343D66CBEBD1C2B771A25DF7BAEA5CAFAD038424C97AFB720E644E7D1BF5B829944EA2CEC69766E68E4E580976DE071C2274C0C5EB0E5421C9D51BBA76AC39B3D009204680035771D9AD79EB02A3805D58E243CF0E"}, {:sha512, "8C385547A8EBA518E777C3593C5B7CE0BD7C859AF6D67B6238D20A58B8D0D74D80D18AB358EF1C1218B928A026AE8C4E3B73BB5BC0914DE905D499C75E6F3D9F", "5860501208A4C922AD7550DBD931A19AC1434750E63D5F34F528A0B5EB1798B37C0338EEB6D293BFE2B9E306ABC4CD6382B3E6A94008758F0D5E7BA981FCF0970AAA507D8EC456B3518C07BD18C4F37D8F7DB8A7E82AC776C5F86B9D58620781C8FF9FA5D79F9965C397C5E869599C50B048C53325CADE4FE39E7879B67063D780AA2D4FDB8EE53FFF82246FE7AA", "C35B26BD02499CDB6B06BFA4B18979F0A472BA7C559DBD277BF78C611590C6E051F2A094ADB22ADE5C44D4FDEB1330C924D1F9A3330C55AC07035735FBB7C877B64527844F72EE7EB58817074F61DFF8DFC1CA56ACE9E782E06855AF2F350699B9FBC37532B47023407992AB24980EE79DE8337D0959FB11CECF8EB8F83108AF"}, {:sha512, "8D9725605AEA94C3EF125B307F7ACD5A906D10B4908FCD21F678937CC4605B0800AF50480EF6FF1439CCA60CD1986F04A1DDEA0ABED6C8DCB9B485A923288C03", "C4E631ADCCA6A4735C905C369C7CD44D132200B362F29A0A3240B7E06BA49D32A6A1D82EE6848B3D828F05416657941B7C6B9E716436EDAE6B274B4ABB0F4F4BCFCA760C2A21753D49EFCE2BD683A2411E46C6CFC59D190BB811145664AEA2C026A832CD02450B7A97F6E07B52C7A5C7E3FAA156EDEFC3290248398CCE", "E8AB6A06DBCD52A245152D3851CEAC0551D5C3780DA0A44F5A7FEDFEEF222050755C5550DD262B6AF6E704CE3FF37215FA51EC2781C1C65CDDFD60E195409D5EC40596D56E1190CE14B32CB1864BDE73F909A07459F7E8A8E13AD7F6E895B3DDFE2E975D37956915C7020DA9CFDED866778548293D4BF27C8DBDBB0391294B17"}, {:sha512, "90093BDCC45DA7338BD2EFE92E30933B14F75582739C747F7572B3270B104F33AF0C939E3C8AE53B2066FC8C97CCF38785CD2EC3D79E6946499D36121E44A3E7", "E9E4480D1C4A621E0C4E1505992556347A7AB34FD2B289910474766CC969116F8040D96DC5F66CDC4454FA7BCFB9F838AF19195038467AB8A16E1CBC12E598E6FD250E21B2145F1E2E859CF73400BE12A0C69749F7100847429875351D5A76970B9CCF700C2CA3AD72E9E4C0F0840E8CF488158136989B0891F867211350134A", "B82EEFB2081BD14DAB0E9E345248A34ADE73F3291886B91EA3E8CC742FD884F6EE0CCDAF4C9879F4DB12DBA58CF491AF2541A1D5EF6CC8B1AF750EF5D8559EF7FF9CD56D8F599974BE3AECD8C0F4C08F3AE50D86F9F822A1E4CA39FD2F0B4D78D22630733A24D8D63ECDF9555411DAF205A761C39EF46FF6292E74129BC13A7F"}, {:sha512, "9210B074BB645C3A36CE46F9921DE1D6CD8C9F37829C251D1D999C193DC30467D44C830084914CF19F4BA761A0E774C103F092B51EA25BEB1B8277E99FDE26A3", "AD8DB0F165D0ED6E9495E6E53EA1E0DEE4437CC156DB2E83C999F084298738B8B1CA2706B82503EDCEBEE76D0725B92597925DB99F6E2876471598390DDB428C5D4D0B1361B99B271AF00FC0B04AEE9806EB5F8D924599476CDE9A1CA4531C30D99EC5E107949E62A1B1C6A5E018687F5AD6EA07D667673F5F7B60F697", "B6D8212D828DFAF27A03B79F0CC73ECD76EBEEB521058C4F317A80BB5AFD41DFF5520E525358DF7851469BEF2C358B2A97DF0F5C0BA68F985FD8B5369831D97802A1BD6E80507B1620E0BBC8F2F229D11BEB275F25F8BE9D994FDB1ED0B8B87F064C9848B07DB7140F5781F20606020A29979E84160302A508695A3BA99BC43C"}, {:sha512, "9F5C4FD863F070B85D29B933B1379E7023335B74AAC37186315E959473BF2B3C0F1F893E1FEACE27DFFE35BE6C607A22B02D695E41948B3B6B2BBF58AE7AE84B", "5D307655CF8F7C1B3B573BD75E2374942EE3E56B6B2578EC7793BBC067BC908D5A17261A094427B4A09633D0CDCF8EF1162A15CC6F9F77AA0C62A10F74AD7A99D7BFD12AA125934A4F3842C681E7A29D51B6B61DE407EA4A3E98927F5B4E93587B3160CEBDB729A4EF454F03A5F31A618890AEA7F1E63B92B73E755945274491", "F91BC92F97C28B011E7BB1DCE84CF9154942094AB908B49635B87906E2F14C51F42A9AC3CE46877B6A687AD6FC08DB2BD2471BB97F7FF5DD381FF4897EB636F1FE4D6F87B5FA302A57B26A9AF25F2E30CE32B6CC993BA90EC0379BC920A9D3B4DE2C526393071176AD0289111278788C06AEE36B4E63579095A875AF10F2AE03"}, {:sha512, "BB714844B6BE93CCEC0ACB8780996B2A4778C42A8A76A49EFF87CED3A258815D76685DCE4C8AE37C244229F17E0503DE089A043368CD300D13F842F28C111FBB", "BCEAF34D50C1F202539233630B16DD048EA23F093C9F713B8D3A385B0D5C2BB6A4DD14F91BF59947DCF31C89F931DF0570476C33AE7F34CB51897623327062B8A3CD7F0AF53B4AAE3E0A209E58385DD32D9CC6163265241332C332AF4DE4B99B4022FA29", "F3BFA5C1F1055281A35B48F86FA3AE454C03EAC56FF064CF268B8DA20431219B3E4DA9AC55714309F5A6A5241E0060DC817562F12DEEBFBC6A9FB11DE594DDB40E8DD754BF0CE9B41EAC1068C4B448101FEC09D014B01200E94265246365931E2B2739A276FECBEBE51690ACAAEAEE4AED12E8486E5BE5036B1DB39FC4C9CB41"}, {:sha512, "BE73D57AB3A7C5BB305451922FA9B11D0AE938BEC886FAC5645A8B72DE93770D96465291DA2BDD5D11692F2CBFAE69ADB36AE714F1E5CF43B9D2841DDEBA4CA6", "5C8589B3845970145E12B34713455EB6B5CEB132242024E42FD9A886FC9A30D3AA15703B3467E4DC99A915AE3AC118FD837E571DCDE5945983C52A2C849296B4C96F3763488D52F818B459ADD51F6DB2468D21DB3D958196BF3A531F65BF9CF702BD66928672C14F235C08AEAE0665BE472397D43CD9F3822B5FA9C767", "7F2544A478961DD012AC705E12E74587E2DF6B2EE1406A0BFE13B908853F31EB384FC236A275654BA8CF51D461EA726228851754EF97EBFBD69326FCFCEA04F594D177633C4618C38B4D64F7E98025ECA4C62E7A40634B8B0E317880002C51D0BB34CAF2EE0F207EE2AE108F53B1466B7F2D18667CAC7403CE75175D390E00C5"}, {:sha512, "C0D6E13C5746369D49BEF107CFC9A465627691320B8203233359E6A49659025AC96A6DB6C4D460224F6AA1CB7A6B8DF311E066F6109BD466CD9AEE3058DBC5F0", "662CA8F53B97EDD9BBD43B1F9E4EA49F2AC14417FAEE257AFF93608BC49A85ABF6913DEF235A2E76C2241FFA749A5DA489595D25C6A8A2026563E12F5E3964E0E518AC9C34E45A938A6F503174A613F34B08737AFE5D6FDE11A45344E64D23B33CA83C23", "0C057A2B56CB7E651C6339E4C91A1A72D51AF2A646DE9DFD77E9E42C18B8A2B576F526B9FCEDD90DFA442090A6E784BB614311793BB5FB39B8418842D586294746F1EA3C02320D6801ECF2BA44B13B60172D2D9693A158BC66947AACD7C5A14A0463905D6E80649DB8C4770CAC5E858A7F400DA4568CFAAE08498311265B50E5"}, {:sha512, "C1437541647FB134322FE4809DE516FF2A9982C16132077DAC91E0E06F14CFA943FC8539A22C91FAA3FA8FE623DAFC954EBEE5C17136281E7F8A3038F58BD80A", "FFE01CBD0EF36A85E32ADF18931C4761709FB382228B27BBF9C1938D816C041F57871CE03CA0C06E68DB10B720399C5E8B1AD460C201C1F72698F3BEF6F4BB1621199AC958C1F8EE6859190DC74D4E836C856827E430722DA3C0A04B9835821B049F7DC18BDE7CCD8CADE363AEDFC599BBE75620B29EA3271741807C8EB9C2F4", "A32D2FBA17F4B0F08A9EE7EDEAB34B1B8F7B12AD6E65FE248FA97A18C12DE5358CA62E8467FFA1EB2BFE00F8C825D6DA36D608B0AFBBAD071C651F9DCD33526B6C7665E334D277775EE8BC5ADC31D08A4A2D4B0E22BE957C2FCEFCBF443803172DE6FD61E637DB990BA3439D90A1E234B2C8024E2D355F8EB02E36058E04A041"}, {:sha512, "CB700E68AEC9448B67AB8E15D491AA070242B4430D6C70DB6B736AD66756065F417C0B201395E203C57BD7809272CE34D4DFE1972B7C5277A28D71C7F52C32FD", "9CB3288F3B04F0442F2CA8CDC41B0F39DDF93F898868E312D509A422E941E4E64E3DAF8B8D33EEA4FFEBDECCE07FC18CA55FD47F8F9780B38155D4530FA53383D7804A8C14054539700643811AC607651901F01CE02D2B6E2200275EE732490BE084E2D8F7015ECB2B84BE339B7A488EE0E97CA9A0B24B096013848A9A6F8F4610525DB85FB09F22D76D36", "96A83010F9D4F0405826E8CC941190E07C33D933362DB680E1B1DB3A78DDC47CF9C7FA3FC75992CF4D5FF680E5DEE89CF8A7C3A1662D04A928940A2A340A1ADFA05AA6060BBECFCC39F52806FD96BD215CA4545CEF62F2348969A1201AF7717FD38ABDCF8BAEAF1F621306C7A4E21756F05112CC9976870A4C582986F34CD143"}, {:sha512, "D032BFB5A538197385EB70673CF8F93E31FDF9C22C0E90008A454BA4D69BDC2232475A41723C8A5E3B29C6DE929A7A1E87B64BEECDA29683D0D925F00CE23B35", "1CE7E20ABBDCD1154D4B536714FF534A01B8E88C78DA34D653638C39291FD80AD01F3DF02067FA3BFAE7907789AD2641C8582B5A45D03DFA24344A676614F5C56CE13B30B6A15608F1E7E18C31033EAB7B76351686A9DD9AC2DEC0AD9A663A47F61422F3", "46AE8403EBB4C8723652B9848FDAAA537A50E3191BD94442F9702BC602DB98B5CFDD8F142AAEBEE7CDA8608F6D436156F743C3491A30404605073155722FAE3BE3AEF74D2B9D128331D9B6CDF1FC68AAC38CE4F6E072BE0322AD49EC0B47B82609888358F86B0D6DE94E83E722ED077666910EC9768506A4D7CA3D33D60BFE9E"}, {:sha512, "D725750A042DE65607AF5EF523E3C86D08BE52427B7036AD514B9596C901E96D76B5E58F68907044282E695B3B875C09AD49ECD9950FE312A59DAD691471C572", "FE4C83E8496A69B7A251228396A5D2B4849EDCEE0AB1F8DABD6D872A1DA324D7C8C97CADEDA05F0A041517E3BC65F807358538A870C1011704A3C5CF1216D2B57ACB269E4FDC841289B0C750FA1E779184D59A9188FBCC4CA11492059326EC8D7E1A29C25866FF5699E9DBD2381676DAD755A9B23BA68201FE8897D588199AE83B7E2E22EE85F95E9D89FB715E97", "C24FAB7F7998C69063C2D1103E60A6C4CB03206ADD01D09FAF75F1007A879E9047EE435A02B35257D1373791A4778D890C8F92D6507DD810BE283EEC3FA11FA82EA8C9AA6A723164AAA9E57A11B54127033AE6DD36E1682B0C5C47E420A4217E1E8525B8D95DCB7F9721C213AFA02A66570C04C5B7B6E7B94219F430451A0CD8"}, {:sha512, "D78285AB97DFFED5F16D00A7F277EEE9E9BBBC5EB14FAB10C189739965FB3DD1C196FBE3B01363260BF688955278884812286DCF81C25F1EB17CD2503FFC7ACC", "59AA9D7F583F6AB90B472935AA6DEA95E2FBE402CBF70C6E1992E61C96C49B63D0304DAF0E4DA7C889C7B857D92301A6AEA3CCA7C069C03809DEB3A53155BF6E4AEC984BBDB31C6E84112C089A63BB0EB0E5243D22D6C15C29D7B9C1529519162FA7275D4CBAF33264EB2E50D5743F57528B94CDD8873662E345A178E1CAD2E2E729A1ECA3A7519C921E66", "B9A8865C3A6BA8F2C13F35730B39FC3C92405C06BB6E116851B84D9D32D20A88484D9FF5BB03922265B4AE7E87F155B0BA3917DB28638321FB3B3C661670505603AEC6A92D0776A550971EE52D68B15A8293F28F39A84231E050B6CE59316DDDD31221FFF940FB846830AC316765B940D29416A95807F7A0E73FE35F63DD0A25"}, {:sha512, "D8BF5FF4392938534A7962C64985F163CE7C95E6C05F93CF704106F9BDA7C9AE963F5EA87F73626F67ED3146E8611CA62EF2EEB4F9A13847DC6E7FFBE3D851A4", "3699D9CD078A20EC0C96EB01AA60DF6CD5DCB554260EEA8E2E15B7C00B6943C638611854AAF8D3DD18D020B49A77E67275EABF973557AB74FD2705481C3CB6A9E077A825AF7E7E2A53BC822396A9DEE40F4B10483BFD9818D06FF32F4DEECDDCD6E57388", "9186EAA3B8E785DD2A747297BDBDD4F5532A47B7008C21686FF7F8D881D464CD383205F6D45DC8203BB267AC9EB12F415A5406BE1C9FAC73497941909DBA08DD12856AAC03D83E0D916147404694FE70F8FA929EF0CC2EDB4CC07ABAA2236405E62820AF8E806D0AF32A1B3AFB8DCAEAF5C4F43DC4392E074075AA3ED93601AB"}, {:sha512, "E913FCCC25F84A1390EF0B0F86050FE9E61146C1B4EF0B4B60D187BAA36B61458BBDA925B96E99CF8A4330291690417FE194CB9BC2B6232D43E046D13F038ED3", "0F67CACEEDF8CCE39A7223D32AE1B6BADAE2C2AB01BF75F543DBB8A408514C4B2CD81801F9EAC1AA52257C7830F120B1536380B23161F734330744CE204A98BBD9DBEEDE484E9B03937C26689526597C8EDB98E6191B72C95FBC76468B8D48437E3AF46BC36F8176C540CAAB3FC989A3F511B54FA2350E3D31C2F6162F", "3173A712ED715B321A849279BE6BA237FC90DEC0E48B0E1290E81CB86C2A10EED50F3E05E616BE098E3F1DA2E6125238C2E2F45A8753AA613C1AE250E304C6FF093A6B799CC34CA2FD4AF81D5622076C2E8752593A27649576E12BA075CCF3E8F57B9635B77FEC448E2E89B2B5A3A81D65066285A70E24F868C35F6ECB8981F2"}, ] test "known HMACs are correctly calculated" do @golden_nist_test_vectors |> Enum.map(fn {algo, hmac, key, data} -> key = key |> Base.decode16! data = data |> Base.decode16! assert Hmac.generate(algo, key, data) |> Base.encode16 == hmac assert Hmac.is_authenticated?(algo, key, data, hmac |> Base.decode16!) end) end test "keyed HMAC implementation is equivalent to passing key" do keyed = Hmac.Keyed.new(:sha256, "key") keyed_mac = keyed |> Hmac.Keyed.generate("test") passed_key_mac = Hmac.generate(:sha256, "key", "test") assert keyed_mac == passed_key_mac assert Hmac.Keyed.is_authenticated?(keyed, "test", passed_key_mac) end test "HMAC calculation works with atoms for hasher" do assert Hmac.generate(:sha256, "key", "test") == Hmac.generate(Cryptex.Hasher.Algorithm.Sha256, "key", "test") end test "HMAC calculation works with enumerables" do assert Hmac.generate(:sha256, "key", ["te", "st"]) == Hmac.generate(:sha256, "key", "test") end test "HMAC calculation with data is equivalen to new followed by calculation" do assert Hmac.new(:sha256) |> Hmac.generate("key", "test") == Hmac.generate(:sha256, "key", "test") end test "HMAC hasher is the same as the algorithm passed to it" do assert Hmac.new(:sha256) |> Hmac.hasher == Hasher.new(:sha256) end test "HMAC digest size is the same as the underlying hash algorithm's digest size" do assert Hmac.new(:sha256) |> Hmac.digest_size == Hasher.new(:sha256) |> Hasher.digest_size end end
306.03
694
0.948502
79e01cdb48044534a2a6fa85daba25a960dac5e4
1,748
ex
Elixir
lib/owl/system.ex
kianmeng/owl
55c0f31438866d79526d1feab44e23728ad88dd6
[ "Apache-2.0" ]
null
null
null
lib/owl/system.ex
kianmeng/owl
55c0f31438866d79526d1feab44e23728ad88dd6
[ "Apache-2.0" ]
null
null
null
lib/owl/system.ex
kianmeng/owl
55c0f31438866d79526d1feab44e23728ad88dd6
[ "Apache-2.0" ]
null
null
null
defmodule Owl.System do @moduledoc """ An alternative to some `System` functions. """ require Logger @doc """ A wrapper around `System.cmd/3` which additionally logs executed `command` and `args`. If URL is found in logged message, then password in it is masked with asterisks. ## Examples > Owl.System.cmd("echo", ["test"]) # 10:25:34.252 [debug] $ echo test {"test\\n", 0} > Owl.System.cmd("psql", ["postgresql://postgres:[email protected]:5432", "-tAc", "SELECT 1;"]) # 10:25:50.947 [debug] $ psql postgresql://postgres:********@127.0.0.1:5432 -tAc 'SELECT 1;' {"1\\n", 0} """ @spec cmd(binary(), [binary()], keyword()) :: {Collectable.t(), exit_status :: non_neg_integer()} def cmd(command, args, opts \\ []) do log_shell_command(command, args) System.cmd(command, args, opts) end defp log_shell_command(command, args) do command = case args do [] -> command args -> args = Enum.map_join(args, " ", fn arg -> if String.contains?(arg, [" ", ";"]) do "'" <> String.replace(arg, "'", "'\\''") <> "'" else arg end end) "#{command} #{args}" end command = sanitize_passwords_in_urls(command) Logger.debug("$ #{command}") end defp sanitize_passwords_in_urls(text) do Regex.replace(~r/\w+:\/\/[^ ]+/, text, fn value -> uri = URI.parse(value) case uri.userinfo do nil -> value userinfo -> [username, _password] = String.split(userinfo, ":") to_string(%{uri | userinfo: username <> ":********"}) end end) end end
25.333333
102
0.53032
79e051d1bb2a5852ee80a5a59100f692567e802a
59
ex
Elixir
nomads/src/lib/nomads_web/views/page_view.ex
HarpBytes/nomads
10c79953e19262d9d095a190eecb09a5e57e6bf2
[ "MIT" ]
null
null
null
nomads/src/lib/nomads_web/views/page_view.ex
HarpBytes/nomads
10c79953e19262d9d095a190eecb09a5e57e6bf2
[ "MIT" ]
null
null
null
nomads/src/lib/nomads_web/views/page_view.ex
HarpBytes/nomads
10c79953e19262d9d095a190eecb09a5e57e6bf2
[ "MIT" ]
null
null
null
defmodule NomadsWeb.PageView do use NomadsWeb, :view end
14.75
31
0.79661
79e05c6180125755788009a7a9b57a1eb82f1545
1,223
ex
Elixir
src/dguweb/web/views/error_helpers.ex
datagovuk/dgu2
3e24bdf27b30c22791efc19029ead05488c8f571
[ "MIT" ]
2
2016-08-09T16:46:52.000Z
2016-08-09T16:46:59.000Z
src/dguweb/web/views/error_helpers.ex
datagovuk/dgu2
3e24bdf27b30c22791efc19029ead05488c8f571
[ "MIT" ]
48
2016-07-14T15:12:41.000Z
2016-09-27T16:19:54.000Z
src/dguweb/web/views/error_helpers.ex
datagovuk/dgu2
3e24bdf27b30c22791efc19029ead05488c8f571
[ "MIT" ]
1
2021-04-10T21:23:44.000Z
2021-04-10T21:23:44.000Z
defmodule DGUWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do if error = form.errors[field] do content_tag :span, translate_error(error), class: "help-block" end end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(DGUWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(DGUWeb.Gettext, "errors", msg, opts) end end end
29.829268
72
0.666394
79e05c9c010ec2b7dba63eba5a5b9bb3e7b546eb
2,130
ex
Elixir
lib/cforum_web/controllers/admin/event_controller.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
lib/cforum_web/controllers/admin/event_controller.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
lib/cforum_web/controllers/admin/event_controller.ex
campingrider/cforum_ex
cf27684c47d6dc26c9c37a946f1c729a79d27c70
[ "MIT" ]
null
null
null
defmodule CforumWeb.Admin.EventController do use CforumWeb, :controller alias Cforum.Events alias Cforum.Events.Event alias CforumWeb.Sortable alias CforumWeb.Paginator def index(conn, params) do {sort_params, conn} = Sortable.sort_collection(conn, [:name, :location, :start_date, :end_date, :visible], dir: :desc) count = Events.count_events() paging = Paginator.paginate(count, page: params["p"]) events = Events.list_events(limit: paging.params, order: sort_params) render(conn, "index.html", events: events, page: paging) end def new(conn, _params) do changeset = Events.change_event(%Event{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"event" => event_params}) do case Events.create_event(conn.assigns.current_user, event_params) do {:ok, event} -> conn |> put_flash(:info, gettext("Event created successfully.")) |> redirect(to: Path.admin_event_path(conn, :edit, event)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "new.html", changeset: changeset) end end def edit(conn, %{"id" => id}) do event = Events.get_event!(id) changeset = Events.change_event(event) render(conn, "edit.html", event: event, changeset: changeset) end def update(conn, %{"id" => id, "event" => event_params}) do event = Events.get_event!(id) case Events.update_event(conn.assigns.current_user, event, event_params) do {:ok, event} -> conn |> put_flash(:info, gettext("Event updated successfully.")) |> redirect(to: Path.admin_event_path(conn, :edit, event)) {:error, %Ecto.Changeset{} = changeset} -> render(conn, "edit.html", event: event, changeset: changeset) end end def delete(conn, %{"id" => id}) do event = Events.get_event!(id) {:ok, _event} = Events.delete_event(conn.assigns.current_user, event) conn |> put_flash(:info, gettext("Event deleted successfully.")) |> redirect(to: Path.admin_event_path(conn, :index)) end def allowed?(conn, _, _), do: Abilities.admin?(conn) end
30.869565
102
0.658685
79e07df4fc4611807a651b736c48c9c26bf03f5f
356
exs
Elixir
priv/repo/seeds.exs
bhelx/AndroidTracker
f628701e5680874cf67e2d4cf8ed0ad1599b3308
[ "MIT" ]
4
2016-05-02T11:40:19.000Z
2019-02-26T20:31:18.000Z
priv/repo/seeds.exs
bhelx/AndroidTracker
f628701e5680874cf67e2d4cf8ed0ad1599b3308
[ "MIT" ]
null
null
null
priv/repo/seeds.exs
bhelx/AndroidTracker
f628701e5680874cf67e2d4cf8ed0ad1599b3308
[ "MIT" ]
null
null
null
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # BhelxTrack.Repo.insert!(%BhelxTrack.SomeModel{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong.
29.666667
61
0.710674
79e08cc10a8966f3335f2b21eb3edf61592042b6
5,218
ex
Elixir
lib/sanbase/kafka/kafka_exporter.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
lib/sanbase/kafka/kafka_exporter.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
1
2021-07-24T16:26:03.000Z
2021-07-24T16:26:03.000Z
lib/sanbase/kafka/kafka_exporter.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
defmodule Sanbase.KafkaExporter do @moduledoc ~s""" Module for persisting any data to Kafka. The module exposes one function that should be used - `persist/1`. This functions adds the data to an internal buffer that is flushed every `kafka_flush_timeout` seconds or when the buffer is big enough. The exporter cannot send data more than once every 1 second so the GenServer cannot die too often and crash its supervisor """ use GenServer require Logger require Sanbase.Utils.Config, as: Config @producer Config.get(:producer) @type data :: {String.t(), String.t()} @type result :: :ok | {:error, String.t()} @typedoc ~s""" Options that describe to which kafka topic and how often to send the batches. These options do not describe the connection """ @type options :: [ {:name, atom()} | {:topic, String.t()} | {:kafka_flush_timeout, non_neg_integer()} | {:buffering_max_messages, non_neg_integer()} | {:can_send_after_interval, non_neg_integer()} ] @spec start_link(options) :: GenServer.on_start() def start_link(opts) do name = Keyword.get(opts, :name, __MODULE__) GenServer.start_link(__MODULE__, opts, name: name) end @spec init(options) :: {:ok, state} when state: map() def init(opts) do kafka_flush_timeout = Keyword.get(opts, :kafka_flush_timeout, 30_000) buffering_max_messages = Keyword.get(opts, :buffering_max_messages, 1000) can_send_after_interval = Keyword.get(opts, :can_send_after_interval, 1000) Process.send_after(self(), :flush, kafka_flush_timeout) {:ok, %{ topic: Keyword.fetch!(opts, :topic), data: [], size: 0, kafka_flush_timeout: kafka_flush_timeout, buffering_max_messages: buffering_max_messages, can_send_after_interval: can_send_after_interval, can_send_after: DateTime.utc_now() |> DateTime.add(can_send_after_interval, :millisecond) }} end @doc ~s""" Asynchronously add data to be exported to the buffer. It will be sent no longer than `kafka_flush_timeout` seconds later. The data is pushed to an internal buffer that is then send at once to Kafka. """ @spec persist(data | [data], pid() | atom()) :: :ok def persist(data, exporter \\ __MODULE__) do GenServer.cast(exporter, {:persist, data}) end @spec persist_sync(data | [data], pid() | atom()) :: result def persist_sync(data, exporter \\ __MODULE__) do GenServer.call(exporter, {:persist, data}) end def flush(exporter \\ __MODULE__) do GenServer.call(exporter, :flush) end @doc ~s""" Send all available data in the buffers before shutting down. The data recorder should be started before the Endpoint in the supervison tree. This means that when shutting down it will be stopped after the Endpoint so all data will be stored in Kafka and no more data is expected. """ def terminate(_reason, state) do Logger.info( "Terminating the KafkaExporter. Sending #{length(state.data)} events to kafka topic: #{ state.topic }" ) send_data(state.data, state) :ok end @spec handle_call({:persist, data | [data]}, any(), state) :: {:reply, result, state} when state: map() def handle_call({:persist, data}, _from, state) do data = List.wrap(data) send_data_result = (data ++ state.data) |> send_data_immediately(%{state | size: state.size + length(data)}) {:reply, send_data_result, %{state | data: [], size: 0}} end def handle_call(:flush, _from, state) do send_data_immediately(state.data, state) {:reply, :ok, %{state | data: [], size: 0}} end @spec handle_cast({:persist, data | [data]}, state) :: {:noreply, state} when state: map() def handle_cast({:persist, data}, state) do data = List.wrap(data) new_messages_length = length(data) case state.size + new_messages_length >= state.buffering_max_messages do true -> :ok = send_data(data ++ state.data, %{state | size: state.size + new_messages_length}) {:noreply, %{ state | data: [], size: 0, can_send_after: DateTime.utc_now() |> DateTime.add(state.can_send_after_interval, :millisecond) }} false -> {:noreply, %{state | data: data ++ state.data, size: state.size + new_messages_length}} end end def handle_info(:flush, state) do send_data(state.data, state) Process.send_after(self(), :flush, state.kafka_flush_timeout) {:noreply, %{state | data: [], size: 0}} end defp send_data([], _), do: :ok defp send_data(nil, _), do: :ok defp send_data(data, %{topic: topic, can_send_after: can_send_after, size: size}) do Sanbase.DateTimeUtils.sleep_until(can_send_after) Logger.info("Sending #{size} events to Kafka topic: #{topic}") @producer.send_data(topic, data) end defp send_data_immediately([], _), do: :ok defp send_data_immediately(nil, _), do: :ok defp send_data_immediately(data, %{topic: topic, size: size}) do Logger.info("Sending #{size} events to Kafka topic: #{topic}") @producer.send_data(topic, data) end end
31.817073
96
0.662898
79e0cb7ba6f4991ab14f1dfc9b97f3af82197b4f
826
exs
Elixir
test/kira/runtime/apply_test.exs
AKST/kira
bef6d8a6004c01b572d624f734e769ab0a5047df
[ "MIT" ]
null
null
null
test/kira/runtime/apply_test.exs
AKST/kira
bef6d8a6004c01b572d624f734e769ab0a5047df
[ "MIT" ]
5
2018-11-17T06:13:30.000Z
2018-11-17T06:18:23.000Z
test/kira/runtime/apply_test.exs
AKST/kira
bef6d8a6004c01b572d624f734e769ab0a5047df
[ "MIT" ]
null
null
null
defmodule Kira.Runtime.ApplyTest do use ExUnit.Case alias Kira, as: T alias Kira.Util.Testing, as: Util describe "start" do test "it works" do a = %T.Branch{name: :a, apply: fn _, _ -> {:ok, 12} end} {:ok, state} = T.RuntimeState.create(:undefined, [a], :infinity) assert state.branch_states.a.task == :not_started assert Enum.count(state.running) == 0 {:ok, state} = T.Runtime.Apply.start(state, :a) assert elem(state.branch_states.a.task, 0) == :running_apply assert Enum.count(state.running) == 1 assert_receive {:apply_exit, a, {:ok, 12}} end test "start non existent branch" do {:ok, state} = T.RuntimeState.create(:undefined, [], :infinity) result = T.Runtime.Apply.start(state, :a) assert Util.is_error(result) end end end
30.592593
70
0.633172
79e0d46b1192193dd48a42ea5db58353f769d133
3,047
ex
Elixir
lib/ex_slp/tool.ex
4pcbr/ex_slp_tk
91a9f435cdc62224219409b9560a031d5ff4bb39
[ "MIT" ]
2
2016-03-01T22:16:18.000Z
2016-04-14T23:10:01.000Z
lib/ex_slp/tool.ex
4pcbr/ex_slp_tk
91a9f435cdc62224219409b9560a031d5ff4bb39
[ "MIT" ]
null
null
null
lib/ex_slp/tool.ex
4pcbr/ex_slp_tk
91a9f435cdc62224219409b9560a031d5ff4bb39
[ "MIT" ]
null
null
null
defmodule ExSlp.Tool do @default_slptool "slptool" @doc """ Returns a string that is used for invoking the slptool. By default this is simply "slptool" per the standard debian package name, but config.exs may override the value """ def slptool do Application.get_env( :ex_slp, :slptool, @default_slptool) end @doc """ Checks the status of `slptool` on the current system. Returns: { :ok, message } # in case of success { :not_executable, message } # in case the tool is installed but is not executable by the current user { :error, message } # otherwise """ def status do {:ok, executable} = String.split(slptool()) |> Enum.fetch(0) case System.find_executable(executable) do nil -> { :cmd_unknown, "The command #{executable} could not be found. Check your $PATH ENV variable." } { error, error_code } -> { :error, error, error_code } path -> path = String.strip( path ) case System.cmd( "test", [ "-x", path ] ) do { "", 0 } -> { :ok, "The toolkit is set up." } { "", 1 } -> { :not_executable, "The file #{path} is not executable for the current user." } { error, error_code } -> { :error, error, error_code } end end end @doc """ Executes `slptool` command `cmd` with `args` as command arguments and `opts` as the list of post-command options. Returns: { :ok, response } # in case of success, { :error, message } # otherwise. """ def exec_cmd( args, cmd ), do: exec_cmd( args, cmd, [] ) def exec_cmd( args, cmd, opts ) do # treat the slptool invocation string as if it might itself # be a command followed by arguments For example: # "docker run --rm vcrhonek/openslp slptool" [invocation | initial_args] = String.split(slptool()) case System.cmd( invocation, initial_args ++ args ++ [ cmd | opts ] ) do { res, 0 } -> { :ok, res |> String.strip } { err, 1 } -> { :error, err |> String.strip } end end @doc """ Gets the current slp toolkit version. Returns: { major, minor, patch } # if the toolkit is installed nil # otherwise Example: ExSlp.Tool.version > { 1, 2, 1 } case ExSlp.Tool.version do { 1, _, _ } -> # do v1 specific things { 2, _, _ } -> # do v2 specific things end """ def version do case exec_cmd( [], "-v" ) do { :ok, res } -> case String.split( res, "\n" ) |> Enum.filter( fn str -> Regex.match?( ~r/slptool\sversion/, str ) end ) |> List.first do nil -> nil version_str -> case Regex.run( ~r/([\d\.]+)$/, version_str ) do nil -> nil [ _, ver ] -> ver |> String.split(".") |> Enum.map( &String.to_integer/1 ) |> List.to_tuple _ -> nil end end _ -> nil end end end
32.414894
113
0.545126
79e0d8b34a572152625fc1dc4642c2ecf7d396cc
938
exs
Elixir
test/slax_web/controllers/slax_controller_test.exs
HoffsMH/slax
b91ee30b9fd71a4cb7826f50b605ce580b7c1651
[ "MIT" ]
11
2016-07-05T18:56:21.000Z
2021-09-15T22:23:54.000Z
test/slax_web/controllers/slax_controller_test.exs
HoffsMH/slax
b91ee30b9fd71a4cb7826f50b605ce580b7c1651
[ "MIT" ]
181
2016-06-23T00:47:13.000Z
2022-03-10T11:23:44.000Z
test/slax_web/controllers/slax_controller_test.exs
HoffsMH/slax
b91ee30b9fd71a4cb7826f50b605ce580b7c1651
[ "MIT" ]
7
2019-01-30T21:38:28.000Z
2022-03-01T07:13:39.000Z
defmodule SlaxWeb.SlaxController.Test do use SlaxWeb.ConnCase, async: true setup %{conn: conn} do user = insert(:user) conn = assign(conn, :user_id, user.id) [conn: conn, user: user] end test "responds to ping", %{conn: conn, user: user} do params = %{ token: "token", text: "ping", channel_id: "blah", timestamp: "12345", response_url: "https://google.com", user_id: user.slack_id } conn = conn |> post(slax_path(conn, :start), params) assert response(conn, 201) == "" end test "responds to roll command", %{conn: conn, user: user} do params = %{ token: "token", text: "roll 6", channel_id: "blah", timestamp: "12345", response_url: "https://google.com", user_id: user.slack_id } conn = conn |> post(slax_path(conn, :start), params) assert response(conn, 201) == "" end end
20.391304
63
0.570362
79e0ef582173602f9dcf2c70229c0ff27962083f
1,756
ex
Elixir
lib/grpc/transport/utils.ex
braverhealth/grpc
eff8a8828d27ddd7f63a3c1dd5aae86246df215e
[ "Apache-2.0" ]
561
2019-03-18T09:10:57.000Z
2022-03-27T17:34:59.000Z
lib/grpc/transport/utils.ex
braverhealth/grpc
eff8a8828d27ddd7f63a3c1dd5aae86246df215e
[ "Apache-2.0" ]
94
2019-03-20T09:34:38.000Z
2022-02-27T20:44:04.000Z
lib/grpc/transport/utils.ex
braverhealth/grpc
eff8a8828d27ddd7f63a3c1dd5aae86246df215e
[ "Apache-2.0" ]
112
2019-03-25T03:27:26.000Z
2022-03-21T12:43:59.000Z
defmodule GRPC.Transport.Utils do @moduledoc false # unit: ns @ns_ceiling 1000 @us_ceiling 1000_000 # @ms_ceiling @us_ceiling * 1000 # unit: ms @ms_ceiling 1000 @second_ceiling @ms_ceiling * 60 @minute_ceiling @second_ceiling * 60 @doc """ Encode timeout(nanoseconds) by gRPC protocol """ def encode_ns(timeout) when timeout <= 0, do: "0u" def encode_ns(timeout) when is_integer(timeout) and timeout < @ns_ceiling do to_string(timeout) <> "n" end def encode_ns(timeout) when timeout < @us_ceiling do to_string(div(timeout, 1000)) <> "u" end @doc """ Encode timeout(milliseconds) by gRPC protocol """ def encode_timeout(timeout) when timeout <= 0, do: "0u" def encode_timeout(timeout) when is_integer(timeout) and timeout < @ms_ceiling do to_string(timeout) <> "m" end def encode_timeout(timeout) when timeout < @second_ceiling do to_string(div(timeout, 1000)) <> "S" end def encode_timeout(timeout) when timeout < @minute_ceiling do to_string(div(timeout, 1000 * 60)) <> "M" end def encode_timeout(timeout) do to_string(div(timeout, 1000 * 3600)) <> "H" end @spec decode_timeout(String.t()) :: non_neg_integer() def decode_timeout(timeout) do {timeout, unit} = String.split_at(timeout, -1) decode_timeout(unit, String.to_integer(timeout)) end defp decode_timeout("n", timeout) do div(timeout, 1000_000) end defp decode_timeout("u", timeout) do div(timeout, 1000) end defp decode_timeout("m", timeout) do timeout end defp decode_timeout("S", timeout) do timeout * 1000 end defp decode_timeout("M", timeout) do timeout * 60_000 end defp decode_timeout("H", timeout) do timeout * 3_600_000 end end
22.512821
83
0.68508
79e10097a47c495c8b02ac71ac303306d7a88b58
1,778
ex
Elixir
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/remove_deal_association_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/remove_deal_association_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/remove_deal_association_request.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.RemoveDealAssociationRequest do @moduledoc """ A request for removing the association between a deal and a creative. ## Attributes * `association` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.CreativeDealAssociation.t`, *default:* `nil`) - The association between a creative and a deal that should be removed. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :association => GoogleApi.AdExchangeBuyer.V2beta1.Model.CreativeDealAssociation.t() | nil } field(:association, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.CreativeDealAssociation) end defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.RemoveDealAssociationRequest do def decode(value, options) do GoogleApi.AdExchangeBuyer.V2beta1.Model.RemoveDealAssociationRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.RemoveDealAssociationRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.041667
187
0.767154
79e14fd05ac1e70c801858a07637bd34aefc99ce
1,558
ex
Elixir
lib/comparator_web/views/error_helpers.ex
jellybob/comparator
e9528341366641baa7fa49690fdd6ffa3e2159a0
[ "MIT" ]
null
null
null
lib/comparator_web/views/error_helpers.ex
jellybob/comparator
e9528341366641baa7fa49690fdd6ffa3e2159a0
[ "MIT" ]
null
null
null
lib/comparator_web/views/error_helpers.ex
jellybob/comparator
e9528341366641baa7fa49690fdd6ffa3e2159a0
[ "MIT" ]
null
null
null
defmodule ComparatorWeb.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ use Phoenix.HTML @doc """ Generates tag for inlined form input errors. """ def error_tag(form, field) do Enum.map(Keyword.get_values(form.errors, field), fn error -> content_tag(:span, translate_error(error), class: "invalid-feedback", phx_feedback_for: input_name(form, field) ) end) end @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # When using gettext, we typically pass the strings we want # to translate as a static argument: # # # Translate "is invalid" in the "errors" domain # dgettext("errors", "is invalid") # # # Translate the number of files with plural rules # dngettext("errors", "1 file", "%{count} files", count) # # Because the error messages we show in our forms and APIs # are defined inside Ecto, we need to translate them dynamically. # This requires us to call the Gettext module passing our gettext # backend as first argument. # # Note we use the "errors" domain, which means translations # should be written to the errors.po file. The :count option is # set by Ecto and indicates we should also apply plural rules. if count = opts[:count] do Gettext.dngettext(ComparatorWeb.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(ComparatorWeb.Gettext, "errors", msg, opts) end end end
32.458333
79
0.667522
79e15c75bb24d8c28de1a9f9224af5e90d3d0eb5
1,835
ex
Elixir
clients/datastore/lib/google_api/datastore/v1/model/google_datastore_admin_v1_export_entities_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/datastore/lib/google_api/datastore/v1/model/google_datastore_admin_v1_export_entities_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/datastore/lib/google_api/datastore/v1/model/google_datastore_admin_v1_export_entities_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1ExportEntitiesResponse do @moduledoc """ The response for google.datastore.admin.v1.DatastoreAdmin.ExportEntities. ## Attributes * `outputUrl` (*type:* `String.t`, *default:* `nil`) - Location of the output metadata file. This can be used to begin an import into Cloud Datastore (this project or another project). See google.datastore.admin.v1.ImportEntitiesRequest.input_url. Only present if the operation completed successfully. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :outputUrl => String.t() } field(:outputUrl) end defimpl Poison.Decoder, for: GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1ExportEntitiesResponse do def decode(value, options) do GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1ExportEntitiesResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Datastore.V1.Model.GoogleDatastoreAdminV1ExportEntitiesResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.767857
132
0.752044
79e1626402834a983d9bf26bdc7ce9e9637c779e
2,160
ex
Elixir
lib/app.ex
xio/emqx
e213feb1c8fe95ae2c10ff87d2cecef3a66b5279
[ "Apache-2.0" ]
null
null
null
lib/app.ex
xio/emqx
e213feb1c8fe95ae2c10ff87d2cecef3a66b5279
[ "Apache-2.0" ]
null
null
null
lib/app.ex
xio/emqx
e213feb1c8fe95ae2c10ff87d2cecef3a66b5279
[ "Apache-2.0" ]
null
null
null
defmodule Emqx.App do use Application use Supervisor require Logger def print_banner(), do: :io.format("Starting ~s on node ~s~n", [:emqx, node()]) def print_vsn() do {:ok, descr} = :application.get_key(:description) {:ok, vsn} = :application.get_key(:vsn) :io.format("~s ~s is running now!~n", [descr, vsn]) end defp child(module), do: %{:id => module, :start => {module, :start_link, []}, :restart => :permanent, :shutdown => :infinity, :type => :supervisor, :modules => [module] } defp prepend(xs,true,it), do: xs++[it] defp prepend(xs,_,_), do: xs def spec(), do: [ child(:emqx_kernel_sup), child(:emqx_sys_sup), child(:emqx_mod_sup), child(:xio_http_sup) ] |> prepend(:emqx_boot.is_enabled(:router), child(:emqx_router_sup)) |> prepend(:emqx_boot.is_enabled(:broker), child(:emqx_broker_sup)) |> prepend(:emqx_boot.is_enabled(:broker), child(:emqx_cm_sup)) @impl true def init([]) do Supervisor.init(spec(), strategy: :one_for_all, max_restart: 0, max_seconds: 1) end @impl true def start(_,arg) do :logger.add_handlers(:emqx) print_banner() :ok = :ekka.start() {:ok, sup} = Supervisor.start_link(__MODULE__, arg, name: __MODULE__) :ok = :emqx_modules.load() :ok = :emqx_plugins.init() :emqx_plugins.load() if :emqx_boot.is_enabled(:listeners), do: :ok = :emqx_listeners.start() :ekka.callback(:prepare, &:emqx.shutdown/1) :ekka.callback(:reboot, &:emqx.reboot/0) :ekka.autocluster(:emqx) :erlang.register(:emqx, self()) print_vsn() :emqx_mgmt_auth.add_default_app() :emqx_mgmt_cli.load() {:ok, sup} end @impl true def stop(_) do :ekka_mnesia.ensure_stopped() :emqx_boot.is_enabled(:listeners) and :emqx_listeners.stop() :emqx_modules.unload() end end
30
85
0.548611
79e1a9f9ba534763f5dbacce5feeb1715f9785f1
16,434
ex
Elixir
lib/elixir/lib/process.ex
diogovk/elixir
7b8213affaad38b50afaa3dfc3a43717f35ba4e7
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/process.ex
diogovk/elixir
7b8213affaad38b50afaa3dfc3a43717f35ba4e7
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/process.ex
diogovk/elixir
7b8213affaad38b50afaa3dfc3a43717f35ba4e7
[ "Apache-2.0" ]
null
null
null
defmodule Process do @moduledoc """ Conveniences for working with processes and the process dictionary. Besides the functions available in this module, the `Kernel` module exposes and auto-imports some basic functionality related to processes available through the functions: * `Kernel.spawn/1` and `Kernel.spawn/3` * `Kernel.spawn_link/1` and `Kernel.spawn_link/3` * `Kernel.spawn_monitor/1` and `Kernel.spawn_monitor/3` * `Kernel.self/0` * `Kernel.send/2` """ @doc """ Returns `true` if the process exists and is alive (i.e. it is not exiting and has not exited yet). Otherwise, returns `false`. `pid` must refer to a process at the local node. Inlined by the compiler. """ @spec alive?(pid) :: boolean def alive?(pid) do :erlang.is_process_alive(pid) end @doc """ Returns all key-value pairs in the process dictionary. Inlined by the compiler. """ @spec get :: [{term, term}] def get do :erlang.get() end @doc """ Returns the value for the given `key` or `default` if `key` is not set. """ @spec get(term) :: term @spec get(term, default :: term) :: term def get(key, default \\ nil) do case :erlang.get(key) do :undefined -> default value -> value end end @doc """ Returns all keys in the process dictionary. Inlined by the compiler. """ @spec get_keys() :: [term] def get_keys() do :erlang.get_keys() end @doc """ Returns all keys that have the given `value`. Inlined by the compiler. """ @spec get_keys(term) :: [term] def get_keys(value) do :erlang.get_keys(value) end @doc """ Stores the given `key`-`value` pair in the process dictionary. The return value is the value that was previously stored under the key `key` (or `nil` in case no value was stored under `key`). """ @spec put(term, term) :: term | nil def put(key, value) do nillify :erlang.put(key, value) end @doc """ Deletes the given `key` from the process dictionary. """ @spec delete(term) :: term | nil def delete(key) do nillify :erlang.erase(key) end @doc """ Sends an exit signal with the given `reason` to the `pid`. The following behaviour applies if `reason` is any term except `:normal` or `:kill`: 1. If `pid` is not trapping exits, `pid` will exit with the given `reason`. 2. If `pid` is trapping exits, the exit signal is transformed into a message `{:EXIT, from, reason}` and delivered to the message queue of `pid`. 3. If `reason` is the atom `:normal`, `pid` will not exit (unless it is the calling process's pid, in which case it will exit with the reason `:normal`). If it is trapping exits, the exit signal is transformed into a message `{:EXIT, from, :normal}` and delivered to its message queue. 4. If `reason` is the atom `:kill`, that is if `exit(pid, :kill)` is called, an untrappable exit signal is sent to `pid` which will unconditionally exit with exit reason `:killed`. Inlined by the compiler. ## Examples Process.exit(pid, :kill) """ @spec exit(pid, term) :: true def exit(pid, reason) do :erlang.exit(pid, reason) end @doc """ Sleeps the current process by `timeout`. `timeout` is either the number of milliseconds to sleep as an integer or the atom `:infinity`. When `:infinity` is given, the current process will suspend forever. **Use this function with extreme care**. For almost all situations where you would use `sleep/1` in Elixir, there is likely a more correct, faster and precise way of achieving it with message passing. For example, if you are waiting a process to perform some action, it is better to communicate. In other words, **do not**: Task.start_link fn -> do_something() ... end # Wait until work is done Process.sleep(2000) But **do**: parent = self() Task.start_link fn -> do_something() send parent, :work_is_done ... end receive do :work_is_done -> :ok after 30_000 -> :timeout # Optional timeout end Or even use `Task.async/1` and `Task.await/2` in the example above. Similarly, if you are waiting for a process to terminate, use monitor instead of sleep. **Do not**: Task.start_link fn -> ... end # Wait until task terminates Process.sleep(2000) Instead **do**: {:ok, pid} = Task.start_link fn -> ... end ref = Process.monitor(pid) receive do {:DOWN, ^ref, _, _, _} -> :task_is_down after 30_000 -> :timeout # Optional timeout end """ def sleep(timeout) when is_integer(timeout) and timeout >= 0 when timeout == :infinity do receive after: (timeout -> :ok) end @doc """ Sends a message to the given process. If the option `:noconnect` is used and sending the message would require an auto-connection to another node the message is not sent and `:noconnect` is returned. If the option `:nosuspend` is used and sending the message would cause the sender to be suspended the message is not sent and `:nosuspend` is returned. Otherwise the message is sent and `:ok` is returned. ## Examples iex> Process.send({:name, :node_does_not_exist}, :hi, [:noconnect]) :noconnect """ @spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend when dest: pid | port | atom | {atom, node}, msg: any, option: :noconnect | :nosuspend def send(dest, msg, options) do :erlang.send(dest, msg, options) end @doc """ Sends `msg` to `dest` after `time` milliseconds. If `dest` is a pid, it must be the pid of a local process, dead or alive. If `dest` is an atom, it must be the name of a registered process which is looked up at the time of delivery. No error is given if the name does not refer to a process. This function returns a timer reference, which can be read or canceled with `read_timer/1` and `cancel_timer/1`. Finally, the timer will be automatically canceled if the given `dest` is a pid which is not alive or when the given pid exits. Note that timers will not be automatically canceled when `dest` is an atom (as the atom resolution is done on delivery). """ @spec send_after(pid | atom, term, non_neg_integer) :: reference def send_after(dest, msg, time) do :erlang.send_after(time, dest, msg) end @doc """ Cancels a timer created by `send_after/3`. When the result is an integer, it represents the time in milliseconds left until the timer would have expired. When the result is `false`, a timer corresponding to `timer_ref` could not be found. This can be either because the timer expired, already has been canceled, or because `timer_ref` never corresponded to a timer. If the timer has expired, the timeout message has been sent, but it does not tell you whether or not it has arrived at its destination yet. Inlined by the compiler. """ @spec cancel_timer(reference) :: non_neg_integer | false def cancel_timer(timer_ref) do :erlang.cancel_timer(timer_ref) end @doc """ Reads a timer created by `send_after/3`. When the result is an integer, it represents the time in milliseconds left until the timer will expire. When the result is `false`, a timer corresponding to `timer_ref` could not be found. This can be either because the timer expired, already has been canceled, or because `timer_ref` never corresponded to a timer. If the timer has expired, the timeout message has been sent, but it does not tell you whether or not it has arrived at its destination yet. Inlined by the compiler. """ @spec read_timer(reference) :: non_neg_integer | false def read_timer(timer_ref) do :erlang.read_timer(timer_ref) end @type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} | {:fullsweep_after, non_neg_integer} | {:min_heap_size, non_neg_integer} | {:min_bin_vheap_size, non_neg_integer} @type spawn_opts :: [spawn_opt] @doc """ Spawns the given function according to the given options. The result depends on the given options. In particular, if `:monitor` is given as an option, it will return a tuple containing the pid and the monitoring reference, otherwise just the spawned process pid. It also accepts extra options, for the list of available options check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4). Inlined by the compiler. """ @spec spawn((() -> any), spawn_opts) :: pid | {pid, reference} def spawn(fun, opts) do :erlang.spawn_opt(fun, opts) end @doc """ Spawns the given function from module `mod`, passing the given `args` according to the given options. The result depends on the given options. In particular, if `:monitor` is given as an option, it will return a tuple containing the pid and the monitoring reference, otherwise just the spawned process pid. It also accepts extra options, for the list of available options check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4). Inlined by the compiler. """ @spec spawn(module, atom, list, spawn_opts) :: pid | {pid, reference} def spawn(mod, fun, args, opts) do :erlang.spawn_opt(mod, fun, args, opts) end @doc """ The calling process starts monitoring the given `item`. It returns the monitor reference. See [the need for monitoring](http://elixir-lang.org/getting-started/mix-otp/genserver.html#the-need-for-monitoring) for an example. See [`:erlang.monitor/2`](http://www.erlang.org/doc/man/erlang.html#monitor-2) for more info. Inlined by the compiler. """ @spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference def monitor(item) do :erlang.monitor(:process, item) end @doc """ If `monitor_ref` is a reference which the calling process obtained by calling `monitor/1`, this monitoring is turned off. If the monitoring is already turned off, nothing happens. See [`:erlang.demonitor/2`](http://www.erlang.org/doc/man/erlang.html#demonitor-2) for more info. Inlined by the compiler. """ @spec demonitor(reference) :: true @spec demonitor(reference, options :: [:flush | :info]) :: boolean def demonitor(monitor_ref, options \\ []) do :erlang.demonitor(monitor_ref, options) end @doc """ Returns a list of process identifiers corresponding to all the processes currently existing on the local node. Note that a process that is exiting, exists but is not alive, i.e., `alive?/1` will return `false` for a process that is exiting, but its process identifier will be part of the result returned. See [`:erlang.processes/0`](http://www.erlang.org/doc/man/erlang.html#processes-0) for more info. """ @spec list :: [pid] def list do :erlang.processes() end @doc """ Creates a link between the calling process and another process (or port) `pid`, if there is not such a link already. See [`:erlang.link/1`](http://www.erlang.org/doc/man/erlang.html#link-1) for more info. Inlined by the compiler. """ @spec link(pid | port) :: true def link(pid) do :erlang.link(pid) end @doc """ Removes the link, if there is one, between the calling process and the process or port referred to by `pid`. Returns `true` and does not fail, even if there is no link or `id` does not exist See [`:erlang.unlink/1`](http://www.erlang.org/doc/man/erlang.html#unlink-1) for more info. Inlined by the compiler. """ @spec unlink(pid | port) :: true def unlink(pid) do :erlang.unlink(pid) end @doc """ Associates the atom `name` with a `pid` or a port identifier. `name`, can then be used instead of the `pid` / port identifier with the `Kernel.send/2` function. `Process.register/2` will fail with `ArgumentError` if the pid supplied is no longer alive, (check with `alive?/1`) or if the name is already registered (check with `whereis/1`) or if the `pid` is already registered to a different `name`. """ @spec register(pid | port, atom) :: true def register(pid, name) when not name in [nil, false, true] and is_atom(name) do :erlang.register(name, pid) end @doc """ Removes the registered `name`, associated with a pid or a port identifier. Fails with `ArgumentError` if the name is not registered to any pid or port. See [`:erlang.unregister/1`](http://www.erlang.org/doc/man/erlang.html#unregister-1) for more info. """ @spec unregister(atom) :: true def unregister(name) do :erlang.unregister(name) end @doc """ Returns the pid or port identifier with the registered `name`. Returns `nil` if the name is not registered. See [`:erlang.whereis/1`](http://www.erlang.org/doc/man/erlang.html#whereis-1) for more info. """ @spec whereis(atom) :: pid | port | nil def whereis(name) do nillify :erlang.whereis(name) end @doc """ Returns the pid of the group leader for the process which evaluates the function. """ @spec group_leader :: pid def group_leader do :erlang.group_leader end @doc """ Sets the group leader of `pid` to `leader`. Typically, this is used when a processes started from a certain shell should have a group leader other than `:init`. """ @spec group_leader(pid, leader :: pid) :: true def group_leader(pid, leader) do :erlang.group_leader(leader, pid) end @doc """ Returns a list of names which have been registered using `register/2`. """ @spec registered :: [atom] def registered do :erlang.registered() end @typep process_flag :: :trap_exit | :error_handler | :min_heap_size | :min_bin_vheap_size | :priority | :save_calls | :sensitive @doc """ Sets certain flags for the process which calls this function. Returns the old value of the `flag`. See [`:erlang.process_flag/2`](http://www.erlang.org/doc/man/erlang.html#process_flag-2) for more info. """ @spec flag(process_flag, term) :: term def flag(flag, value) do :erlang.process_flag(flag, value) end @doc """ Sets certain flags for the process `pid`, in the same manner as `flag/2`. Returns the old value of the `flag`. The allowed values for `flag` are only a subset of those allowed in `flag/2`, namely `:save_calls`. See [`:erlang.process_flag/3`](http://www.erlang.org/doc/man/erlang.html#process_flag-3) for more info. """ @spec flag(pid, :save_calls, non_neg_integer) :: non_neg_integer def flag(pid, flag, value) do :erlang.process_flag(pid, flag, value) end @doc """ Returns information about the process identified by `pid`, or returns `nil` if the process is not alive. Use this only for debugging information. See [`:erlang.process_info/1`](http://www.erlang.org/doc/man/erlang.html#process_info-1) for more info. """ @spec info(pid) :: Keyword.t def info(pid) do nillify :erlang.process_info(pid) end @doc """ Returns information about the process identified by `pid`, or returns `nil` if the process is not alive. See [`:erlang.process_info/2`](http://www.erlang.org/doc/man/erlang.html#process_info-2) for more info. """ @spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil def info(pid, spec) def info(pid, :registered_name) do case :erlang.process_info(pid, :registered_name) do :undefined -> nil [] -> {:registered_name, []} other -> other end end def info(pid, spec) when is_atom(spec) or is_list(spec) do nillify :erlang.process_info(pid, spec) end @doc """ Puts the calling process into a wait state where its memory allocation has been reduced as much as possible, which is useful if the process does not expect to receive any messages in the near future. See [`:erlang.hibernate/3`](http://www.erlang.org/doc/man/erlang.html#hibernate-3) for more info. Inlined by the compiler. """ @spec hibernate(module, atom, list) :: no_return def hibernate(mod, fun, args) do :erlang.hibernate(mod, fun, args) end @compile {:inline, nillify: 1} defp nillify(:undefined), do: nil defp nillify(other), do: other end
30.265193
118
0.672021
79e1cb1630e64bc51eabe3117d3edd81d5299ca6
1,905
exs
Elixir
clients/digital_asset_links/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/digital_asset_links/mix.exs
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/digital_asset_links/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.DigitalAssetLinks.Mixfile do use Mix.Project @version "0.7.0" def project() do [ app: :google_api_digital_asset_links, 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/digital_asset_links" ] 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 """ Digital Asset Links API client library. Discovers relationships between online assets such as websites or mobile apps. """ 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/digital_asset_links", "Homepage" => "https://developers.google.com/digital-asset-links/" } ] end end
28.432836
122
0.665617
79e1d900c43cc97080e846dfdbf34cebdc380479
5,103
exs
Elixir
apps/potterhat_node/test/node/active_nodes_test.exs
omisego/potterhat
47635e5d061c76900bd0e42a19e5dfc2ae8c0253
[ "Apache-2.0" ]
6
2019-03-28T14:47:41.000Z
2019-06-25T02:38:06.000Z
apps/potterhat_node/test/node/active_nodes_test.exs
omisego/potterhat
47635e5d061c76900bd0e42a19e5dfc2ae8c0253
[ "Apache-2.0" ]
30
2019-05-22T10:08:09.000Z
2019-08-02T06:37:56.000Z
apps/potterhat_node/test/node/active_nodes_test.exs
omisego/potterhat
47635e5d061c76900bd0e42a19e5dfc2ae8c0253
[ "Apache-2.0" ]
null
null
null
# Copyright 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 PotterhatNode.ActiveNodesTest do use ExUnit.Case, async: true alias PotterhatNode.ActiveNodes setup do # Starts an isolated ActiveNodes server so we can test different cases independently. # In real world use case we only need a single instance of ActiveNodes, # so we can call ActiveNodes functions without passing its pid, unlike these tests. {:ok, active_nodes_pid} = GenServer.start_link(ActiveNodes, [], name: :"active_nodes_#{:rand.uniform(99_999_999)}") {:ok, %{ active_nodes_pid: active_nodes_pid }} end describe "all/1" do test "returns an empty list by default", meta do assert ActiveNodes.all(meta.active_nodes_pid) == [] end test "returns a list of pids", meta do {:ok, node_pid_1} = Agent.start(fn -> nil end) {:ok, node_pid_2} = Agent.start(fn -> nil end) :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_1, 10, "Node 1") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_2, 20, "Node 2") result = ActiveNodes.all(meta.active_nodes_pid) assert length(result) == 2 assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_1 end) assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_2 end) end end describe "count/1" do test "returns zero by default", meta do assert ActiveNodes.count(meta.active_nodes_pid) == 0 end test "returns the number of active nodes", meta do {:ok, node_pid_1} = Agent.start(fn -> nil end) {:ok, node_pid_2} = Agent.start(fn -> nil end) :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_1, 10, "Node 1") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_2, 20, "Node 2") assert ActiveNodes.count(meta.active_nodes_pid) == 2 end end describe "first/1" do test "returns the pid with the top priority", meta do {:ok, node_pid_1} = Agent.start(fn -> nil end) {:ok, node_pid_2} = Agent.start(fn -> nil end) {:ok, node_pid_3} = Agent.start(fn -> nil end) :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_2, 20, "Node 2") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_1, 10, "Node 1") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_3, 30, "Node 3") assert {node_pid_1, 10, "Node 1"} = ActiveNodes.first(meta.active_nodes_pid) end test "returns nil if there are no active nodes", meta do assert ActiveNodes.first(meta.active_nodes_pid) == nil end end describe "register/3" do test "adds the given node to the registry", meta do {:ok, node_pid} = Agent.start(fn -> nil end) :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid, 10, "Node 1") assert [{node_pid, 10, "Node 1"}] = ActiveNodes.all(meta.active_nodes_pid) end test "sorts the nodes by their priorities", meta do {:ok, node_pid_1} = Agent.start(fn -> nil end) {:ok, node_pid_2} = Agent.start(fn -> nil end) {:ok, node_pid_3} = Agent.start(fn -> nil end) :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_2, 20, "Node 1") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_1, 10, "Node 2") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_3, 30, "Node 3") result = ActiveNodes.all(meta.active_nodes_pid) assert length(result) == 3 assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_1 end) assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_2 end) assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_3 end) end end describe "deregister/3" do test "removes the matching node from the registry", meta do {:ok, node_pid_1} = Agent.start(fn -> nil end) {:ok, node_pid_2} = Agent.start(fn -> nil end) {:ok, node_pid_3} = Agent.start(fn -> nil end) :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_1, 10, "Node 1") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_2, 20, "Node 2") :ok = ActiveNodes.register(meta.active_nodes_pid, node_pid_3, 30, "Node 3") assert ActiveNodes.deregister(meta.active_nodes_pid, node_pid_2) == :ok result = ActiveNodes.all(meta.active_nodes_pid) assert length(result) == 2 assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_1 end) refute Enum.any?(result, fn {pid, _, _} -> pid == node_pid_2 end) assert Enum.any?(result, fn {pid, _, _} -> pid == node_pid_3 end) end end end
38.368421
95
0.66941
79e221dfaf18894064de8b8b3053cbc8150068f4
932
exs
Elixir
year_2021/test/day_16_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2021/test/day_16_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
year_2021/test/day_16_test.exs
bschmeck/advent_of_code
cbec98019c6c00444e0f4c7e15e01b1ed9ae6145
[ "MIT" ]
null
null
null
defmodule Day16Test do use ExUnit.Case, async: true test "it can parse a literal value" do assert %{version: 6, type_id: 4, value: func} = Day16.parse("D2FE28") assert func.() == 2021 end test "it can sum versions of packets" do assert Day16.version_sum("8A004A801A8002F478") == 16 assert Day16.version_sum("620080001611562C8802118E34") == 12 assert Day16.version_sum("C0015000016115A2E0802F182340") == 23 assert Day16.version_sum("A0016C880162017C3686B18A3D4780") == 31 end test "it can compute" do assert Day16.compute("C200B40A82") == 3 assert Day16.compute("04005AC33890") == 54 assert Day16.compute("880086C3E88112") == 7 assert Day16.compute("CE00C43D881120") == 9 assert Day16.compute("D8005AC2A8F0") == 1 assert Day16.compute("F600BC2D8F") == 0 assert Day16.compute("9C005AC2F8F0") == 0 assert Day16.compute("9C0141080250320F1802104A08") == 1 end end
34.518519
73
0.701717
79e2318b5502292af5356d3aa6197740ab3b72d9
226
ex
Elixir
lib/post_utils.ex
crertel/bloglixir
6c8ee7775ee1f76f8bb9c9f8a9db74e6cf5eecc6
[ "MIT" ]
null
null
null
lib/post_utils.ex
crertel/bloglixir
6c8ee7775ee1f76f8bb9c9f8a9db74e6cf5eecc6
[ "MIT" ]
null
null
null
lib/post_utils.ex
crertel/bloglixir
6c8ee7775ee1f76f8bb9c9f8a9db74e6cf5eecc6
[ "MIT" ]
null
null
null
defmodule Bloglixir.PostUtils do def get_metadata_blob_from_post_string( post ) do [[ _, metadata, post_body]] = Regex.scan( ~r/\A\s*---(.*?)---(.*)\z/s, post) {:ok, [ metadata, post_body] } end end
25.111111
85
0.588496
79e238e995f5ec02c44498c3187efd47e14b913e
28,132
exs
Elixir
test/x509/test/server_test.exs
fhunleth/x509
24c5fcc42207cc74e1e00a322f4809caf058eb6b
[ "BSD-3-Clause" ]
null
null
null
test/x509/test/server_test.exs
fhunleth/x509
24c5fcc42207cc74e1e00a322f4809caf058eb6b
[ "BSD-3-Clause" ]
null
null
null
test/x509/test/server_test.exs
fhunleth/x509
24c5fcc42207cc74e1e00a322f4809caf058eb6b
[ "BSD-3-Clause" ]
null
null
null
defmodule X509.Test.ServerTest do # This test module serves two purposes: # # * To perform sanity tests on the `X509.Test.Suite` and # `X509.Test.Server` modules # * To serve as an example for using those modules to test a TLS client # # The client being tested by this module is Erlang/OTP's built-in HTTP # client, `httpc`. To adapt for other clients, update the `request/2` # function, as described in the comments. # # Add `log_alert: true` to the call to request/2 to get more information on # a failing scenario, e.g.: # # ``` # request('https://valid.#{context.suite.domain}:#{context.port}/', # cacertfile: context.cacertfile, # log_alert: true # ) # ``` # # Look for the keyword "ISSUE" to find comments throughout this file # documenting unexpected behaviour, interop issues or insecure defaults. use ExUnit.Case import X509.TestHelper require Logger # # Client under test # # This function invokes the TLS client under test. In this case we're using # Erlang/OTP's built-in HTTP client `httpc`, part of the `inets` application. # # To test another client, update this function as necessary. If the client is # not an HTTP client, remember to also update the test server response to # match the protocol the client is expecting. def request(uri, opts) do # ISSUE: `ssl` fails to perform CRL checks on certificates issued by # root CAs that were passed in via the `cacerts` option; to get the # connection to succeed, CRL checks have to be limited to the peer # certificate only crl_check = (Keyword.has_key?(opts, :cacerts) && :peer) || true # ISSUE: `httpc` requires explicit opt-in to peer certificate verification, # with HTTPS connections to misconfigured or malicious servers succeeding # without warning when using the default settings! ssl_defaults = [ log_alert: false, verify: :verify_peer, depth: 2, crl_check: crl_check, crl_cache: {:ssl_crl_cache, {:internal, [http: 30_000]}} ] ssl_opts = cond do version(:public_key) >= [1, 6] -> # ISSUE: `httpc` does not leverage OTP 21's built-in hostname # verification function for HTTPS, causing connections to servers # with wildcard patterns in their certificate's Subject Alternative # Name (SAN) extension to fail Keyword.put(ssl_defaults, :customize_hostname_check, match_fun: :public_key.pkix_verify_hostname_match_fun(:https) ) true -> ssl_defaults end |> Keyword.merge(opts) case :httpc.request(:get, {uri, []}, [ssl: ssl_opts], []) do {:ok, response} -> {:ok, response} {:error, {:failed_connect, info}} -> # Return the TLS alert {:error, info |> List.keyfind(:inet, 0) |> elem(2)} {:error, reason} -> {:error, reason} end end # # Test cases # describe "RSA, PEM" do setup [:rsa_suite, :create_pem_files] test "valid", context do assert {:ok, _} = request('https://valid.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-missing-chain", context do assert {:error, {:tls_alert, 'unknown ca'}} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-missing-chain with intermediate in cacerts", context do # On OTP 21, `ssl` will fill in gaps in the server's chain using # intermediate CAs from the provided trust store if version(:ssl) >= [9, 0, 2] do assert {:ok, _} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile_with_chain ) end end test "valid-expired-chain", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://valid-expired-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-revoked-chain", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://valid-revoked-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-wrong-key", context do assert {:error, {:tls_alert, 'decrypt error'}} = request('https://valid-wrong-key.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-wrong-host", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://valid-wrong-host.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end # ISSUE: this test case fails, because `public_key` does not explore # alternate paths to complete the chain; instead, it only looks for CAs # in its CA store that can complete the chain presented by the peer; # it is possible to work around this using a `partial_chain` function, # but this short-circuits other certificate verification features, such # as revocation checks and path length constraint checking @tag :known_to_fail test "valid-cross-signed, cross-signed CA", context do assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-cross-signed, cross-signing CA", context do # TODO: this only works with 'best effort' CRL checks; this may be an # issue with the test suite assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacertfile: context.alternate_cacertfile, crl_check: :best_effort ) end test "valid.wildcard", context do # OTP 21 supports wildcard certificates with the Subject Alternate Name # extension, if configured properly (see `request/2` comments); on older # versions this test would fail if version(:public_key) >= [1, 6] do assert {:ok, _} = request('https://valid.wildcard.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end end test "wildcard, bare domain", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://wildcard.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "invalid.subdomain.wildcard", context do assert {:error, {:tls_alert, 'handshake failure'}} = request( 'https://invalid.subdomain.wildcard.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "expired", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://expired.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "revoked", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://revoked.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "selfsigned", context do assert {:error, {:tls_alert, 'bad certificate'}} = request('https://selfsigned.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end end describe "RSA, DER" do setup [:rsa_suite] test "valid", context do assert {:ok, _} = request('https://valid.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-missing-chain", context do assert {:error, {:tls_alert, 'unknown ca'}} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-missing-chain with intermediate in cacerts", context do # On OTP 21, `ssl` will fill in gaps in the server's chain using # intermediate CAs from the provided trust store if version(:ssl) >= [9, 0, 2] do # ISSUE: `ssl` fails to perform CRL checks on certificates issued by # certificates that were passed in via the `cacerts` option; since the # issuer of the peer certificate in this case is taken from `cacerts`, # no CRL checks can be performed assert {:ok, _} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ++ context.suite.chain, crl_check: false ) end end test "valid-expired-chain", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://valid-expired-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end # ISSUE: this test case fails, because `ssl` does not handle CRL checks on # certificates issued by CAs passed in through `cacerts` @tag :known_to_fail test "valid-revoked-chain", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://valid-revoked-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-wrong-key", context do assert {:error, {:tls_alert, 'decrypt error'}} = request('https://valid-wrong-key.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-wrong-host", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://valid-wrong-host.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end # ISSUE: this test case fails, because `public_key` does not explore # alternate paths to complete the chain; instead, it only looks for CAs # in its CA store that can complete the chain presented by the peer; # it is possible to work around this using a `partial_chain` function, # but this short-circuits other certificate verification features, such # as revocation checks and path length constraint checking @tag :known_to_fail test "valid-cross-signed, cross-signed CA", context do assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-cross-signed, cross-signing CA", context do # TODO: this does not work with CRL checks at all, not even peer-only; # this may be an issue with the test suite assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.alternate_cacerts, crl_check: false ) end test "valid.wildcard", context do # OTP 21 supports wildcard certificates with the Subject Alternate Name # extension, if configured properly (see `request/2` comments); on older # versions this test would fail if version(:public_key) >= [1, 6] do assert {:ok, _} = request('https://valid.wildcard.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end end test "wildcard, bare domain", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://wildcard.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "invalid.subdomain.wildcard", context do assert {:error, {:tls_alert, 'handshake failure'}} = request( 'https://invalid.subdomain.wildcard.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "expired", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://expired.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "revoked", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://revoked.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "selfsigned", context do assert {:error, {:tls_alert, 'bad certificate'}} = request('https://selfsigned.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end end # ECDSA tests fail on older OTP releases, due to OTP-15203 if version(:ssl) >= [8, 2, 6, 2] and version(:ssl) != [9, 0, 0] do describe "ECDSA, PEM" do setup [:ecdsa_suite, :create_pem_files] test "valid", context do assert {:ok, _} = request('https://valid.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-missing-chain", context do assert {:error, {:tls_alert, 'unknown ca'}} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-missing-chain with intermediate in cacerts", context do # On OTP 21, `ssl` will fill in gaps in the server's chain using # intermediate CAs from the provided trust store if version(:ssl) >= [9, 0, 2] do assert {:ok, _} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile_with_chain ) end end test "valid-expired-chain", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://valid-expired-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-revoked-chain", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://valid-revoked-chain.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-wrong-key", context do assert {:error, {:tls_alert, 'decrypt error'}} = request('https://valid-wrong-key.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-wrong-host", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://valid-wrong-host.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end # ISSUE: this test case fails, because `public_key` does not explore # alternate paths to complete the chain; instead, it only looks for CAs # in its CA store that can complete the chain presented by the peer; # it is possible to work around this using a `partial_chain` function, # but this short-circuits other certificate verification features, such # as revocation checks and path length constraint checking @tag :known_to_fail test "valid-cross-signed, cross-signed CA", context do assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "valid-cross-signed, cross-signing CA", context do # TODO: this only works with 'best effort' CRL checks; this may be an # issue with the test suite assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacertfile: context.alternate_cacertfile, crl_check: :best_effort ) end test "valid.wildcard", context do # OTP 21 supports wildcard certificates with the Subject Alternate Name # extension, if configured properly (see `request/2` comments); on older # versions this test would fail if version(:public_key) >= [1, 6] do assert {:ok, _} = request('https://valid.wildcard.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end end test "wildcard, bare domain", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://wildcard.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "invalid.subdomain.wildcard", context do assert {:error, {:tls_alert, 'handshake failure'}} = request( 'https://invalid.subdomain.wildcard.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "expired", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://expired.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "revoked", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://revoked.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end test "selfsigned", context do assert {:error, {:tls_alert, 'bad certificate'}} = request('https://selfsigned.#{context.suite.domain}:#{context.port}/', cacertfile: context.cacertfile ) end end describe "ECDSA, DER" do setup [:ecdsa_suite] test "valid", context do assert {:ok, _} = request('https://valid.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-missing-chain", context do assert {:error, {:tls_alert, 'unknown ca'}} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-missing-chain with intermediate in cacerts", context do # On OTP 21, `ssl` will fill in gaps in the server's chain using # intermediate CAs from the provided trust store if version(:ssl) >= [9, 0, 2] do # ISSUE: `ssl` fails to perform CRL checks on certificates issued by # certificates that were passed in via the `cacerts` option; since the # issuer of the peer certificate in this case is taken from `cacerts`, # no CRL checks can be performed assert {:ok, _} = request('https://valid-missing-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ++ context.suite.chain, crl_check: false ) end end test "valid-expired-chain", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://valid-expired-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end # ISSUE: this test case fails, because `ssl` does not handle CRL checks on # certificates issued by CAs passed in through `cacerts` @tag :known_to_fail test "valid-revoked-chain", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://valid-revoked-chain.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-wrong-key", context do assert {:error, {:tls_alert, 'decrypt error'}} = request('https://valid-wrong-key.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-wrong-host", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://valid-wrong-host.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end # ISSUE: this test case fails, because `public_key` does not explore # alternate paths to complete the chain; instead, it only looks for CAs # in its CA store that can complete the chain presented by the peer; # it is possible to work around this using a `partial_chain` function, # but this short-circuits other certificate verification features, such # as revocation checks and path length constraint checking @tag :known_to_fail test "valid-cross-signed, cross-signed CA", context do assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "valid-cross-signed, cross-signing CA", context do # TODO: this does not work with CRL checks at all, not even peer-only; # this may be an issue with the test suite assert {:ok, _} = request('https://valid-cross-signed.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.alternate_cacerts, crl_check: false ) end test "valid.wildcard", context do # OTP 21 supports wildcard certificates with the Subject Alternate Name # extension, if configured properly (see `request/2` comments); on older # versions this test would fail if version(:public_key) >= [1, 6] do assert {:ok, _} = request('https://valid.wildcard.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end end test "wildcard, bare domain", context do assert {:error, {:tls_alert, 'handshake failure'}} = request('https://wildcard.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "invalid.subdomain.wildcard", context do assert {:error, {:tls_alert, 'handshake failure'}} = request( 'https://invalid.subdomain.wildcard.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "expired", context do assert {:error, {:tls_alert, 'certificate expired'}} = request('https://expired.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "revoked", context do assert {:error, {:tls_alert, 'certificate revoked'}} = request('https://revoked.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end test "selfsigned", context do assert {:error, {:tls_alert, 'bad certificate'}} = request('https://selfsigned.#{context.suite.domain}:#{context.port}/', cacerts: context.suite.cacerts ) end end else Logger.warn("ECDSA certificates can't be tested on the current OTP version") end # # Test setup callbacks and helper functions # # Canned response to be returned by the test server on established # connections @http_response ["HTTP/1.1 200 OK", "Content-Length: 2", "Connection: close", "", "OK"] |> Enum.join("\r\n") # Global test setup: start required applications and CRL responder setup_all do # Ensure inets and ssl applications are started; httpc is part of inets Application.ensure_all_started(:inets) Application.ensure_all_started(:ssl) # Start the CRL responder crl_server_pid = start(X509.Test.CRLServer) crl_server_port = X509.Test.CRLServer.get_port(crl_server_pid) crl_server_uri = "http://localhost:#{crl_server_port}" [crl_server: %{pid: crl_server_pid, uri: crl_server_uri}] end # Setup for RSA testing defp rsa_suite(context) do new_suite(context, {:rsa, 1024}, "rsa") end # Setup for ECSA testing defp ecdsa_suite(context) do new_suite(context, {:ec, :secp256r1}, "ecdsa") end # Generate a test suite, update the CRL responder and start a test server defp new_suite(context, key_type, prefix) do suite = X509.Test.Suite.new(key_type: key_type, crl_server: "#{context.crl_server.uri}/#{prefix}/") Enum.each(suite.crls, fn {path, crl} -> X509.Test.CRLServer.put_crl(context.crl_server.pid, "/#{prefix}/#{path}", crl) end) pid = start(X509.Test.Server, {suite, [response: @http_response]}) port = X509.Test.Server.get_port(pid) [suite: suite, port: port] end # Create PEM files for various CA stores used in test cases defp create_pem_files(context) do tmp_dir = System.tmp_dir!() |> Path.join("x509_server_test#{System.get_pid()}") File.mkdir(tmp_dir) cacerts = certificates_der_to_pem(context.suite.cacerts) cacerts_and_chain = certificates_der_to_pem(context.suite.cacerts ++ context.suite.chain) alternate_cacerts = certificates_der_to_pem(context.suite.alternate_cacerts) # Ensure unique path names for different contents, to avoid caching issues cacertfile = Path.join(tmp_dir, "cacerts_#{:erlang.phash2(cacerts)}.pem") File.write!(cacertfile, cacerts) cacertfile_with_chain = Path.join(tmp_dir, "cacerts_and_chain_#{:erlang.phash2(cacerts_and_chain)}.pem") File.write!(cacertfile_with_chain, cacerts_and_chain) alternate_cacertfile = Path.join(tmp_dir, "alternate_cacerts_#{:erlang.phash2(cacerts)}.pem") File.write!(alternate_cacertfile, alternate_cacerts) on_exit(fn -> File.rm(cacertfile) File.rm(cacertfile_with_chain) File.rm(alternate_cacertfile) File.rmdir(tmp_dir) end) [ cacertfile: cacertfile, cacertfile_with_chain: cacertfile_with_chain, alternate_cacertfile: alternate_cacertfile ] end # Convert a list of DER certificates to a single PEM string defp certificates_der_to_pem(list) do list |> Enum.map(&X509.Certificate.from_der!/1) |> Enum.map(&X509.Certificate.to_pem/1) |> Enum.join() end # Starts the GenServer in the specified module, using ExUnit's # `start_supervised` if available defp start(module, args \\ []) do {:ok, pid} = if version(:ex_unit) >= [1, 6] do # Assign a unique ID, to allow multiple servers to be running under # the ExUnit supervisor at the same time ExUnit.Callbacks.start_supervised({module, args}, id: make_ref()) else module.start_link(args) end pid end end
38.222826
98
0.594661
79e250727dd7a18a9b2c42d17c2b71a86aee0311
607
exs
Elixir
apps/tai/test/tai/events/sub_free_asset_balance_test.exs
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
1
2019-12-19T05:16:26.000Z
2019-12-19T05:16:26.000Z
apps/tai/test/tai/events/sub_free_asset_balance_test.exs
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
null
null
null
apps/tai/test/tai/events/sub_free_asset_balance_test.exs
ihorkatkov/tai
09f9f15d2c385efe762ae138a8570f1e3fd41f26
[ "MIT" ]
null
null
null
defmodule Tai.Events.SubFreeAssetBalanceTest do use ExUnit.Case, async: true test ".to_data/1 transforms decimal data to strings" do event = %Tai.Events.SubFreeAssetBalance{ venue_id: :my_venue, account_id: :my_account, asset: :btc, val: Decimal.new("0.1"), free: Decimal.new("0.2"), locked: Decimal.new("0.3") } assert Tai.LogEvent.to_data(event) == %{ venue_id: :my_venue, account_id: :my_account, asset: :btc, val: "0.1", free: "0.2", locked: "0.3" } end end
25.291667
57
0.5486
79e251fd281b12cdb0599b4edd61a8aa5187a31e
8,342
exs
Elixir
test/capture_test.exs
bitcrowd/carbonite
663af92caa2afa8838cb43800da8e320f323276a
[ "Apache-2.0" ]
26
2021-10-30T06:32:20.000Z
2022-03-28T14:34:24.000Z
test/capture_test.exs
bitcrowd/carbonite
663af92caa2afa8838cb43800da8e320f323276a
[ "Apache-2.0" ]
8
2021-10-20T08:03:34.000Z
2022-02-25T08:48:14.000Z
test/capture_test.exs
bitcrowd/carbonite
663af92caa2afa8838cb43800da8e320f323276a
[ "Apache-2.0" ]
null
null
null
# SPDX-License-Identifier: Apache-2.0 defmodule CaptureTest do use ExUnit.Case, async: true import Ecto.Adapters.SQL, only: [query!: 2] alias Carbonite.TestRepo alias Ecto.Adapters.SQL.Sandbox setup do :ok = Sandbox.checkout(TestRepo) end defp query!(statement), do: query!(TestRepo, statement) defp insert_transaction do query!("INSERT INTO carbonite_default.transactions (inserted_at) VALUES (NOW());") end defp insert_jack do query!("INSERT INTO rabbits (name, age) VALUES ('Jack', 99);") end defp upsert_jack(new_name, do_clause) do query!(""" INSERT INTO rabbits (id, name) VALUES (#{last_rabbit_id()}, '#{new_name}') ON CONFLICT (id) DO #{do_clause} """) end defp select_changes do "SELECT * FROM carbonite_default.changes;" |> query!() |> postgrex_result_to_structs() end defp select_rabbits do "SELECT * FROM public.rabbits ORDER BY id DESC;" |> query!() |> postgrex_result_to_structs() end defp last_rabbit_id do select_rabbits() |> List.last() |> Map.fetch!("id") |> to_string() end defp postgrex_result_to_structs(%Postgrex.Result{columns: columns, rows: rows}) do Enum.map(rows, fn row -> columns |> Enum.zip(row) |> Map.new() end) end describe "change capture trigger" do test "INSERTs on tables are tracked as changes" do TestRepo.transaction(fn -> insert_transaction() insert_jack() end) assert [ %{ "id" => _, "transaction_id" => _, "table_prefix" => "public", "table_name" => "rabbits", "op" => "insert", "changed" => [], "data" => %{"id" => _, "name" => "Jack"} } ] = select_changes() end test "UPDATEs on tables are tracked as changes" do TestRepo.transaction(fn -> insert_transaction() insert_jack() query!("UPDATE rabbits SET name = 'Jane' WHERE name = 'Jack';") end) assert [ %{ "op" => "insert", "changed" => [], "data" => %{"id" => _, "name" => "Jack"} }, %{ "op" => "update", "changed" => ["name"], "data" => %{"id" => _, "name" => "Jane"} } ] = select_changes() end test "UPDATEs on tables are not tracked when data remains the same" do TestRepo.transaction(fn -> insert_transaction() insert_jack() query!("UPDATE rabbits SET name = 'Jack';") end) assert [%{"op" => "insert"}] = select_changes() end test "INSERT ON CONFLICT NOTHING is not tracked" do TestRepo.transaction(fn -> insert_transaction() insert_jack() upsert_jack("Jack", "NOTHING") end) assert [%{"op" => "insert"}] = select_changes() end test "INSERT ON CONFLICT SET ... is not tracked when data remains the same" do TestRepo.transaction(fn -> insert_transaction() insert_jack() upsert_jack("Jack", "UPDATE SET name = excluded.name;") end) assert [%{"op" => "insert"}] = select_changes() end test "INSERT ON CONFLICT SET ... is tracked when data is changed" do TestRepo.transaction(fn -> insert_transaction() insert_jack() upsert_jack("Jane", "UPDATE SET name = excluded.name;") end) assert [ %{"op" => "insert"}, %{ "op" => "update", "changed" => ["name"], "data" => %{"id" => _, "name" => "Jane"} } ] = select_changes() end test "DELETEs on tables are tracked as changes" do TestRepo.transaction(fn -> insert_transaction() insert_jack() query!("DELETE FROM rabbits WHERE name = 'Jack';") end) assert [ %{ "op" => "insert", "changed" => [], "data" => %{"id" => _, "name" => "Jack"} }, %{ "op" => "delete", "changed" => [], "data" => %{"id" => _, "name" => "Jack"} } ] = select_changes() end test "table primary key is written for INSERTs" do TestRepo.transaction(fn -> insert_transaction() insert_jack() end) rabbit_id = last_rabbit_id() assert [%{"table_pk" => [^rabbit_id]}] = select_changes() end test "table primary key is written for UPDATEs" do TestRepo.transaction(fn -> insert_transaction() insert_jack() query!("UPDATE rabbits SET name = 'Jane' WHERE name = 'Jack';") end) rabbit_id = last_rabbit_id() assert [ %{"table_pk" => [^rabbit_id]}, %{"table_pk" => [^rabbit_id]} ] = select_changes() end test "table primary key is written for DELETEs" do {:ok, rabbit_id} = TestRepo.transaction(fn -> insert_transaction() insert_jack() rabbit_id = last_rabbit_id() query!("DELETE FROM rabbits WHERE name = 'Jack';") rabbit_id end) assert [ %{"table_pk" => [^rabbit_id]}, %{"table_pk" => [^rabbit_id]} ] = select_changes() end test "table_pk is NULL when primary_key_columns is empty" do query!("UPDATE carbonite_default.triggers SET primary_key_columns = '{}';") TestRepo.transaction(fn -> insert_transaction() insert_jack() end) assert [%{"table_pk" => nil}] = select_changes() end test "a friendly error is raised when transaction is not inserted or is inserted too late" do msg = "ERROR 23503 (foreign_key_violation) INSERT on table public.rabbits " <> "without prior INSERT into carbonite_default.transactions" assert_raise Postgrex.Error, msg, fn -> TestRepo.transaction(&insert_jack/0) end end test "a (not quite as) friendly error is raised when transaction is inserted twice" do TestRepo.transaction(fn -> insert_transaction() assert_raise Postgrex.Error, ~r/duplicate key value violates unique constraint "transactions_pkey"/, fn -> insert_transaction() end end) end end describe "default mode / override mode" do test "override mode reverses the default mode" do TestRepo.transaction(fn -> query!(""" UPDATE carbonite_default.triggers SET override_transaction_id = pg_current_xact_id(); """) insert_jack() end) assert select_changes() == [] end test "default mode can be set to ignore" do # This test exists because we had a bug with the ignore mode # when the override_transaction_id was NULL TestRepo.transaction(fn -> query!(""" UPDATE carbonite_default.triggers SET mode = 'ignore'; """) insert_jack() end) assert select_changes() == [] end end describe "excluded columns" do test "excluded columns do not appear in captured data" do TestRepo.transaction(fn -> insert_transaction() insert_jack() end) assert [%{"data" => data}] = select_changes() refute Map.has_key?(data, "age") end test "UPDATEs on only excluded fields are not tracked" do TestRepo.transaction(fn -> insert_transaction() insert_jack() query!("UPDATE rabbits SET age = 100 WHERE name = 'Jack';") end) assert [%{"age" => 100}] = select_rabbits() assert [%{"op" => "insert"}] = select_changes() end end describe "filtered columns" do test "appear as [FILTERED] in the data" do TestRepo.transaction(fn -> query!(""" UPDATE carbonite_default.triggers SET filtered_columns = '{name}'; """) insert_transaction() insert_jack() end) assert [%{"data" => %{"name" => "[FILTERED]"}}] = select_changes() end end end
27.084416
97
0.541956
79e25dceb5065b82520af05381e7a06cd14c1f4e
153
exs
Elixir
lab-one-introduction-to-elixir/ex3-n-clients-single-server/test/clientserver_test.exs
HilliamT/distributed-algorithms
788e8e0b9a6c60570ecf8336f2239fb1d1945b1c
[ "MIT" ]
null
null
null
lab-one-introduction-to-elixir/ex3-n-clients-single-server/test/clientserver_test.exs
HilliamT/distributed-algorithms
788e8e0b9a6c60570ecf8336f2239fb1d1945b1c
[ "MIT" ]
null
null
null
lab-one-introduction-to-elixir/ex3-n-clients-single-server/test/clientserver_test.exs
HilliamT/distributed-algorithms
788e8e0b9a6c60570ecf8336f2239fb1d1945b1c
[ "MIT" ]
null
null
null
defmodule ClentServerrTest do use ExUnit.Case doctest ClientServer test "greets the world" do assert ClientServer.hello() == :world end end
17
41
0.738562
79e26f77101d9f3f32a45d5771a69fce5f6d42a3
319
ex
Elixir
lib/livebooks/application.ex
christhekeele/livebooks
b7e272b53679cfd573221bffe1e4721703fe35c4
[ "MIT" ]
null
null
null
lib/livebooks/application.ex
christhekeele/livebooks
b7e272b53679cfd573221bffe1e4721703fe35c4
[ "MIT" ]
null
null
null
lib/livebooks/application.ex
christhekeele/livebooks
b7e272b53679cfd573221bffe1e4721703fe35c4
[ "MIT" ]
null
null
null
defmodule Livebooks.Application do @moduledoc false use Application @impl true def start(_type, _args) do [ {Plug.Cowboy, scheme: :http, plug: Livebooks.Router, options: [port: 4001]} ] |> Supervisor.start_link( strategy: :one_for_one, name: Livebooks.Supervisor ) end end
18.764706
81
0.655172
79e2b344ca3c0214974669b193e116c0d95593a9
4,466
ex
Elixir
lib/pbcs/aes_cbc_hmac_sha2.ex
hexpm/pbcs
5446d4602f4638046f2dcafd7ae0359866e0da42
[ "Apache-2.0" ]
16
2018-09-03T21:59:29.000Z
2021-11-27T08:15:17.000Z
lib/pbcs/aes_cbc_hmac_sha2.ex
hexpm/pbcs
5446d4602f4638046f2dcafd7ae0359866e0da42
[ "Apache-2.0" ]
8
2018-08-28T17:46:23.000Z
2021-06-02T00:19:43.000Z
lib/pbcs/aes_cbc_hmac_sha2.ex
hexpm/hex_crypto
5446d4602f4638046f2dcafd7ae0359866e0da42
[ "Apache-2.0" ]
3
2018-09-12T12:32:16.000Z
2021-05-10T13:39:08.000Z
defmodule PBCS.AES_CBC_HMAC_SHA2 do alias PBCS.ContentEncryptor alias PBCS.CryptoWrapper @behaviour ContentEncryptor @moduledoc ~S""" Content Encryption with AES_CBC_HMAC_SHA2. See: https://tools.ietf.org/html/rfc7518#section-5.2.6 """ @spec content_encrypt({binary, PBCS.plain_text()}, binary(), binary()) :: {PBCS.cipher_text(), binary()} def content_encrypt({aad, plain_text}, key, iv) when is_binary(aad) and is_binary(plain_text) and bit_size(key) in [256, 384, 512] and bit_size(iv) === 128 do mac_size = div(byte_size(key), 2) enc_size = mac_size tag_size = mac_size <<mac_key::binary-size(mac_size), enc_key::binary-size(enc_size)>> = key cipher_text = aes_cbc_encrypt(enc_key, iv, pkcs7_pad(plain_text)) aad_length = <<bit_size(aad)::1-unsigned-big-integer-unit(64)>> mac_data = aad <> iv <> cipher_text <> aad_length <<cipher_tag::binary-size(tag_size), _::binary>> = hmac_sha2(mac_key, mac_data) {cipher_text, cipher_tag} end @spec content_decrypt({binary(), PBCS.cipher_text(), PBCS.tag()}, binary(), binary()) :: {:ok, PBCS.plain_text()} | :error def content_decrypt({aad, cipher_text, cipher_tag}, key, iv) when is_binary(aad) and is_binary(cipher_text) and bit_size(cipher_tag) in [128, 192, 256] and bit_size(key) in [256, 384, 512] and bit_size(iv) === 128 do mac_size = div(byte_size(key), 2) enc_size = mac_size tag_size = mac_size <<mac_key::binary-size(mac_size), enc_key::binary-size(enc_size)>> = key aad_length = <<bit_size(aad)::1-unsigned-big-integer-unit(64)>> mac_data = aad <> iv <> cipher_text <> aad_length case hmac_sha2(mac_key, mac_data) do <<^cipher_tag::binary-size(tag_size), _::binary>> -> case aes_cbc_decrypt(enc_key, iv, cipher_text) do plain_text when is_binary(plain_text) -> pkcs7_unpad(plain_text) _ -> :error end _ -> :error end end def init(%{enc: enc}, _opts) do {:ok, %{key_length: encoding_to_key_length(enc)}} end def encrypt(%{key_length: key_length}, key, iv, {aad, plain_text}) when byte_size(key) == key_length do content_encrypt({aad, plain_text}, key, iv) end def decrypt(%{key_length: key_length}, key, iv, {aad, cipher_text, cipher_tag}) when byte_size(key) == key_length do content_decrypt({aad, cipher_text, cipher_tag}, key, iv) end def generate_key(%{key_length: key_length}) do :crypto.strong_rand_bytes(key_length) end def generate_iv(_params) do :crypto.strong_rand_bytes(16) end def key_length(%{key_length: key_length}) do key_length end # Support new and old style AES-CBC calls. defp aes_cbc_encrypt(key, iv, plain_text) do CryptoWrapper.block_encrypt(:aes_cbc, key, iv, plain_text) end defp aes_cbc_decrypt(key, iv, cipher_text) do CryptoWrapper.block_decrypt(:aes_cbc, key, iv, cipher_text) end defp hmac_sha2(mac_key, mac_data) when bit_size(mac_key) === 128 do CryptoWrapper.hmac(:sha256, mac_key, mac_data) end defp hmac_sha2(mac_key, mac_data) when bit_size(mac_key) === 192 do CryptoWrapper.hmac(:sha384, mac_key, mac_data) end defp hmac_sha2(mac_key, mac_data) when bit_size(mac_key) === 256 do CryptoWrapper.hmac(:sha512, mac_key, mac_data) end # Pads a message using the PKCS #7 cryptographic message syntax. # # See: https://tools.ietf.org/html/rfc2315 # See: `pkcs7_unpad/1` defp pkcs7_pad(message) do bytes_remaining = rem(byte_size(message), 16) padding_size = 16 - bytes_remaining message <> :binary.copy(<<padding_size>>, padding_size) end # Unpads a message using the PKCS #7 cryptographic message syntax. # # See: https://tools.ietf.org/html/rfc2315 # See: `pkcs7_pad/1` defp pkcs7_unpad(<<>>) do :error end defp pkcs7_unpad(message) do padding_size = :binary.last(message) if padding_size <= 16 do message_size = byte_size(message) if binary_part(message, message_size, -padding_size) === :binary.copy(<<padding_size>>, padding_size) do {:ok, binary_part(message, 0, message_size - padding_size)} else :error end else :error end end defp encoding_to_key_length("A128CBC-HS256"), do: 32 defp encoding_to_key_length("A192CBC-HS384"), do: 48 defp encoding_to_key_length("A256CBC-HS512"), do: 64 end
31.673759
100
0.674877
79e2bc81657f36644f58598ed87a3f5ad14eb099
6,992
ex
Elixir
lib/ring_logger/client.ex
mattludwigs/ring_logger
7392f9ff998079765b9ba1716825a3f6b2cfacac
[ "Apache-2.0" ]
null
null
null
lib/ring_logger/client.ex
mattludwigs/ring_logger
7392f9ff998079765b9ba1716825a3f6b2cfacac
[ "Apache-2.0" ]
null
null
null
lib/ring_logger/client.ex
mattludwigs/ring_logger
7392f9ff998079765b9ba1716825a3f6b2cfacac
[ "Apache-2.0" ]
null
null
null
defmodule RingLogger.Client do use GenServer @moduledoc """ Interact with the RingLogger """ alias RingLogger.Server defmodule State do @moduledoc false defstruct io: nil, colors: nil, metadata: nil, format: nil, level: nil, index: 0, module_levels: %{} end @doc """ Start up a client GenServer. Except for just getting the contents of the ring buffer, you'll need to create one of these. See `configure/2` for information on options. """ def start_link(config \\ []) do GenServer.start_link(__MODULE__, config) end @doc """ Stop a client. """ def stop(client_pid) do GenServer.stop(client_pid) end @doc """ Update the client configuration. Options include: * `:io` - Defaults to `:stdio` * `:colors` - * `:metadata` - A KV list of additional metadata * `:format` - A custom format string, or a {module, function} tuple (see https://hexdocs.pm/logger/master/Logger.html#module-custom-formatting) * `:level` - The minimum log level to report. """ @spec configure(GenServer.server(), [RingLogger.client_option()]) :: :ok def configure(client_pid, config) do GenServer.call(client_pid, {:config, config}) end @doc """ Attach the current IEx session to the logger. It will start printing log messages. """ @spec attach(GenServer.server()) :: :ok def attach(client_pid) do GenServer.call(client_pid, :attach) end @doc """ Detach the current IEx session from the logger. """ @spec detach(GenServer.server()) :: :ok def detach(client_pid) do GenServer.call(client_pid, :detach) end @doc """ Tail the messages in the log. """ @spec tail(GenServer.server()) :: :ok def tail(client_pid) do GenServer.call(client_pid, :tail) end @doc """ Reset the index into the log for `tail/1` to the oldest entry. """ @spec reset(GenServer.server()) :: :ok def reset(client_pid) do GenServer.call(client_pid, :reset) end @doc """ Helper method for formatting log messages per the current client's configuration. """ @spec format(GenServer.server(), RingLogger.entry()) :: :ok def format(client_pid, message) do GenServer.call(client_pid, {:format, message}) end @doc """ Run a regular expression on each entry in the log and print out the matchers. """ @spec grep(GenServer.server(), Regex.t()) :: :ok def grep(client_pid, regex) do GenServer.call(client_pid, {:grep, regex}) end def init(config) do state = %State{ io: Keyword.get(config, :io, :stdio), colors: configure_colors(config), metadata: Keyword.get(config, :metadata, []) |> configure_metadata(), format: Keyword.get(config, :format) |> configure_formatter(), level: Keyword.get(config, :level, :debug), module_levels: Keyword.get(config, :module_levels, %{}) } {:ok, state} end def handle_info({:log, msg}, state) do maybe_print(msg, state) {:noreply, state} end def handle_call({:config, config}, _from, state) do new_io = Keyword.get(config, :io, state.io) new_level = Keyword.get(config, :level, state.level) new_state = %State{state | io: new_io, level: new_level} {:reply, :ok, new_state} end def handle_call(:attach, _from, state) do {:reply, Server.attach_client(self()), state} end def handle_call(:detach, _from, state) do {:reply, Server.detach_client(self()), state} end def handle_call(:tail, _from, state) do messages = Server.get(state.index) case List.last(messages) do nil -> # No messages {:reply, :ok, state} last_message -> Enum.each(messages, fn msg -> maybe_print(msg, state) end) next_index = message_index(last_message) + 1 {:reply, :ok, %{state | index: next_index}} end end def handle_call(:reset, _from, state) do {:reply, :ok, %{state | index: 0}} end def handle_call({:grep, regex}, _from, state) do Server.get() |> Enum.each(fn msg -> maybe_print(msg, regex, state) end) {:reply, :ok, state} end def handle_call({:format, msg}, _from, state) do item = format_message(msg, state) {:reply, item, state} end defp message_index({_level, {_, _msg, _ts, md}}), do: Keyword.get(md, :index) defp format_message({level, {_, msg, ts, md}}, state) do metadata = take_metadata(md, state.metadata) state.format |> apply_format(level, msg, ts, metadata) |> color_event(level, state.colors, md) end ## Helpers defp apply_format({mod, fun}, level, msg, ts, metadata) do apply(mod, fun, [level, msg, ts, metadata]) end defp apply_format(format, level, msg, ts, metadata) do Logger.Formatter.format(format, level, msg, ts, metadata) end defp configure_metadata(:all), do: :all defp configure_metadata(metadata), do: Enum.reverse(metadata) defp configure_colors(config) do colors = Keyword.get(config, :colors, []) %{ debug: Keyword.get(colors, :debug, :cyan), info: Keyword.get(colors, :info, :normal), warn: Keyword.get(colors, :warn, :yellow), error: Keyword.get(colors, :error, :red), enabled: Keyword.get(colors, :enabled, IO.ANSI.enabled?()) } end defp meet_level?(_lvl, nil), do: true defp meet_level?(lvl, min) do Logger.compare_levels(lvl, min) != :lt end defp take_metadata(metadata, :all), do: metadata defp take_metadata(metadata, keys) do Enum.reduce(keys, [], fn key, acc -> case Keyword.fetch(metadata, key) do {:ok, val} -> [{key, val} | acc] :error -> acc end end) end defp color_event(data, _level, %{enabled: false}, _md), do: data defp color_event(data, level, %{enabled: true} = colors, md) do color = md[:ansi_color] || Map.fetch!(colors, level) [IO.ANSI.format_fragment(color, true), data | IO.ANSI.reset()] end defp configure_formatter({mod, fun}), do: {mod, fun} defp configure_formatter(format) do Logger.Formatter.compile(format) end defp maybe_print(msg, state) do if should_print?(msg, state) do item = format_message(msg, state) IO.binwrite(state.io, item) end end defp maybe_print({_, {_, text, _, _}} = msg, r, state) do flattened_text = IO.iodata_to_binary(text) if should_print?(msg, state) && Regex.match?(r, flattened_text) do item = format_message(msg, state) IO.binwrite(state.io, item) end end defp get_module_from_msg({_, {_, _, _, meta}}) do Keyword.get(meta, :module) end defp should_print?({level, _} = msg, %State{module_levels: module_levels} = state) do module = get_module_from_msg(msg) with module_level when not is_nil(module_level) <- Map.get(module_levels, module), true <- meet_level?(level, module_level) do true else nil -> meet_level?(level, state.level) _ -> false end end end
26.187266
94
0.640303
79e2f44f408d2ba9b5690ed44e0ba58999b698e8
641
exs
Elixir
config/releases.exs
daddyfatstacksBIG/ex_testchain
06a870668b70c75009880ef574eb4bbee1cf47e4
[ "Apache-2.0" ]
5
2018-11-22T18:54:08.000Z
2021-05-07T18:47:20.000Z
config/releases.exs
daddyfatstacksBIG/ex_testchain
06a870668b70c75009880ef574eb4bbee1cf47e4
[ "Apache-2.0" ]
29
2018-12-04T16:55:01.000Z
2019-01-29T14:33:26.000Z
config/releases.exs
daddyfatstacksBIG/ex_testchain
06a870668b70c75009880ef574eb4bbee1cf47e4
[ "Apache-2.0" ]
3
2019-01-11T04:40:19.000Z
2022-03-23T17:31:37.000Z
import Config config :chain, base_path: "/opt/chains" config :chain, snapshot_base_path: "/opt/snapshots" config :chain, geth_executable: "geth" config :chain, geth_password_file: "/opt/built/priv/presets/geth/account_password" config :chain, ganache_executable: "ganache-cli" config :chain, ganache_wrapper_file: "/opt/built/priv/presets/ganache/wrapper.sh" config :chain, geth_vdb_executable: "geth_vdb" config :chain, backend_proxy_node: :"[email protected]" config :chain, front_url: System.fetch_env!("FRONT_URL") # Place where all dets DBs will be config :storage, dets_db_path: "/opt/chains"
37.705882
93
0.792512
79e30e1094dc255d1d427262a3f1cba76801c57f
618
exs
Elixir
apps/core/priv/repo/migrations/20210515021126_soft_recipe_dependency_fk.exs
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
59
2021-09-16T19:29:39.000Z
2022-03-31T20:44:24.000Z
apps/core/priv/repo/migrations/20210515021126_soft_recipe_dependency_fk.exs
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
111
2021-08-15T09:56:37.000Z
2022-03-31T23:59:32.000Z
apps/core/priv/repo/migrations/20210515021126_soft_recipe_dependency_fk.exs
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
4
2021-12-13T09:43:01.000Z
2022-03-29T18:08:44.000Z
defmodule Core.Repo.Migrations.SoftRecipeDependencyFk do use Ecto.Migration def up do execute "ALTER TABLE recipe_dependencies DROP CONSTRAINT recipe_dependencies_dependent_recipe_id_fkey" alter table(:recipe_dependencies) do modify :dependent_recipe_id, references(:recipes, type: :uuid, on_delete: :nothing) end end def down do execute "ALTER TABLE recipe_dependencies DROP CONSTRAINT recipe_dependencies_dependent_recipe_id_fkey" alter table(:recipe_dependencies) do modify :dependent_recipe_id, references(:recipes, type: :uuid, on_delete: :delete_all) end end end
32.526316
106
0.781553
79e3101204938d0dcf2e2bd16985fb955c093ac7
2,208
ex
Elixir
lib/bluetooth/hci/command.ex
sadesyllas/nerves_bluetooth
d316dbc192be8beec8b76dd245225117bc7d925f
[ "Apache-2.0" ]
14
2018-01-29T23:34:50.000Z
2021-07-15T04:29:36.000Z
lib/bluetooth/hci/command.ex
sadesyllas/nerves_bluetooth
d316dbc192be8beec8b76dd245225117bc7d925f
[ "Apache-2.0" ]
2
2017-05-24T18:16:42.000Z
2018-11-06T19:29:09.000Z
lib/bluetooth/hci/command.ex
sadesyllas/nerves_bluetooth
d316dbc192be8beec8b76dd245225117bc7d925f
[ "Apache-2.0" ]
3
2018-06-01T07:10:19.000Z
2019-01-06T22:32:56.000Z
defmodule Bluetooth.HCI.Commands do @moduledoc """ This module holds conversion functions for HCI commands and their results from and to a logical format and the binary representation. This module does not to attempt to be complete but grows by need. """ alias Bluetooth.HCI alias Bluetooth.AssignedNumbers def read_local_name() do HCI.create_command(0x03, 0x0014, <<>>) end def receive_local_name(<<0 :: size(8), long_name :: binary>>) do # the local name is 0-terminated or a full 248 bytes long UTF8 string [name, _] = String.split(long_name, <<0>>, parts: 2) {:ok, name} end def receive_local_name(<<code :: integer-size(8), _>>), do: {:error, code} def write_local_name(name) when is_binary(name) and :erlang.byte_size(name) == 248 do HCI.create_command(0x03, 0x0015, name) end def write_local_name(name) when is_binary(name) and :erlang.byte_size(name) < 248 do HCI.create_command(0x03, 0x0015, name <> <<0>>) end def read_local_version_info() do HCI.create_command(0x04, 0x01, <<>>) end def receive_local_version_info(params) do <<code :: integer-size(8), hci_version :: integer-size(8), hci_revision :: integer-little-size(16), pal_version :: integer-size(8), manufacturer :: integer-little-size(16), pal_subversion :: integer-little-size(16) >> = params if (code != 0) do {:error, code} else {:ok, %{hci_version_code: hci_version, hci_version: AssignedNumbers.version(hci_version), hci_revision: hci_revision, pal_version_code: pal_version, pal_version: AssignedNumbers.version(pal_version), manufacturer_uuid: manufacturer, manufacturer: AssignedNumbers.company_name(manufacturer), pal_subversion: pal_subversion }} end end @doc """ Reads the BD address or the LE public address from the controller """ def read_bd_address() do HCI.create_command(0x04, 0x0009, <<>>) end def reveive_bd_address(<<0x00, addr :: binary-size(6)>>), do: {:ok, addr} def reveive_bd_address(<<code :: unsigned-integer-size(8), _rest::binary>>), do: {:error, code} end
31.098592
97
0.668478
79e34012d17b65887ede70ab0319d3727e3e7f5e
2,203
ex
Elixir
lib/ex_clubhouse/model/epic_slim.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
4
2020-03-17T00:42:10.000Z
2021-04-11T16:39:52.000Z
lib/ex_clubhouse/model/epic_slim.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
7
2020-03-21T20:22:13.000Z
2021-12-30T16:32:07.000Z
lib/ex_clubhouse/model/epic_slim.ex
pootsbook/exclubhouse
3b93cded0124e4e5df489db4f9262a560595bb8e
[ "MIT" ]
4
2020-03-25T18:34:49.000Z
2021-09-13T16:44:00.000Z
defmodule ExClubhouse.Model.EpicSlim do @moduledoc """ Definition of EpicSlim Ref: https://clubhouse.io/api/rest/v3/#EpicSlim """ alias ExClubhouse.Model @type t :: %__MODULE__{ app_url: binary(), archived: boolean(), completed: boolean(), completed_at: binary() | nil, completed_at_override: binary() | nil, created_at: binary() | nil, deadline: binary() | nil, entity_type: binary(), epic_state_id: integer(), external_id: binary() | nil, external_tickets: list(), follower_ids: list(binary()), group_mention_ids: list(binary()), id: integer(), labels: list(Model.Label.t()), member_mention_ids: list(binary()), mention_ids: list(binary()), milestone_id: integer() | nil, name: binary(), owner_ids: list(binary()), planned_start_date: binary() | nil, position: integer(), project_ids: list(integer()), requested_by_id: binary(), started: boolean(), started_at: binary() | nil, started_at_override: binary() | nil, state: binary(), stats: Model.EpicStats.t(), updated_at: binary() | nil } defstruct app_url: nil, archived: nil, completed: nil, completed_at: nil, completed_at_override: nil, created_at: nil, deadline: nil, entity_type: nil, epic_state_id: nil, external_id: nil, external_tickets: [], follower_ids: [], group_mention_ids: [], id: nil, labels: [], member_mention_ids: [], mention_ids: [], milestone_id: nil, name: nil, owner_ids: [], planned_start_date: nil, position: nil, project_ids: [], requested_by_id: nil, started: nil, started_at: nil, started_at_override: nil, state: nil, stats: nil, updated_at: nil end
30.178082
49
0.509305
79e341207312e71190c71db3a6c86be2c162fc23
9,913
ex
Elixir
lib/mix/tasks/phx.gen.live.slime.ex
AnomalousBit/phoenix_slime
da0630066c37cc471185cfe227244d0760a54fa3
[ "MIT" ]
null
null
null
lib/mix/tasks/phx.gen.live.slime.ex
AnomalousBit/phoenix_slime
da0630066c37cc471185cfe227244d0760a54fa3
[ "MIT" ]
null
null
null
lib/mix/tasks/phx.gen.live.slime.ex
AnomalousBit/phoenix_slime
da0630066c37cc471185cfe227244d0760a54fa3
[ "MIT" ]
null
null
null
defmodule Mix.Tasks.Phx.Gen.Live.Slime do @shortdoc "Generates LiveView, templates, and context for a resource" @moduledoc """ Generates LiveView, templates, and context for a resource. mix phx.gen.live Accounts User users name:string age:integer The first argument is the context module followed by the schema module and its plural name (used as the schema table name). The context is an Elixir module that serves as an API boundary for the given resource. A context often holds many related resources. Therefore, if the context already exists, it will be augmented with functions for the given resource. When this command is run for the first time, a `ModalComponent` and `LiveHelpers` module will be created, along with the resource level LiveViews and components, including an `IndexLive`, `ShowLive`, `FormComponent` for the new resource. > Note: A resource may also be split > over distinct contexts (such as `Accounts.User` and `Payments.User`). The schema is responsible for mapping the database fields into an Elixir struct. It is followed by an optional list of attributes, with their respective names and types. See `mix phx.gen.schema` for more information on attributes. Overall, this generator will add the following files to `lib/`: * a context module in `lib/app/accounts.ex` for the accounts API * a schema in `lib/app/accounts/user.ex`, with an `users` table * a view in `lib/app_web/views/user_view.ex` * a LiveView in `lib/app_web/live/user_live/show_live.ex` * a LiveView in `lib/app_web/live/user_live/index_live.ex` * a LiveComponent in `lib/app_web/live/user_live/form_component.ex` * a LiveComponent in `lib/app_web/live/modal_component.ex` * a helpers modules in `lib/app_web/live/live_helpers.ex` ## The context app A migration file for the repository and test files for the context and controller features will also be generated. The location of the web files (LiveView's, views, templates, etc) in an umbrella application will vary based on the `:context_app` config located in your applications `:generators` configuration. When set, the Phoenix generators will generate web files directly in your lib and test folders since the application is assumed to be isolated to web specific functionality. If `:context_app` is not set, the generators will place web related lib and test files in a `web/` directory since the application is assumed to be handling both web and domain specific functionality. Example configuration: config :my_app_web, :generators, context_app: :my_app Alternatively, the `--context-app` option may be supplied to the generator: mix phx.gen.live Sales User users --context-app warehouse ## Web namespace By default, the controller and view will be namespaced by the schema name. You can customize the web module namespace by passing the `--web` flag with a module name, for example: mix phx.gen.live Sales User users --web Sales Which would generate a LiveViews inside `lib/app_web/live/sales/user_live/` and a view at `lib/app_web/views/sales/user_view.ex`. ## Customising the context, schema, tables and migrations In some cases, you may wish to bootstrap HTML templates, LiveViews, and tests, but leave internal implementation of the context or schema to yourself. You can use the `--no-context` and `--no-schema` flags for file generation control. You can also change the table name or configure the migrations to use binary ids for primary keys, see `mix phx.gen.schema` for more information. """ use Mix.Task alias Mix.Phoenix.{Context,Schema} alias Mix.Tasks.Phx.Gen import Mix.Tasks.Phx.Gen.Live, only: [print_shell_instructions: 1] @doc false def run(args) do if Mix.Project.umbrella?() do Mix.raise "mix phx.gen.live must be invoked from within your *_web application root directory" end {context, schema} = Gen.Context.build(args) Gen.Context.prompt_for_code_injection(context) binding = [context: context, schema: schema, inputs: inputs(schema)] paths = [".", :phoenix_slime, :phoenix] prompt_for_conflicts(context) context |> copy_new_files(binding, paths) |> maybe_inject_helpers() |> print_shell_instructions() end defp prompt_for_conflicts(context) do context |> files_to_be_generated() |> Kernel.++(context_files(context)) |> Mix.Phoenix.prompt_for_conflicts() end defp context_files(%Context{generate?: true} = context) do Gen.Context.files_to_be_generated(context) end defp context_files(%Context{generate?: false}) do [] end defp files_to_be_generated(%Context{schema: schema, context_app: context_app}) do web_prefix = Mix.Phoenix.web_path(context_app) test_prefix = Mix.Phoenix.web_test_path(context_app) web_path = to_string(schema.web_path) live_subdir = "#{schema.singular}_live" [ {:eex, "show.ex", Path.join([web_prefix, "live", web_path, live_subdir, "show.ex"])}, {:eex, "index.ex", Path.join([web_prefix, "live", web_path, live_subdir, "index.ex"])}, {:eex, "form_component.ex", Path.join([web_prefix, "live", web_path, live_subdir, "form_component.ex"])}, {:eex, "form_component.html.leex", Path.join([web_prefix, "live", web_path, live_subdir, "form_component.html.slimleex"])}, {:eex, "index.html.leex", Path.join([web_prefix, "live", web_path, live_subdir, "index.html.slimleex"])}, {:eex, "show.html.leex", Path.join([web_prefix, "live", web_path, live_subdir, "show.html.slimleex"])}, {:eex, "live_test.exs", Path.join([test_prefix, "live", web_path, "#{schema.singular}_live_test.exs"])}, {:new_eex, "modal_component.ex", Path.join([web_prefix, "live", "modal_component.ex"])}, {:new_eex, "live_helpers.ex", Path.join([web_prefix, "live", "live_helpers.ex"])}, ] end defp copy_new_files(%Context{} = context, binding, paths) do files = files_to_be_generated(context) Mix.Phoenix.copy_from(paths, "priv/templates/phx.gen.live.slime", binding, files) if context.generate?, do: Gen.Context.copy_new_files(context, paths, binding) context end defp maybe_inject_helpers(%Context{context_app: ctx_app} = context) do web_prefix = Mix.Phoenix.web_path(ctx_app) [lib_prefix, web_dir] = Path.split(web_prefix) file_path = Path.join(lib_prefix, "#{web_dir}.ex") file = File.read!(file_path) inject = "import #{inspect(context.web_module)}.LiveHelpers" if String.contains?(file, inject) do :ok else do_inject_helpers(context, file, file_path, inject) end context end defp do_inject_helpers(context, file, file_path, inject) do Mix.shell().info([:green, "* injecting ", :reset, Path.relative_to_cwd(file_path)]) new_file = String.replace(file, "import Phoenix.LiveView.Helpers", "import Phoenix.LiveView.Helpers\n #{inject}") if file != new_file do File.write!(file_path, new_file) else Mix.shell().info """ Could not find Phoenix.LiveView.Helpers imported in #{file_path}. This typically happens because your application was not generated with the --live flag: mix phx.new my_app --live Please make sure LiveView is installed and that #{inspect(context.web_module)} defines both `live_view/0` and `live_component/0` functions, and that both functions import #{inspect(context.web_module)}.LiveHelpers. """ end end defp live_route_instructions(schema) do [ ~s|live "/#{schema.plural}", #{inspect(schema.alias)}Live.Index, :index\n|, ~s|live "/#{schema.plural}/new", #{inspect(schema.alias)}Live.Index, :new\n|, ~s|live "/#{schema.plural}/:id/edit", #{inspect(schema.alias)}Live.Index, :edit\n\n|, ~s|live "/#{schema.plural}/:id", #{inspect(schema.alias)}Live.Show, :show\n|, ~s|live "/#{schema.plural}/:id/show/edit", #{inspect(schema.alias)}Live.Show, :edit| ] end defp inputs(%Schema{attrs: attrs}) do Enum.map(attrs, fn {_, {:array, _}} -> {nil, nil, nil} {_, {:references, _}} -> {nil, nil, nil} {key, :integer} -> {label(key), ~s(= number_input f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, :float} -> {label(key), ~s(= number_input f, #{inspect(key)}, step: "any", class: "form-control", autocomplete: "off"), error(key)} {key, :decimal} -> {label(key), ~s(= number_input f, #{inspect(key)}, step: "any", class: "form-control", autocomplete: "off"), error(key)} {key, :boolean} -> {label(key), ~s(= checkbox f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, :text} -> {label(key), ~s(= textarea f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, :date} -> {label(key), ~s(= date_select f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, :time} -> {label(key), ~s(= time_select f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, :utc_datetime} -> {label(key), ~s(= datetime_select f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, :naive_datetime} -> {label(key), ~s(= datetime_select f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} {key, _} -> {label(key), ~s(= text_input f, #{inspect(key)}, class: "form-control", autocomplete: "off"), error(key)} end) end defp label(key) do ~s(= label f, #{inspect(key)}, class: "control-label") end defp error(field) do ~s(= error_tag f, #{inspect(field)}) end end
39.652
130
0.67699
79e346c5799d46b034f79157809159a477f9b65d
911
ex
Elixir
plugins/ucc_chat/lib/ucc_chat/services/attachment_service.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
plugins/ucc_chat/lib/ucc_chat/services/attachment_service.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
plugins/ucc_chat/lib/ucc_chat/services/attachment_service.ex
josephkabraham/ucx_ucc
0dbd9e3eb5940336b4870cff033482ceba5f6ee7
[ "MIT" ]
null
null
null
defmodule UccChat.AttachmentService do use UccChat.Shared, :service alias UccChat.{Attachment} require Logger def delete_attachment(%UccChat.Schema.Attachment{} = attachment) do Logger.warn "deprecated" case Attachment.delete attachment do {:ok, _} = res -> path = UccChat.File.storage_dir(attachment) File.rm_rf path res error -> error end end # defp broadcast_message(message) do # channel = Channel.get message.channel_id # html = # message # |> Repo.preload(MessageService.preloads()) # |> MessageService.render_message # MessageService.broadcast_message(message.id, channel.name, message.user_id, html) # end def count(message_id) do Attachment.count message_id end def allowed?(channel) do UccSettings.file_uploads_enabled() && ((channel.type != 2) || UccSettings.dm_file_uploads()) end end
25.305556
96
0.684962
79e36d8abb1c7e81dc2af63795db7b614ec285fe
85
exs
Elixir
.formatter.exs
davorbadrov/memoize
dd34c313de805e57da18c4e6142247cc8eb1ba6a
[ "MIT" ]
null
null
null
.formatter.exs
davorbadrov/memoize
dd34c313de805e57da18c4e6142247cc8eb1ba6a
[ "MIT" ]
null
null
null
.formatter.exs
davorbadrov/memoize
dd34c313de805e57da18c4e6142247cc8eb1ba6a
[ "MIT" ]
null
null
null
[ inputs: [".formatter.exs", "mix.exs", "{bench,config,lib,test}/**/*.{ex,exs}"] ]
21.25
80
0.552941
79e391468b7e20ba4c11a7fb3258c46155680a64
2,512
ex
Elixir
apps/badger_data/lib/badger_data/api/user.ex
andyl/logstore
763580ce6f75b2735adfc919b80c37ed5064a04e
[ "MIT" ]
null
null
null
apps/badger_data/lib/badger_data/api/user.ex
andyl/logstore
763580ce6f75b2735adfc919b80c37ed5064a04e
[ "MIT" ]
9
2021-03-09T20:25:18.000Z
2021-05-27T12:58:03.000Z
apps/badger_data/lib/badger_data/api/user.ex
andyl/badger
763580ce6f75b2735adfc919b80c37ed5064a04e
[ "MIT" ]
null
null
null
defmodule BadgerData.Api.User do alias BadgerData.Schema.{User, Site, Token, View, Downstream} alias BadgerData.Repo import Ecto.Query # ----- user_one ----- def user_one do Repo.get_by(User, id: 1) || User.changeset(%User{}, %{name: "aaa", email: "aaa", pwd_hash: User.pwd_hash("aaa"), id: 1}) |> Repo.insert!() end # ----- queries ----- def sites(user_id) do from(sit in Site, where: sit.user_id == ^user_id, order_by: sit.id, select: %{ site_id: sit.id, site_tag: sit.tag, site_name: sit.name, site_url: sit.url } ) |> Repo.all() end def views(user_id) do from(sit in Site, join: tok in Token, on: tok.site_id == sit.id, join: vie in View, on: vie.token_id == tok.id, where: sit.user_id == ^user_id, order_by: [desc: vie.id], limit: 100, select: %{ site_id: sit.id, site_name: sit.name, site_url: sit.url, token_id: tok.id, token_path: tok.path, view_id: vie.id, view_cip: vie.client_ip, view_cua: vie.client_ua, view_date: vie.inserted_at } ) |> Repo.all() end def downstreams(user_id) do from(dstream in Downstream, where: dstream.user_id == ^user_id, select: %{ id: dstream.id, name: dstream.name, type: dstream.type, config: dstream.config } ) |> Repo.all() end # ----- users ----- def user_list do Repo.all(User) end def user_get(user_id) do Repo.get(User, user_id) end def user_get_by(params) do Repo.get_by(User, params) end def user_get_by_email(email) do from(usr in User, where: fragment("email ilike ?", ^email)) |> Repo.one() end def user_add(opts) do %User{} |> User.changeset(opts) |> Repo.insert() end def user_signup(opts) do %User{} |> User.signup_changeset(opts) |> Repo.insert() end def user_changeset(%User{} = user) do User.changeset(user, %{}) end def user_change(_user_id) do end def user_change_pwd(_user_id, _newpwd) do end def user_delete(_user_id) do end def user_auth_by_email_and_pwd(email, pwd) do user = user_get_by_email(email) cond do user && Pbkdf2.verify_pass(pwd, user.pwd_hash) -> {:ok, user} user -> {:error, :unauthorized} true -> Pbkdf2.no_user_verify() {:error, :not_found} end end end
19.936508
116
0.574045
79e3946bcd3e623204370d9412f9dde856420d27
1,903
ex
Elixir
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__list_models_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__list_models_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
null
null
null
clients/machine_learning/lib/google_api/machine_learning/v1/model/google_cloud_ml_v1__list_models_response.ex
leandrocp/elixir-google-api
a86e46907f396d40aeff8668c3bd81662f44c71e
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1ListModelsResponse do @moduledoc """ Response message for the ListModels method. ## Attributes - models ([GoogleCloudMlV1Model]): The list of models. Defaults to: `null`. - nextPageToken (String.t): Optional. Pass this token as the &#x60;page_token&#x60; field of the request for a subsequent call. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :models => list(GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1Model.t()), :nextPageToken => any() } field(:models, as: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1Model, type: :list) field(:nextPageToken) end defimpl Poison.Decoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1ListModelsResponse do def decode(value, options) do GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1ListModelsResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.MachineLearning.V1.Model.GoogleCloudMlV1ListModelsResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.313725
150
0.758802
79e39e23ae94561e2ac334eb6773028aac956779
512
exs
Elixir
priv/repo/migrations/20211006201122_create_memberships.exs
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
null
null
null
priv/repo/migrations/20211006201122_create_memberships.exs
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
4
2021-12-07T12:26:50.000Z
2021-12-30T14:17:25.000Z
priv/repo/migrations/20211006201122_create_memberships.exs
patrotom/adaptable-costs-evaluator
c97e65af1e021d7c6acf6564f4671c60321346e3
[ "MIT" ]
null
null
null
defmodule AdaptableCostsEvaluator.Repo.Migrations.CreateMemberships do use Ecto.Migration def change do create table(:memberships) do add :user_id, references(:users, on_delete: :delete_all), null: false add :organization_id, references(:organizations, on_delete: :delete_all), null: false timestamps() end create index(:memberships, [:user_id]) create index(:memberships, [:organization_id]) create unique_index(:memberships, [:user_id, :organization_id]) end end
30.117647
91
0.730469
79e39f264cf64ceb5ef3648134925ba251d5408d
171,303
ex
Elixir
lib/elixir/lib/kernel.ex
sthagen/elixir-lang-elixir
bab0c7e7738eb7957254bbede93a741e2a61d4ce
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel.ex
sthagen/elixir-lang-elixir
bab0c7e7738eb7957254bbede93a741e2a61d4ce
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel.ex
sthagen/elixir-lang-elixir
bab0c7e7738eb7957254bbede93a741e2a61d4ce
[ "Apache-2.0" ]
null
null
null
# Use elixir_bootstrap module to be able to bootstrap Kernel. # The bootstrap module provides simpler implementations of the # functions removed, simple enough to bootstrap. import Kernel, except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2] import :elixir_bootstrap defmodule Kernel do @moduledoc """ `Kernel` is Elixir's default environment. It mainly consists of: * basic language primitives, such as arithmetic operators, spawning of processes, data type handling, and others * macros for control-flow and defining new functionality (modules, functions, and the like) * guard checks for augmenting pattern matching You can invoke `Kernel` functions and macros anywhere in Elixir code without the use of the `Kernel.` prefix since they have all been automatically imported. For example, in IEx, you can call: iex> is_number(13) true If you don't want to import a function or macro from `Kernel`, use the `:except` option and then list the function/macro by arity: import Kernel, except: [if: 2, unless: 2] See `Kernel.SpecialForms.import/2` for more information on importing. Elixir also has special forms that are always imported and cannot be skipped. These are described in `Kernel.SpecialForms`. ## The standard library `Kernel` provides the basic capabilities the Elixir standard library is built on top of. It is recommended to explore the standard library for advanced functionality. Here are the main groups of modules in the standard library (this list is not a complete reference, see the documentation sidebar for all entries). ### Built-in types The following modules handle Elixir built-in data types: * `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms) * `Float` - numbers with floating point precision * `Function` - a reference to code chunk, created with the `fn/1` special form * `Integer` - whole numbers (not fractions) * `List` - collections of a variable number of elements (linked lists) * `Map` - collections of key-value pairs * `Process` - light-weight threads of execution * `Port` - mechanisms to interact with the external world * `Tuple` - collections of a fixed number of elements There are two data types without an accompanying module: * Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>/1`. When the number of bits is divisible by 8, they are called binaries and can be manipulated with Erlang's `:binary` module * Reference - a unique value in the runtime system, created with `make_ref/0` ### Data types Elixir also provides other data types that are built on top of the types listed above. Some of them are: * `Date` - `year-month-day` structs in a given calendar * `DateTime` - date and time with time zone in a given calendar * `Exception` - data raised from errors and unexpected scenarios * `MapSet` - unordered collections of unique elements * `NaiveDateTime` - date and time without time zone in a given calendar * `Keyword` - lists of two-element tuples, often representing optional values * `Range` - inclusive ranges between two integers * `Regex` - regular expressions * `String` - UTF-8 encoded binaries representing characters * `Time` - `hour:minute:second` structs in a given calendar * `URI` - representation of URIs that identify resources * `Version` - representation of versions and requirements ### System modules Modules that interface with the underlying system, such as: * `IO` - handles input and output * `File` - interacts with the underlying file system * `Path` - manipulates file system paths * `System` - reads and writes system information ### Protocols Protocols add polymorphic dispatch to Elixir. They are contracts implementable by data types. See `Protocol` for more information on protocols. Elixir provides the following protocols in the standard library: * `Collectable` - collects data into a data type * `Enumerable` - handles collections in Elixir. The `Enum` module provides eager functions for working with collections, the `Stream` module provides lazy functions * `Inspect` - converts data types into their programming language representation * `List.Chars` - converts data types to their outside world representation as charlists (non-programming based) * `String.Chars` - converts data types to their outside world representation as strings (non-programming based) ### Process-based and application-centric functionality The following modules build on top of processes to provide concurrency, fault-tolerance, and more. * `Agent` - a process that encapsulates mutable state * `Application` - functions for starting, stopping and configuring applications * `GenServer` - a generic client-server API * `Registry` - a key-value process-based storage * `Supervisor` - a process that is responsible for starting, supervising and shutting down other processes * `Task` - a process that performs computations * `Task.Supervisor` - a supervisor for managing tasks exclusively ### Supporting documents Elixir documentation also includes supporting documents under the "Pages" section. Those are: * [Compatibility and deprecations](compatibility-and-deprecations.md) - lists compatibility between every Elixir version and Erlang/OTP, release schema; lists all deprecated functions, when they were deprecated and alternatives * [Library guidelines](library-guidelines.md) - general guidelines, anti-patterns, and rules for those writing libraries * [Naming conventions](naming-conventions.md) - naming conventions for Elixir code * [Operators](operators.md) - lists all Elixir operators and their precedences * [Patterns and guards](patterns-and-guards.md) - an introduction to patterns, guards, and extensions * [Syntax reference](syntax-reference.md) - the language syntax reference * [Typespecs](typespecs.md)- types and function specifications, including list of types * [Unicode syntax](unicode-syntax.md) - outlines Elixir support for Unicode * [Writing documentation](writing-documentation.md) - guidelines for writing documentation in Elixir ## Guards This module includes the built-in guards used by Elixir developers. They are a predefined set of functions and macros that augment pattern matching, typically invoked after the `when` operator. For example: def drive(%User{age: age}) when age >= 16 do ... end The clause above will only be invoked if the user's age is more than or equal to 16. Guards also support joining multiple conditions with `and` and `or`. The whole guard is true if all guard expressions will evaluate to `true`. A more complete introduction to guards is available in the [Patterns and guards](patterns-and-guards.md) page. ## Structural comparison The comparison functions in this module perform structural comparison. This means structures are compared based on their representation and not on their semantic value. This is specially important for functions that are meant to provide ordering, such as `>/2`, `</2`, `>=/2`, `<=/2`, `min/2`, and `max/2`. For example: ~D[2017-03-31] > ~D[2017-04-01] will return `true` because structural comparison compares the `:day` field before `:month` or `:year`. Therefore, when comparing structs, you often use the `compare/2` function made available by the structs modules themselves: iex> Date.compare(~D[2017-03-31], ~D[2017-04-01]) :lt Alternatively, you can use the functions in the `Enum` module to sort or compute a maximum/minimum: iex> Enum.sort([~D[2017-03-31], ~D[2017-04-01]], Date) [~D[2017-03-31], ~D[2017-04-01]] iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date) ~D[2017-04-01] ## Truthy and falsy values Besides the booleans `true` and `false`, Elixir has the concept of a "truthy" or "falsy" value. * a value is truthy when it is neither `false` nor `nil` * a value is falsy when it is either `false` or `nil` Elixir has functions, like `and/2`, that *only* work with booleans, but also functions that work with these truthy/falsy values, like `&&/2` and `!/1`. ### Examples We can check the truthiness of a value by using the `!/1` function twice. Truthy values: iex> !!true true iex> !!5 true iex> !![1,2] true iex> !!"foo" true Falsy values (of which there are exactly two): iex> !!false false iex> !!nil false ## Inlining Some of the functions described in this module are inlined by the Elixir compiler into their Erlang counterparts in the [`:erlang`](`:erlang`) module. Those functions are called BIFs (built-in internal functions) in Erlang-land and they exhibit interesting properties, as some of them are allowed in guards and others are used for compiler optimizations. Most of the inlined functions can be seen in effect when capturing the function: iex> &Kernel.is_atom/1 &:erlang.is_atom/1 Those functions will be explicitly marked in their docs as "inlined by the compiler". """ # We need this check only for bootstrap purposes. # Once Kernel is loaded and we recompile, it is a no-op. @compile {:inline, bootstrapped?: 1} case :code.ensure_loaded(Kernel) do {:module, _} -> defp bootstrapped?(_), do: true {:error, _} -> defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module} end ## Delegations to Erlang with inlining (macros) @doc """ Returns an integer or float which is the arithmetical absolute value of `number`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> abs(-3.33) 3.33 iex> abs(-3) 3 """ @doc guard: true @spec abs(number) :: number def abs(number) do :erlang.abs(number) end @doc """ Invokes the given anonymous function `fun` with the list of arguments `args`. If the number of arguments is known at compile time, prefer `fun.(arg_1, arg_2, ..., arg_n)` as it is clearer than `apply(fun, [arg_1, arg_2, ..., arg_n])`. Inlined by the compiler. ## Examples iex> apply(fn x -> x * 2 end, [2]) 4 """ @spec apply(fun, [any]) :: any def apply(fun, args) do :erlang.apply(fun, args) end @doc """ Invokes the given function from `module` with the list of arguments `args`. `apply/3` is used to invoke functions where the module, function name or arguments are defined dynamically at runtime. For this reason, you can't invoke macros using `apply/3`, only functions. If the number of arguments and the function name are known at compile time, prefer `module.function(arg_1, arg_2, ..., arg_n)` as it is clearer than `apply(module, :function, [arg_1, arg_2, ..., arg_n])`. `apply/3` cannot be used to call private functions. Inlined by the compiler. ## Examples iex> apply(Enum, :reverse, [[1, 2, 3]]) [3, 2, 1] """ @spec apply(module, function_name :: atom, [any]) :: any def apply(module, function_name, args) do :erlang.apply(module, function_name, args) end @doc """ Extracts the part of the binary starting at `start` with length `length`. Binaries are zero-indexed. If `start` or `length` reference in any way outside the binary, an `ArgumentError` exception is raised. Allowed in guard tests. Inlined by the compiler. ## Examples iex> binary_part("foo", 1, 2) "oo" A negative `length` can be used to extract bytes that come *before* the byte at `start`: iex> binary_part("Hello", 5, -3) "llo" An `ArgumentError` is raised when the length is outside of the binary: binary_part("Hello", 0, 10) ** (ArgumentError) argument error """ @doc guard: true @spec binary_part(binary, non_neg_integer, integer) :: binary def binary_part(binary, start, length) do :erlang.binary_part(binary, start, length) end @doc """ Returns an integer which is the size in bits of `bitstring`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> bit_size(<<433::16, 3::3>>) 19 iex> bit_size(<<1, 2, 3>>) 24 """ @doc guard: true @spec bit_size(bitstring) :: non_neg_integer def bit_size(bitstring) do :erlang.bit_size(bitstring) end @doc """ Returns the number of bytes needed to contain `bitstring`. That is, if the number of bits in `bitstring` is not divisible by 8, the resulting number of bytes will be rounded up (by excess). This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> byte_size(<<433::16, 3::3>>) 3 iex> byte_size(<<1, 2, 3>>) 3 """ @doc guard: true @spec byte_size(bitstring) :: non_neg_integer def byte_size(bitstring) do :erlang.byte_size(bitstring) end @doc """ Returns the smallest integer greater than or equal to `number`. If you want to perform ceil operation on other decimal places, use `Float.ceil/2` instead. Allowed in guard tests. Inlined by the compiler. """ @doc since: "1.8.0", guard: true @spec ceil(number) :: integer def ceil(number) do :erlang.ceil(number) end @doc """ Performs an integer division. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. `div/2` performs *truncated* integer division. This means that the result is always rounded towards zero. If you want to perform floored integer division (rounding towards negative infinity), use `Integer.floor_div/2` instead. Allowed in guard tests. Inlined by the compiler. ## Examples div(5, 2) #=> 2 div(6, -4) #=> -1 div(-99, 2) #=> -49 div(100, 0) ** (ArithmeticError) bad argument in arithmetic expression """ @doc guard: true @spec div(integer, neg_integer | pos_integer) :: integer def div(dividend, divisor) do :erlang.div(dividend, divisor) end @doc """ Stops the execution of the calling process with the given reason. Since evaluating this function causes the process to terminate, it has no return value. Inlined by the compiler. ## Examples When a process reaches its end, by default it exits with reason `:normal`. You can also call `exit/1` explicitly if you want to terminate a process but not signal any failure: exit(:normal) In case something goes wrong, you can also use `exit/1` with a different reason: exit(:seems_bad) If the exit reason is not `:normal`, all the processes linked to the process that exited will crash (unless they are trapping exits). ## OTP exits Exits are used by the OTP to determine if a process exited abnormally or not. The following exits are considered "normal": * `exit(:normal)` * `exit(:shutdown)` * `exit({:shutdown, term})` Exiting with any other reason is considered abnormal and treated as a crash. This means the default supervisor behaviour kicks in, error reports are emitted, and so forth. This behaviour is relied on in many different places. For example, `ExUnit` uses `exit(:shutdown)` when exiting the test process to signal linked processes, supervision trees and so on to politely shut down too. ## CLI exits Building on top of the exit signals mentioned above, if the process started by the command line exits with any of the three reasons above, its exit is considered normal and the Operating System process will exit with status 0. It is, however, possible to customize the operating system exit signal by invoking: exit({:shutdown, integer}) This will cause the operating system process to exit with the status given by `integer` while signaling all linked Erlang processes to politely shut down. Any other exit reason will cause the operating system process to exit with status `1` and linked Erlang processes to crash. """ @spec exit(term) :: no_return def exit(reason) do :erlang.exit(reason) end @doc """ Returns the largest integer smaller than or equal to `number`. If you want to perform floor operation on other decimal places, use `Float.floor/2` instead. Allowed in guard tests. Inlined by the compiler. """ @doc since: "1.8.0", guard: true @spec floor(number) :: integer def floor(number) do :erlang.floor(number) end @doc """ Returns the head of a list. Raises `ArgumentError` if the list is empty. It works with improper lists. Allowed in guard tests. Inlined by the compiler. ## Examples hd([1, 2, 3, 4]) #=> 1 hd([1 | 2]) #=> 1 Giving it an empty list raises: hd([]) #=> ** (ArgumentError) argument error """ @doc guard: true @spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term def hd(list) do :erlang.hd(list) end @doc """ Returns `true` if `term` is an atom; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_atom(false) true iex> is_atom(:name) true iex> is_atom(AnAtom) true iex> is_atom("true") false """ @doc guard: true @spec is_atom(term) :: boolean def is_atom(term) do :erlang.is_atom(term) end @doc """ Returns `true` if `term` is a binary; otherwise returns `false`. A binary always contains a complete number of bytes. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_binary("foo") true iex> is_binary(<<1::3>>) false """ @doc guard: true @spec is_binary(term) :: boolean def is_binary(term) do :erlang.is_binary(term) end @doc """ Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_bitstring("foo") true iex> is_bitstring(<<1::3>>) true """ @doc guard: true @spec is_bitstring(term) :: boolean def is_bitstring(term) do :erlang.is_bitstring(term) end @doc """ Returns `true` if `term` is either the atom `true` or the atom `false` (i.e., a boolean); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_boolean(false) true iex> is_boolean(true) true iex> is_boolean(:test) false """ @doc guard: true @spec is_boolean(term) :: boolean def is_boolean(term) do :erlang.is_boolean(term) end @doc """ Returns `true` if `term` is a floating-point number; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_float(term) :: boolean def is_float(term) do :erlang.is_float(term) end @doc """ Returns `true` if `term` is a function; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_function(fn x -> x + x end) true iex> is_function("not a function") false """ @doc guard: true @spec is_function(term) :: boolean def is_function(term) do :erlang.is_function(term) end @doc """ Returns `true` if `term` is a function that can be applied with `arity` number of arguments; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> is_function(fn x -> x * 2 end, 1) true iex> is_function(fn x -> x * 2 end, 2) false """ @doc guard: true @spec is_function(term, non_neg_integer) :: boolean def is_function(term, arity) do :erlang.is_function(term, arity) end @doc """ Returns `true` if `term` is an integer; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_integer(term) :: boolean def is_integer(term) do :erlang.is_integer(term) end @doc """ Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_list(term) :: boolean def is_list(term) do :erlang.is_list(term) end @doc """ Returns `true` if `term` is either an integer or a floating-point number; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_number(term) :: boolean def is_number(term) do :erlang.is_number(term) end @doc """ Returns `true` if `term` is a PID (process identifier); otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_pid(term) :: boolean def is_pid(term) do :erlang.is_pid(term) end @doc """ Returns `true` if `term` is a port identifier; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_port(term) :: boolean def is_port(term) do :erlang.is_port(term) end @doc """ Returns `true` if `term` is a reference; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_reference(term) :: boolean def is_reference(term) do :erlang.is_reference(term) end @doc """ Returns `true` if `term` is a tuple; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_tuple(term) :: boolean def is_tuple(term) do :erlang.is_tuple(term) end @doc """ Returns `true` if `term` is a map; otherwise returns `false`. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec is_map(term) :: boolean def is_map(term) do :erlang.is_map(term) end @doc """ Returns `true` if `key` is a key in `map`; otherwise returns `false`. It raises `BadMapError` if the first element is not a map. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true, since: "1.10.0" @spec is_map_key(map, term) :: boolean def is_map_key(map, key) do :erlang.is_map_key(key, map) end @doc """ Returns the length of `list`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9]) 9 """ @doc guard: true @spec length(list) :: non_neg_integer def length(list) do :erlang.length(list) end @doc """ Returns an almost unique reference. The returned reference will re-occur after approximately 2^82 calls; therefore it is unique enough for practical purposes. Inlined by the compiler. ## Examples make_ref() #=> #Reference<0.0.0.135> """ @spec make_ref() :: reference def make_ref() do :erlang.make_ref() end @doc """ Returns the size of a map. The size of a map is the number of key-value pairs that the map contains. This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> map_size(%{a: "foo", b: "bar"}) 2 """ @doc guard: true @spec map_size(map) :: non_neg_integer def map_size(map) do :erlang.map_size(map) end @doc """ Returns the biggest of the two given terms according to their structural comparison. If the terms compare equal, the first one is returned. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Inlined by the compiler. ## Examples iex> max(1, 2) 2 iex> max(:a, :b) :b """ @spec max(first, second) :: first | second when first: term, second: term def max(first, second) do :erlang.max(first, second) end @doc """ Returns the smallest of the two given terms according to their structural comparison. If the terms compare equal, the first one is returned. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Inlined by the compiler. ## Examples iex> min(1, 2) 1 iex> min("foo", "bar") "bar" """ @spec min(first, second) :: first | second when first: term, second: term def min(first, second) do :erlang.min(first, second) end @doc """ Returns an atom representing the name of the local node. If the node is not alive, `:nonode@nohost` is returned instead. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec node() :: node def node do :erlang.node() end @doc """ Returns the node where the given argument is located. The argument can be a PID, a reference, or a port. If the local node is not alive, `:nonode@nohost` is returned. Allowed in guard tests. Inlined by the compiler. """ @doc guard: true @spec node(pid | reference | port) :: node def node(arg) do :erlang.node(arg) end @doc """ Computes the remainder of an integer division. `rem/2` uses truncated division, which means that the result will always have the sign of the `dividend`. Raises an `ArithmeticError` exception if one of the arguments is not an integer, or when the `divisor` is `0`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> rem(5, 2) 1 iex> rem(6, -4) 2 """ @doc guard: true @spec rem(integer, neg_integer | pos_integer) :: integer def rem(dividend, divisor) do :erlang.rem(dividend, divisor) end @doc """ Rounds a number to the nearest integer. If the number is equidistant to the two nearest integers, rounds away from zero. Allowed in guard tests. Inlined by the compiler. ## Examples iex> round(5.6) 6 iex> round(5.2) 5 iex> round(-9.9) -10 iex> round(-9) -9 iex> round(2.5) 3 iex> round(-2.5) -3 """ @doc guard: true @spec round(number) :: integer def round(number) do :erlang.round(number) end @doc """ Sends a message to the given `dest` and returns the message. `dest` may be a remote or local PID, a local port, a locally registered name, or a tuple in the form of `{registered_name, node}` for a registered name at another node. Inlined by the compiler. ## Examples iex> send(self(), :hello) :hello """ @spec send(dest :: Process.dest(), message) :: message when message: any def send(dest, message) do :erlang.send(dest, message) end @doc """ Returns the PID (process identifier) of the calling process. Allowed in guard clauses. Inlined by the compiler. """ @doc guard: true @spec self() :: pid def self() do :erlang.self() end @doc """ Spawns the given function and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() child = spawn(fn -> send(current, {self(), 1 + 2}) end) receive do {^child, 3} -> IO.puts("Received 3 back") end """ @spec spawn((() -> any)) :: pid def spawn(fun) do :erlang.spawn(fun) end @doc """ Spawns the given function `fun` from the given `module` passing it the given `args` and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. Inlined by the compiler. ## Examples spawn(SomeModule, :function, [1, 2, 3]) """ @spec spawn(module, atom, list) :: pid def spawn(module, fun, args) do :erlang.spawn(module, fun, args) end @doc """ Spawns the given function, links it to the current process, and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. For more information on linking, check `Process.link/1`. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() child = spawn_link(fn -> send(current, {self(), 1 + 2}) end) receive do {^child, 3} -> IO.puts("Received 3 back") end """ @spec spawn_link((() -> any)) :: pid def spawn_link(fun) do :erlang.spawn_link(fun) end @doc """ Spawns the given function `fun` from the given `module` passing it the given `args`, links it to the current process, and returns its PID. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. For more information on linking, check `Process.link/1`. Inlined by the compiler. ## Examples spawn_link(SomeModule, :function, [1, 2, 3]) """ @spec spawn_link(module, atom, list) :: pid def spawn_link(module, fun, args) do :erlang.spawn_link(module, fun, args) end @doc """ Spawns the given function, monitors it and returns its PID and monitoring reference. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. The anonymous function receives 0 arguments, and may return any value. Inlined by the compiler. ## Examples current = self() spawn_monitor(fn -> send(current, {self(), 1 + 2}) end) """ @spec spawn_monitor((() -> any)) :: {pid, reference} def spawn_monitor(fun) do :erlang.spawn_monitor(fun) end @doc """ Spawns the given module and function passing the given args, monitors it and returns its PID and monitoring reference. Typically developers do not use the `spawn` functions, instead they use abstractions such as `Task`, `GenServer` and `Agent`, built on top of `spawn`, that spawns processes with more conveniences in terms of introspection and debugging. Check the `Process` module for more process-related functions. Inlined by the compiler. ## Examples spawn_monitor(SomeModule, :function, [1, 2, 3]) """ @spec spawn_monitor(module, atom, list) :: {pid, reference} def spawn_monitor(module, fun, args) do :erlang.spawn_monitor(module, fun, args) end @doc """ Pipes the first argument, `value`, into the second argument, a function `fun`, and returns `value` itself. Useful for running synchronous side effects in a pipeline, using the `|>/2` operator. ## Examples iex> tap(1, fn x -> x + 1 end) 1 Most commonly, this is used in pipelines, using the `|>/2` operator. For example, let's suppose you want to inspect part of a data structure. You could write: %{a: 1} |> Map.update!(:a, & &1 + 2) |> tap(&IO.inspect(&1.a)) |> Map.update!(:a, & &1 * 2) """ @doc since: "1.12.0" defmacro tap(value, fun) do quote bind_quoted: [fun: fun, value: value] do _ = fun.(value) value end end @doc """ A non-local return from a function. Using `throw/1` is generally discouraged, as it allows a function to escape from its regular execution flow, which can make the code harder to read. Furthermore, all thrown values must be caught by `try/catch`. See `try/1` for more information. Inlined by the compiler. """ @spec throw(term) :: no_return def throw(term) do :erlang.throw(term) end @doc """ Returns the tail of a list. Raises `ArgumentError` if the list is empty. It works with improper lists. Allowed in guard tests. Inlined by the compiler. ## Examples tl([1, 2, 3, :go]) #=> [2, 3, :go] tl([:one]) #=> [] tl([:a, :b | :c]) #=> [:b | :c] tl([:a | %{b: 1}]) #=> %{b: 1} Giving it an empty list raises: tl([]) #=> ** (ArgumentError) argument error """ @doc guard: true @spec tl(nonempty_maybe_improper_list(elem, last)) :: maybe_improper_list(elem, last) | last when elem: term, last: term def tl(list) do :erlang.tl(list) end @doc """ Returns the integer part of `number`. Allowed in guard tests. Inlined by the compiler. ## Examples iex> trunc(5.4) 5 iex> trunc(-5.99) -5 iex> trunc(-5) -5 """ @doc guard: true @spec trunc(number) :: integer def trunc(number) do :erlang.trunc(number) end @doc """ Returns the size of a tuple. This operation happens in constant time. Allowed in guard tests. Inlined by the compiler. ## Examples iex> tuple_size({:a, :b, :c}) 3 """ @doc guard: true @spec tuple_size(tuple) :: non_neg_integer def tuple_size(tuple) do :erlang.tuple_size(tuple) end @doc """ Arithmetic addition operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 + 2 3 """ @doc guard: true @spec integer + integer :: integer @spec float + float :: float @spec integer + float :: float @spec float + integer :: float def left + right do :erlang.+(left, right) end @doc """ Arithmetic subtraction operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 - 2 -1 """ @doc guard: true @spec integer - integer :: integer @spec float - float :: float @spec integer - float :: float @spec float - integer :: float def left - right do :erlang.-(left, right) end @doc """ Arithmetic positive unary operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> +1 1 """ @doc guard: true @spec +integer :: integer @spec +float :: float def +value do :erlang.+(value) end @doc """ Arithmetic negative unary operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> -2 -2 """ @doc guard: true @spec -0 :: 0 @spec -pos_integer :: neg_integer @spec -neg_integer :: pos_integer @spec -float :: float def -value do :erlang.-(value) end @doc """ Arithmetic multiplication operator. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 * 2 2 """ @doc guard: true @spec integer * integer :: integer @spec float * float :: float @spec integer * float :: float @spec float * integer :: float def left * right do :erlang.*(left, right) end @doc """ Arithmetic division operator. The result is always a float. Use `div/2` and `rem/2` if you want an integer division or the remainder. Raises `ArithmeticError` if `right` is 0 or 0.0. Allowed in guard tests. Inlined by the compiler. ## Examples 1 / 2 #=> 0.5 -3.0 / 2.0 #=> -1.5 5 / 1 #=> 5.0 7 / 0 ** (ArithmeticError) bad argument in arithmetic expression """ @doc guard: true @spec number / number :: float def left / right do :erlang./(left, right) end @doc """ List concatenation operator. Concatenates a proper list and a term, returning a list. The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly appending to lists of arbitrary length, for example, `list ++ [element]`. Instead, consider prepending via `[element | rest]` and then reversing. If the `right` operand is not a proper list, it returns an improper list. If the `left` operand is not a proper list, it raises `ArgumentError`. Inlined by the compiler. ## Examples iex> [1] ++ [2, 3] [1, 2, 3] iex> 'foo' ++ 'bar' 'foobar' # returns an improper list iex> [1] ++ 2 [1 | 2] # returns a proper list iex> [1] ++ [2] [1, 2] # improper list on the right will return an improper list iex> [1] ++ [2 | 3] [1, 2 | 3] """ @spec list ++ term :: maybe_improper_list def left ++ right do :erlang.++(left, right) end @doc """ List subtraction operator. Removes the first occurrence of an element on the left list for each element on the right. This function is optimized so the complexity of `a -- b` is proportional to `length(a) * log(length(b))`. See also the [Erlang efficiency guide](https://www.erlang.org/doc/efficiency_guide/retired_myths.html). Inlined by the compiler. ## Examples iex> [1, 2, 3] -- [1, 2] [3] iex> [1, 2, 3, 2, 1] -- [1, 2, 2] [3, 1] The `--/2` operator is right associative, meaning: iex> [1, 2, 3] -- [2] -- [3] [1, 3] As it is equivalent to: iex> [1, 2, 3] -- ([2] -- [3]) [1, 3] """ @spec list -- list :: list def left -- right do :erlang.--(left, right) end @doc """ Strictly boolean "not" operator. `value` must be a boolean; if it's not, an `ArgumentError` exception is raised. Allowed in guard tests. Inlined by the compiler. ## Examples iex> not false true """ @doc guard: true @spec not true :: false @spec not false :: true def not value do :erlang.not(value) end @doc """ Less-than operator. Returns `true` if `left` is less than `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 < 2 true """ @doc guard: true @spec term < term :: boolean def left < right do :erlang.<(left, right) end @doc """ Greater-than operator. Returns `true` if `left` is more than `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 > 2 false """ @doc guard: true @spec term > term :: boolean def left > right do :erlang.>(left, right) end @doc """ Less-than or equal to operator. Returns `true` if `left` is less than or equal to `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 <= 2 true """ @doc guard: true @spec term <= term :: boolean def left <= right do :erlang."=<"(left, right) end @doc """ Greater-than or equal to operator. Returns `true` if `left` is more than or equal to `right`. This performs a structural comparison where all Elixir terms can be compared with each other. See the ["Structural comparison" section](#module-structural-comparison) section for more information. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 >= 2 false """ @doc guard: true @spec term >= term :: boolean def left >= right do :erlang.>=(left, right) end @doc """ Equal to operator. Returns `true` if the two terms are equal. This operator considers 1 and 1.0 to be equal. For stricter semantics, use `===/2` instead. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 == 2 false iex> 1 == 1.0 true """ @doc guard: true @spec term == term :: boolean def left == right do :erlang.==(left, right) end @doc """ Not equal to operator. Returns `true` if the two terms are not equal. This operator considers 1 and 1.0 to be equal. For match comparison, use `!==/2` instead. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 != 2 true iex> 1 != 1.0 false """ @doc guard: true @spec term != term :: boolean def left != right do :erlang."/="(left, right) end @doc """ Strictly equal to operator. Returns `true` if the two terms are exactly equal. The terms are only considered to be exactly equal if they have the same value and are of the same type. For example, `1 == 1.0` returns `true`, but since they are of different types, `1 === 1.0` returns `false`. All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 === 2 false iex> 1 === 1.0 false """ @doc guard: true @spec term === term :: boolean def left === right do :erlang."=:="(left, right) end @doc """ Strictly not equal to operator. Returns `true` if the two terms are not exactly equal. See `===/2` for a definition of what is considered "exactly equal". All terms in Elixir can be compared with each other. Allowed in guard tests. Inlined by the compiler. ## Examples iex> 1 !== 2 true iex> 1 !== 1.0 true """ @doc guard: true @spec term !== term :: boolean def left !== right do :erlang."=/="(left, right) end @doc """ Gets the element at the zero-based `index` in `tuple`. It raises `ArgumentError` when index is negative or it is out of range of the tuple elements. Allowed in guard tests. Inlined by the compiler. ## Examples tuple = {:foo, :bar, 3} elem(tuple, 1) #=> :bar elem({}, 0) ** (ArgumentError) argument error elem({:foo, :bar}, 2) ** (ArgumentError) argument error """ @doc guard: true @spec elem(tuple, non_neg_integer) :: term def elem(tuple, index) do :erlang.element(index + 1, tuple) end @doc """ Puts `value` at the given zero-based `index` in `tuple`. Inlined by the compiler. ## Examples iex> tuple = {:foo, :bar, 3} iex> put_elem(tuple, 0, :baz) {:baz, :bar, 3} """ @spec put_elem(tuple, non_neg_integer, term) :: tuple def put_elem(tuple, index, value) do :erlang.setelement(index + 1, tuple, value) end ## Implemented in Elixir defp optimize_boolean({:case, meta, args}) do {:case, [{:optimize_boolean, true} | meta], args} end @doc """ Strictly boolean "or" operator. If `left` is `true`, returns `true`; otherwise returns `right`. Requires only the `left` operand to be a boolean since it short-circuits. If the `left` operand is not a boolean, a `BadBooleanError` exception is raised. Allowed in guard tests. ## Examples iex> true or false true iex> false or 42 42 iex> 42 or false ** (BadBooleanError) expected a boolean on left-side of "or", got: 42 """ @doc guard: true defmacro left or right do case __CALLER__.context do nil -> build_boolean_check(:or, left, true, right) :match -> invalid_match!(:or) :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right))) end end @doc """ Strictly boolean "and" operator. If `left` is `false`, returns `false`; otherwise returns `right`. Requires only the `left` operand to be a boolean since it short-circuits. If the `left` operand is not a boolean, a `BadBooleanError` exception is raised. Allowed in guard tests. ## Examples iex> true and false false iex> true and "yay!" "yay!" iex> "yay!" and true ** (BadBooleanError) expected a boolean on left-side of "and", got: "yay!" """ @doc guard: true defmacro left and right do case __CALLER__.context do nil -> build_boolean_check(:and, left, right, false) :match -> invalid_match!(:and) :guard -> quote(do: :erlang.andalso(unquote(left), unquote(right))) end end defp build_boolean_check(operator, check, true_clause, false_clause) do optimize_boolean( quote do case unquote(check) do false -> unquote(false_clause) true -> unquote(true_clause) other -> :erlang.error({:badbool, unquote(operator), other}) end end ) end @doc """ Boolean "not" operator. Receives any value (not just booleans) and returns `true` if `value` is `false` or `nil`; returns `false` otherwise. Not allowed in guard clauses. ## Examples iex> !Enum.empty?([]) false iex> !List.first([]) true """ defmacro !value defmacro !{:!, _, [value]} do assert_no_match_or_guard_scope(__CALLER__.context, "!") optimize_boolean( quote do case unquote(value) do x when :"Elixir.Kernel".in(x, [false, nil]) -> false _ -> true end end ) end defmacro !value do assert_no_match_or_guard_scope(__CALLER__.context, "!") optimize_boolean( quote do case unquote(value) do x when :"Elixir.Kernel".in(x, [false, nil]) -> true _ -> false end end ) end @doc """ Binary concatenation operator. Concatenates two binaries. Raises an `ArgumentError` if one of the sides aren't binaries. ## Examples iex> "foo" <> "bar" "foobar" The `<>/2` operator can also be used in pattern matching (and guard clauses) as long as the left argument is a literal binary: iex> "foo" <> x = "foobar" iex> x "bar" `x <> "bar" = "foobar"` would result in an `ArgumentError` exception. """ defmacro left <> right do concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__) quote(do: <<unquote_splicing(concats)>>) end # Extracts concatenations in order to optimize many # concatenations into one single clause. defp extract_concatenations({:<>, _, [left, right]}, caller) do [wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)] end defp extract_concatenations(other, caller) do [wrap_concatenation(other, :right, caller)] end defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do binary end defp wrap_concatenation(literal, _side, _caller) when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do :erlang.error( ArgumentError.exception( "expected binary argument in <> operator but got: #{Macro.to_string(literal)}" ) ) end defp wrap_concatenation(other, side, caller) do expanded = expand_concat_argument(other, side, caller) {:"::", [], [expanded, {:binary, [], nil}]} end defp expand_concat_argument(arg, :left, %{context: :match} = caller) do expanded_arg = case bootstrapped?(Macro) do true -> Macro.expand(arg, caller) false -> arg end case expanded_arg do {var, _, nil} when is_atom(var) -> invalid_concat_left_argument_error(Atom.to_string(var)) {:^, _, [{var, _, nil}]} when is_atom(var) -> invalid_concat_left_argument_error("^#{Atom.to_string(var)}") _ -> expanded_arg end end defp expand_concat_argument(arg, _, _) do arg end defp invalid_concat_left_argument_error(arg) do :erlang.error( ArgumentError.exception( "the left argument of <> operator inside a match should always be a literal " <> "binary because its size can't be verified. Got: #{arg}" ) ) end @doc """ Raises an exception. If `message` is a string, it raises a `RuntimeError` exception with it. If `message` is an atom, it just calls `raise/2` with the atom as the first argument and `[]` as the second one. If `message` is an exception struct, it is raised as is. If `message` is anything else, `raise` will fail with an `ArgumentError` exception. ## Examples iex> raise "oops" ** (RuntimeError) oops try do 1 + :foo rescue x in [ArithmeticError] -> IO.puts("that was expected") raise x end """ defmacro raise(message) do # Try to figure out the type at compilation time # to avoid dead code and make Dialyzer happy. message = case not is_binary(message) and bootstrapped?(Macro) do true -> Macro.expand(message, __CALLER__) false -> message end erlang_error = case :erlang.system_info(:otp_release) >= '24' do true -> fn x -> quote do :erlang.error(unquote(x), :none, error_info: %{module: Exception}) end end false -> fn x -> quote do :erlang.error(unquote(x)) end end end case message do message when is_binary(message) -> erlang_error.(quote do: RuntimeError.exception(unquote(message))) {:<<>>, _, _} = message -> erlang_error.(quote do: RuntimeError.exception(unquote(message))) alias when is_atom(alias) -> erlang_error.(quote do: unquote(alias).exception([])) _ -> erlang_error.(quote do: Kernel.Utils.raise(unquote(message))) end end @doc """ Raises an exception. Calls the `exception/1` function on the given argument (which has to be a module name like `ArgumentError` or `RuntimeError`) passing `attributes` in order to retrieve the exception struct. Any module that contains a call to the `defexception/1` macro automatically implements the `c:Exception.exception/1` callback expected by `raise/2`. For more information, see `defexception/1`. ## Examples iex> raise(ArgumentError, "Sample") ** (ArgumentError) Sample """ defmacro raise(exception, attributes) do quote do :erlang.error(unquote(exception).exception(unquote(attributes))) end end @doc """ Raises an exception preserving a previous stacktrace. Works like `raise/1` but does not generate a new stacktrace. Note that `__STACKTRACE__` can be used inside catch/rescue to retrieve the current stacktrace. ## Examples try do raise "oops" rescue exception -> reraise exception, __STACKTRACE__ end """ defmacro reraise(message, stacktrace) do # Try to figure out the type at compilation time # to avoid dead code and make Dialyzer happy. case Macro.expand(message, __CALLER__) do message when is_binary(message) -> quote do :erlang.error( :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) ) end {:<<>>, _, _} = message -> quote do :erlang.error( :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) ) end alias when is_atom(alias) -> quote do :erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace))) end message -> quote do :erlang.error( :erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace)) ) end end end @doc """ Raises an exception preserving a previous stacktrace. `reraise/3` works like `reraise/2`, except it passes arguments to the `exception/1` function as explained in `raise/2`. ## Examples try do raise "oops" rescue exception -> reraise WrapperError, [exception: exception], __STACKTRACE__ end """ defmacro reraise(exception, attributes, stacktrace) do quote do :erlang.raise( :error, unquote(exception).exception(unquote(attributes)), unquote(stacktrace) ) end end @doc """ Text-based match operator. Matches the term on the `left` against the regular expression or string on the `right`. If `right` is a regular expression, returns `true` if `left` matches right. If `right` is a string, returns `true` if `left` contains `right`. ## Examples iex> "abcd" =~ ~r/c(d)/ true iex> "abcd" =~ ~r/e/ false iex> "abcd" =~ ~r// true iex> "abcd" =~ "bc" true iex> "abcd" =~ "ad" false iex> "abcd" =~ "abcd" true iex> "abcd" =~ "" true For more information about regular expressions, please check the `Regex` module. """ @spec String.t() =~ (String.t() | Regex.t()) :: boolean def left =~ "" when is_binary(left), do: true def left =~ right when is_binary(left) and is_binary(right) do :binary.match(left, right) != :nomatch end def left =~ right when is_binary(left) do Regex.match?(right, left) end @doc ~S""" Inspects the given argument according to the `Inspect` protocol. The second argument is a keyword list with options to control inspection. ## Options `inspect/2` accepts a list of options that are internally translated to an `Inspect.Opts` struct. Check the docs for `Inspect.Opts` to see the supported options. ## Examples iex> inspect(:foo) ":foo" iex> inspect([1, 2, 3, 4, 5], limit: 3) "[1, 2, 3, ...]" iex> inspect([1, 2, 3], pretty: true, width: 0) "[1,\n 2,\n 3]" iex> inspect("olá" <> <<0>>) "<<111, 108, 195, 161, 0>>" iex> inspect("olá" <> <<0>>, binaries: :as_strings) "\"olá\\0\"" iex> inspect("olá", binaries: :as_binaries) "<<111, 108, 195, 161>>" iex> inspect('bar') "'bar'" iex> inspect([0 | 'bar']) "[0, 98, 97, 114]" iex> inspect(100, base: :octal) "0o144" iex> inspect(100, base: :hex) "0x64" Note that the `Inspect` protocol does not necessarily return a valid representation of an Elixir term. In such cases, the inspected result must start with `#`. For example, inspecting a function will return: inspect(fn a, b -> a + b end) #=> #Function<...> The `Inspect` protocol can be derived to hide certain fields from structs, so they don't show up in logs, inspects and similar. See the "Deriving" section of the documentation of the `Inspect` protocol for more information. """ @spec inspect(Inspect.t(), keyword) :: String.t() def inspect(term, opts \\ []) when is_list(opts) do opts = Inspect.Opts.new(opts) limit = case opts.pretty do true -> opts.width false -> :infinity end doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts)) IO.iodata_to_binary(Inspect.Algebra.format(doc, limit)) end @doc """ Creates and updates a struct. The `struct` argument may be an atom (which defines `defstruct`) or a `struct` itself. The second argument is any `Enumerable` that emits two-element tuples (key-value pairs) during enumeration. Keys in the `Enumerable` that don't exist in the struct are automatically discarded. Note that keys must be atoms, as only atoms are allowed when defining a struct. If keys in the `Enumerable` are duplicated, the last entry will be taken (same behaviour as `Map.new/1`). This function is useful for dynamically creating and updating structs, as well as for converting maps to structs; in the latter case, just inserting the appropriate `:__struct__` field into the map may not be enough and `struct/2` should be used instead. ## Examples defmodule User do defstruct name: "john" end struct(User) #=> %User{name: "john"} opts = [name: "meg"] user = struct(User, opts) #=> %User{name: "meg"} struct(user, unknown: "value") #=> %User{name: "meg"} struct(User, %{name: "meg"}) #=> %User{name: "meg"} # String keys are ignored struct(User, %{"name" => "meg"}) #=> %User{name: "john"} """ @spec struct(module | struct, Enumerable.t()) :: struct def struct(struct, fields \\ []) do struct(struct, fields, fn {:__struct__, _val}, acc -> acc {key, val}, acc -> case acc do %{^key => _} -> %{acc | key => val} _ -> acc end end) end @doc """ Similar to `struct/2` but checks for key validity. The function `struct!/2` emulates the compile time behaviour of structs. This means that: * when building a struct, as in `struct!(SomeStruct, key: :value)`, it is equivalent to `%SomeStruct{key: :value}` and therefore this function will check if every given key-value belongs to the struct. If the struct is enforcing any key via `@enforce_keys`, those will be enforced as well; * when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`, it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this function will check if every given key-value belongs to the struct. However, updating structs does not enforce keys, as keys are enforced only when building; """ @spec struct!(module | struct, Enumerable.t()) :: struct def struct!(struct, fields \\ []) def struct!(struct, fields) when is_atom(struct) do validate_struct!(struct.__struct__(fields), struct, 1) end def struct!(struct, fields) when is_map(struct) do struct(struct, fields, fn {:__struct__, _}, acc -> acc {key, val}, acc -> Map.replace!(acc, key, val) end) end defp struct(struct, [], _fun) when is_atom(struct) do validate_struct!(struct.__struct__(), struct, 0) end defp struct(struct, fields, fun) when is_atom(struct) do struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun) end defp struct(%_{} = struct, [], _fun) do struct end defp struct(%_{} = struct, fields, fun) do Enum.reduce(fields, struct, fun) end defp validate_struct!(%{__struct__: module} = struct, module, _arity) do struct end defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do error_message = "expected struct name returned by #{inspect(module)}.__struct__/#{arity} to be " <> "#{inspect(module)}, got: #{inspect(struct_name)}" :erlang.error(ArgumentError.exception(error_message)) end defp validate_struct!(expr, module, arity) do error_message = "expected #{inspect(module)}.__struct__/#{arity} to return a map with a :__struct__ " <> "key that holds the name of the struct (atom), got: #{inspect(expr)}" :erlang.error(ArgumentError.exception(error_message)) end @doc """ Returns true if `term` is a struct; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_struct(URI.parse("/")) true iex> is_struct(%{}) false """ @doc since: "1.10.0", guard: true defmacro is_struct(term) do case __CALLER__.context do nil -> quote do case unquote(term) do %_{} -> true _ -> false end end :match -> invalid_match!(:is_struct) :guard -> quote do is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and is_atom(:erlang.map_get(:__struct__, unquote(term))) end end end @doc """ Returns true if `term` is a struct of `name`; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_struct(URI.parse("/"), URI) true iex> is_struct(URI.parse("/"), Macro.Env) false """ @doc since: "1.11.0", guard: true defmacro is_struct(term, name) do case __CALLER__.context do nil -> quote generated: true do case unquote(name) do name when is_atom(name) -> case unquote(term) do %{__struct__: ^name} -> true _ -> false end _ -> raise ArgumentError end end :match -> invalid_match!(:is_struct) :guard -> quote do is_map(unquote(term)) and (is_atom(unquote(name)) or :fail) and :erlang.is_map_key(:__struct__, unquote(term)) and :erlang.map_get(:__struct__, unquote(term)) == unquote(name) end end end @doc """ Returns true if `term` is an exception; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_exception(%RuntimeError{}) true iex> is_exception(%{}) false """ @doc since: "1.11.0", guard: true defmacro is_exception(term) do case __CALLER__.context do nil -> quote do case unquote(term) do %_{__exception__: true} -> true _ -> false end end :match -> invalid_match!(:is_exception) :guard -> quote do is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and is_atom(:erlang.map_get(:__struct__, unquote(term))) and :erlang.is_map_key(:__exception__, unquote(term)) and :erlang.map_get(:__exception__, unquote(term)) == true end end end @doc """ Returns true if `term` is an exception of `name`; otherwise returns `false`. Allowed in guard tests. ## Examples iex> is_exception(%RuntimeError{}, RuntimeError) true iex> is_exception(%RuntimeError{}, Macro.Env) false """ @doc since: "1.11.0", guard: true defmacro is_exception(term, name) do case __CALLER__.context do nil -> quote do case unquote(name) do name when is_atom(name) -> case unquote(term) do %{__struct__: ^name, __exception__: true} -> true _ -> false end _ -> raise ArgumentError end end :match -> invalid_match!(:is_exception) :guard -> quote do is_map(unquote(term)) and (is_atom(unquote(name)) or :fail) and :erlang.is_map_key(:__struct__, unquote(term)) and :erlang.map_get(:__struct__, unquote(term)) == unquote(name) and :erlang.is_map_key(:__exception__, unquote(term)) and :erlang.map_get(:__exception__, unquote(term)) == true end end end @doc """ Pipes the first argument, `value`, into the second argument, a function `fun`, and returns the result of calling `fun`. In other words, it invokes the function `fun` with `value` as argument, and returns its result. This is most commonly used in pipelines, using the `|>/2` operator, allowing you to pipe a value to a function outside of its first argument. ### Examples iex> 1 |> then(fn x -> x * 2 end) 2 iex> 1 |> then(fn x -> Enum.drop(["a", "b", "c"], x) end) ["b", "c"] """ @doc since: "1.12.0" defmacro then(value, fun) do quote do unquote(fun).(unquote(value)) end end @doc """ Gets a value from a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function, which is detailed in a later section. Note that if none of the given keys are functions, there is rarely a reason to use `get_in` over writing "regular" Elixir code using `[]`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_in(users, ["john", :age]) 27 iex> # Equivalent to: iex> users["john"][:age] 27 `get_in/2` can also use the accessors in the `Access` module to traverse more complex data structures. For example, here we use `Access.all/0` to traverse a list: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> get_in(users, [Access.all(), :age]) [27, 23] In case any of the components returns `nil`, `nil` will be returned and `get_in/2` won't traverse any further: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_in(users, ["unknown", :age]) nil iex> # Equivalent to: iex> users["unknown"][:age] nil iex> users = nil iex> get_in(users, [Access.all(), :age]) nil Alternatively, if you need to access complex data-structures, you can use pattern matching: case users do %{"john" => %{age: age}} -> age _ -> default_value end ## Functions as keys If a key given to `get_in/2` is a function, the function will be invoked passing three arguments: * the operation (`:get`) * the data to be accessed * a function to be invoked next This means `get_in/2` can be extended to provide custom lookups. That's precisely how the `Access.all/0` key in the previous section behaves. For example, we can manually implement such traversal as follows: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> all = fn :get, data, next -> Enum.map(data, next) end iex> get_in(users, [all, :age]) [27, 23] The `Access` module ships with many convenience accessor functions. See `Access.all/0`, `Access.key/2`, and others as examples. ## Working with structs By default, structs do not implement the `Access` behaviour required by this function. Therefore, you can't do this: get_in(some_struct, [:some_key, :nested_key]) The good news is that structs have predefined shape. Therefore, you can write instead: some_struct.some_key.nested_key If, by any chance, `some_key` can return nil, you can always fallback to pattern matching to provide nested struct handling: case some_struct do %{some_key: %{nested_key: value}} -> value %{} -> nil end """ @spec get_in(Access.t(), nonempty_list(term)) :: term def get_in(data, keys) def get_in(nil, [_ | _]), do: nil def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1) def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t)) def get_in(data, [h]), do: Access.get(data, h) def get_in(data, [h | t]), do: get_in(Access.get(data, h), t) @doc """ Puts a value in a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users, ["john", :age], 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} If any of the intermediate values are nil, it will raise: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users, ["jane", :age], "oops") ** (ArgumentError) could not put/update key :age on a nil value """ @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t() def put_in(data, [_ | _] = keys, value) do elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1) end @doc """ Updates a key in a nested structure. Uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. `data` is a nested structure (that is, a map, keyword list, or struct that implements the `Access` behaviour). The `fun` argument receives the value of `key` (or `nil` if `key` is not present) and the result replaces the value in the structure. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users, ["john", :age], &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} Note the current value given to the anonymous function may be `nil`. If any of the intermediate values are nil, it will raise: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users, ["jane", :age], & &1 + 1) ** (ArgumentError) could not put/update key :age on a nil value """ @spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t() def update_in(data, [_ | _] = keys, fun) when is_function(fun) do elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1) end @doc """ Gets a value and updates a nested structure. `data` is a nested structure (that is, a map, keyword list, or struct that implements the `Access` behaviour). The `fun` argument receives the value of `key` (or `nil` if `key` is not present) and must return one of the following values: * a two-element tuple `{current_value, new_value}`. In this case, `current_value` is the retrieved value which can possibly be operated on before being returned. `new_value` is the new value to be stored under `key`. * `:pop`, which implies that the current value under `key` should be removed from the structure and returned. This function uses the `Access` module to traverse the structures according to the given `keys`, unless the `key` is a function, which is detailed in a later section. ## Examples This function is useful when there is a need to retrieve the current value (or something calculated in function of the current value) and update it at the same time. For example, it could be used to read the current age of a user while increasing it by one in one pass: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1}) {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} Note the current value given to the anonymous function may be `nil`. If any of the intermediate values are nil, it will raise: iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users, ["jane", :age], &{&1, &1 + 1}) ** (ArgumentError) could not put/update key :age on a nil value ## Functions as keys If a key is a function, the function will be invoked passing three arguments: * the operation (`:get_and_update`) * the data to be accessed * a function to be invoked next This means `get_and_update_in/3` can be extended to provide custom lookups. The downside is that functions cannot be stored as keys in the accessed data structures. When one of the keys is a function, the function is invoked. In the example below, we use a function to get and increment all ages inside a list: iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] iex> all = fn :get_and_update, data, next -> ...> data |> Enum.map(next) |> Enum.unzip() ...> end iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1}) {[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]} If the previous value before invoking the function is `nil`, the function *will* receive `nil` as a value and must handle it accordingly (be it by failing or providing a sane default). The `Access` module ships with many convenience accessor functions, like the `all` anonymous function defined above. See `Access.all/0`, `Access.key/2`, and others as examples. """ @spec get_and_update_in( structure, keys, (term | nil -> {current_value, new_value} | :pop) ) :: {current_value, new_structure :: structure} when structure: Access.t(), keys: nonempty_list(any), current_value: Access.value(), new_value: Access.value() def get_and_update_in(data, keys, fun) def get_and_update_in(data, [head], fun) when is_function(head, 3), do: head.(:get_and_update, data, fun) def get_and_update_in(data, [head | tail], fun) when is_function(head, 3), do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun)) def get_and_update_in(data, [head], fun) when is_function(fun, 1), do: Access.get_and_update(data, head, fun) def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1), do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun)) @doc """ Pops a key from the given nested structure. Uses the `Access` protocol to traverse the structures according to the given `keys`, unless the `key` is a function. If the key is a function, it will be invoked as specified in `get_and_update_in/3`. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users, ["john", :age]) {27, %{"john" => %{}, "meg" => %{age: 23}}} In case any entry returns `nil`, its key will be removed and the deletion will be considered a success. iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users, ["jane", :age]) {nil, %{"john" => %{age: 27}, "meg" => %{age: 23}}} """ @spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data} when data: Access.container() def pop_in(data, keys) def pop_in(nil, [key | _]) do raise ArgumentError, "could not pop key #{inspect(key)} on a nil value" end def pop_in(data, [_ | _] = keys) do pop_in_data(data, keys) end defp pop_in_data(nil, [_ | _]), do: :pop defp pop_in_data(data, [fun]) when is_function(fun), do: fun.(:get_and_update, data, fn _ -> :pop end) defp pop_in_data(data, [fun | tail]) when is_function(fun), do: fun.(:get_and_update, data, &pop_in_data(&1, tail)) defp pop_in_data(data, [key]), do: Access.pop(data, key) defp pop_in_data(data, [key | tail]), do: Access.get_and_update(data, key, &pop_in_data(&1, tail)) @doc """ Puts a value in a nested structure via the given `path`. This is similar to `put_in/3`, except the path is extracted via a macro rather than passing a list. For example: put_in(opts[:foo][:bar], :baz) Is equivalent to: put_in(opts, [:foo, :bar], :baz) This also works with nested structs and the `struct.path.to.value` way to specify paths: put_in(struct.foo.bar, :baz) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users["john"][:age], 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> put_in(users["john"].age, 28) %{"john" => %{age: 28}, "meg" => %{age: 23}} """ defmacro put_in(path, value) do case unnest(path, [], true, "put_in/2") do {[h | t], true} -> nest_update_in(h, t, quote(do: fn _ -> unquote(value) end)) {[h | t], false} -> expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end)) quote(do: :erlang.element(2, unquote(expr))) end end @doc """ Pops a key from the nested structure via the given `path`. This is similar to `pop_in/2`, except the path is extracted via a macro rather than passing a list. For example: pop_in(opts[:foo][:bar]) Is equivalent to: pop_in(opts, [:foo, :bar]) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> pop_in(users["john"][:age]) {27, %{"john" => %{}, "meg" => %{age: 23}}} iex> users = %{john: %{age: 27}, meg: %{age: 23}} iex> pop_in(users.john[:age]) {27, %{john: %{}, meg: %{age: 23}}} In case any entry returns `nil`, its key will be removed and the deletion will be considered a success. """ defmacro pop_in(path) do {[h | t], _} = unnest(path, [], true, "pop_in/1") nest_pop_in(:map, h, t) end @doc """ Updates a nested structure via the given `path`. This is similar to `update_in/3`, except the path is extracted via a macro rather than passing a list. For example: update_in(opts[:foo][:bar], &(&1 + 1)) Is equivalent to: update_in(opts, [:foo, :bar], &(&1 + 1)) This also works with nested structs and the `struct.path.to.value` way to specify paths: update_in(struct.foo.bar, &(&1 + 1)) Note that in order for this macro to work, the complete path must always be visible by this macro. For more information about the supported path expressions, please check `get_and_update_in/2` docs. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users["john"][:age], &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> update_in(users["john"].age, &(&1 + 1)) %{"john" => %{age: 28}, "meg" => %{age: 23}} """ defmacro update_in(path, fun) do case unnest(path, [], true, "update_in/2") do {[h | t], true} -> nest_update_in(h, t, fun) {[h | t], false} -> expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end)) quote(do: :erlang.element(2, unquote(expr))) end end @doc """ Gets a value and updates a nested data structure via the given `path`. This is similar to `get_and_update_in/3`, except the path is extracted via a macro rather than passing a list. For example: get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1}) Is equivalent to: get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1}) This also works with nested structs and the `struct.path.to.value` way to specify paths: get_and_update_in(struct.foo.bar, &{&1, &1 + 1}) Note that in order for this macro to work, the complete path must always be visible by this macro. See the "Paths" section below. ## Examples iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} iex> get_and_update_in(users["john"].age, &{&1, &1 + 1}) {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} ## Paths A path may start with a variable, local or remote call, and must be followed by one or more: * `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil, `nil` is returned * `foo.bar` - accesses a map/struct field; in case the field is not present, an error is raised Here are some valid paths: users["john"][:age] users["john"].age User.all()["john"].age all_users()["john"].age Here are some invalid ones: # Does a remote call after the initial value users["john"].do_something(arg1, arg2) # Does not access any key or field users """ defmacro get_and_update_in(path, fun) do {[h | t], _} = unnest(path, [], true, "get_and_update_in/2") nest_get_and_update_in(h, t, fun) end defp nest_update_in([], fun), do: fun defp nest_update_in(list, fun) do quote do fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end end end defp nest_update_in(h, [{:map, key} | t], fun) do quote do Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun))) end end defp nest_get_and_update_in([], fun), do: fun defp nest_get_and_update_in(list, fun) do quote do fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end end end defp nest_get_and_update_in(h, [{:access, key} | t], fun) do quote do Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) end end defp nest_get_and_update_in(h, [{:map, key} | t], fun) do quote do Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) end end defp nest_pop_in(kind, list) do quote do fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end end end defp nest_pop_in(:map, h, [{:access, key}]) do quote do case unquote(h) do nil -> {nil, nil} h -> Access.pop(h, unquote(key)) end end end defp nest_pop_in(_, _, [{:map, key}]) do raise ArgumentError, "cannot use pop_in when the last segment is a map/struct field. " <> "This would effectively remove the field #{inspect(key)} from the map/struct" end defp nest_pop_in(_, h, [{:map, key} | t]) do quote do Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t))) end end defp nest_pop_in(_, h, [{:access, key}]) do quote do case unquote(h) do nil -> :pop h -> Access.pop(h, unquote(key)) end end end defp nest_pop_in(_, h, [{:access, key} | t]) do quote do Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t))) end end defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do unnest(expr, [{:access, key} | acc], false, kind) end defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind) when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and :erlang.element(1, expr) != :__MODULE__ do unnest(expr, [{:map, key} | acc], all_map?, kind) end defp unnest(other, [], _all_map?, kind) do raise ArgumentError, "expected expression given to #{kind} to access at least one element, " <> "got: #{Macro.to_string(other)}" end defp unnest(other, acc, all_map?, kind) do case proper_start?(other) do true -> {[other | acc], all_map?} false -> raise ArgumentError, "expression given to #{kind} must start with a variable, local or remote call " <> "and be followed by an element access, got: #{Macro.to_string(other)}" end end defp proper_start?({{:., _, [expr, _]}, _, _args}) when is_atom(expr) when :erlang.element(1, expr) == :__aliases__ when :erlang.element(1, expr) == :__MODULE__, do: true defp proper_start?({atom, _, _args}) when is_atom(atom), do: true defp proper_start?(other), do: not is_tuple(other) @doc """ Converts the argument to a string according to the `String.Chars` protocol. This is the function invoked when there is string interpolation. ## Examples iex> to_string(:foo) "foo" """ defmacro to_string(term) do quote(do: :"Elixir.String.Chars".to_string(unquote(term))) end @doc """ Converts the given term to a charlist according to the `List.Chars` protocol. ## Examples iex> to_charlist(:foo) 'foo' """ defmacro to_charlist(term) do quote(do: List.Chars.to_charlist(unquote(term))) end @doc """ Returns `true` if `term` is `nil`, `false` otherwise. Allowed in guard clauses. ## Examples iex> is_nil(1) false iex> is_nil(nil) true """ @doc guard: true defmacro is_nil(term) do quote(do: unquote(term) == nil) end @doc """ A convenience macro that checks if the right side (an expression) matches the left side (a pattern). ## Examples iex> match?(1, 1) true iex> match?({1, _}, {1, 2}) true iex> map = %{a: 1, b: 2} iex> match?(%{a: _}, map) true iex> a = 1 iex> match?(^a, 1) true `match?/2` is very useful when filtering or finding a value in an enumerable: iex> list = [a: 1, b: 2, a: 3] iex> Enum.filter(list, &match?({:a, _}, &1)) [a: 1, a: 3] Guard clauses can also be given to the match: iex> list = [a: 1, b: 2, a: 3] iex> Enum.filter(list, &match?({:a, x} when x < 2, &1)) [a: 1] However, variables assigned in the match will not be available outside of the function call (unlike regular pattern matching with the `=` operator): iex> match?(_x, 1) true iex> binding() [] Furthermore, remember the pin operator matches _values_, not _patterns_: match?(%{x: 1}, %{x: 1, y: 2}) #=> true attrs = %{x: 1} match?(^attrs, %{x: 1, y: 2}) #=> false The pin operator will check if the values are equal, using `===/2`, while patterns have their own rules when matching maps, lists, and so forth. Such behaviour is not specific to `match?/2`. The following code also throws an exception: attrs = %{x: 1} ^attrs = %{x: 1, y: 2} #=> (MatchError) no match of right hand side value: %{x: 1, y: 2} """ defmacro match?(pattern, expr) do success = quote do unquote(pattern) -> true end failure = quote generated: true do _ -> false end {:case, [], [expr, [do: success ++ failure]]} end @doc """ Module attribute unary operator. Reads and writes attributes in the current module. The canonical example for attributes is annotating that a module implements an OTP behaviour, such as `GenServer`: defmodule MyServer do @behaviour GenServer # ... callbacks ... end By default Elixir supports all the module attributes supported by Erlang, but custom attributes can be used as well: defmodule MyServer do @my_data 13 IO.inspect(@my_data) #=> 13 end Unlike Erlang, such attributes are not stored in the module by default since it is common in Elixir to use custom attributes to store temporary data that will be available at compile-time. Custom attributes may be configured to behave closer to Erlang by using `Module.register_attribute/3`. > **Important:** Libraries and frameworks should consider prefixing any > module attributes that are private by underscore, such as `@_my_data` > so code completion tools do not show them on suggestions and prompts. Finally, note that attributes can also be read inside functions: defmodule MyServer do @my_data 11 def first_data, do: @my_data @my_data 13 def second_data, do: @my_data end MyServer.first_data() #=> 11 MyServer.second_data() #=> 13 It is important to note that reading an attribute takes a snapshot of its current value. In other words, the value is read at compilation time and not at runtime. Check the `Module` module for other functions to manipulate module attributes. ## Attention! Multiple references of the same attribute As mentioned above, every time you read a module attribute, a snapshot of its current value is taken. Therefore, if you are storing large values inside module attributes (for example, embedding external files in module attributes), you should avoid referencing the same attribute multiple times. For example, don't do this: @files %{ example1: File.read!("lib/example1.data"), example2: File.read!("lib/example2.data") } def example1, do: @files[:example1] def example2, do: @files[:example2] In the above, each reference to `@files` may end-up with a complete and individual copy of the whole `@files` module attribute. Instead, reference the module attribute once in a private function: @files %{ example1: File.read!("lib/example1.data"), example2: File.read!("lib/example2.data") } defp files(), do: @files def example1, do: files()[:example1] def example2, do: files()[:example2] ## Attention! Compile-time dependencies Keep in mind references to other modules, even in module attributes, generate compile-time dependencies to said modules. For example, take this common pattern: @values [:foo, :bar, :baz] def handle_arg(arg) when arg in @values do ... end While the above is fine, imagine if instead you have actual module names in the module attribute, like this: @values [Foo, Bar, Baz] def handle_arg(arg) when arg in @values do ... end The code above will define a compile-time dependency on the modules `Foo`, `Bar`, and `Baz`, in a way that, if any of them change, the current module will have to recompile. In such cases, it may be preferred to avoid the module attribute altogether: def handle_arg(arg) when arg in [Foo, Bar, Baz] do ... end """ defmacro @expr defmacro @{:__aliases__, _meta, _args} do raise ArgumentError, "module attributes set via @ cannot start with an uppercase letter" end defmacro @{name, meta, args} do assert_module_scope(__CALLER__, :@, 1) function? = __CALLER__.function != nil cond do # Check for Macro as it is compiled later than Kernel not bootstrapped?(Macro) -> nil not function? and __CALLER__.context == :match -> raise ArgumentError, """ invalid write attribute syntax. If you want to define an attribute, don't do this: @foo = :value Instead, do this: @foo :value """ # Typespecs attributes are currently special cased by the compiler is_list(args) and typespec?(name) -> case bootstrapped?(Kernel.Typespec) do false -> :ok true -> pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.deftypespec( unquote(name), unquote(Macro.escape(hd(args), unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos) ) end end true -> do_at(args, meta, name, function?, __CALLER__) end end # @attribute(value) defp do_at([arg], meta, name, function?, env) do line = case :lists.keymember(:context, 1, meta) do true -> nil false -> env.line end cond do function? -> raise ArgumentError, "cannot set attribute @#{name} inside function/macro" name == :behavior -> warn_message = "@behavior attribute is not supported, please use @behaviour instead" IO.warn(warn_message, env) :lists.member(name, [:moduledoc, :typedoc, :doc]) -> arg = {env.line, arg} quote do Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) end true -> arg = expand_attribute(name, arg, env) quote do Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) end end end # @attribute() defp do_at([], meta, name, function?, env) do IO.warn( "the @#{name}() notation (with parenthesis) is deprecated, please use @#{name} (without parenthesis) instead", Macro.Env.stacktrace(env) ) do_at(nil, meta, name, function?, env) end # @attribute defp do_at(args, _meta, name, function?, env) when is_atom(args) do line = env.line doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc]) case function? do true -> value = case Module.__get_attribute__(env.module, name, line) do {_, doc} when doc_attr? -> doc other -> other end try do :elixir_quote.escape(value, :none, false) rescue ex in [ArgumentError] -> raise ArgumentError, "cannot inject attribute @#{name} into function/macro because " <> Exception.message(ex) end false when doc_attr? -> quote do case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do {_, doc} -> doc other -> other end end false -> quote do Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) end end end # Error cases defp do_at([{call, meta, ctx_or_args}, [{:do, _} | _] = kw], _meta, name, _function?, _env) do args = case is_atom(ctx_or_args) do true -> [] false -> ctx_or_args end code = "\n@#{name} (#{Macro.to_string({call, meta, args ++ [kw]})})" raise ArgumentError, """ expected 0 or 1 argument for @#{name}, got 2. It seems you are trying to use the do-syntax with @module attributes \ but the do-block is binding to the attribute name. You probably want \ to wrap the argument value in parentheses, like this: #{String.replace(code, "\n", "\n ")} """ end defp do_at(args, _meta, name, _function?, _env) do raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}" end defp expand_attribute(:compile, arg, env) do Macro.prewalk(arg, fn # {:no_warn_undefined, alias} {elem, {:__aliases__, _, _} = alias} -> {elem, Macro.expand(alias, %{env | function: {:__info__, 1}})} # {alias, fun, arity} {:{}, meta, [{:__aliases__, _, _} = alias, fun, arity]} -> {:{}, meta, [Macro.expand(alias, %{env | function: {:__info__, 1}}), fun, arity]} node -> node end) end defp expand_attribute(_, arg, _), do: arg defp typespec?(:type), do: true defp typespec?(:typep), do: true defp typespec?(:opaque), do: true defp typespec?(:spec), do: true defp typespec?(:callback), do: true defp typespec?(:macrocallback), do: true defp typespec?(_), do: false @doc """ Returns the binding for the given context as a keyword list. In the returned result, keys are variable names and values are the corresponding variable values. If the given `context` is `nil` (by default it is), the binding for the current context is returned. ## Examples iex> x = 1 iex> binding() [x: 1] iex> x = 2 iex> binding() [x: 2] iex> binding(:foo) [] iex> var!(x, :foo) = 1 1 iex> binding(:foo) [x: 1] """ defmacro binding(context \\ nil) do in_match? = Macro.Env.in_match?(__CALLER__) bindings = for {v, c} <- Macro.Env.vars(__CALLER__), c == context do {v, wrap_binding(in_match?, {v, [generated: true], c})} end :lists.sort(bindings) end defp wrap_binding(true, var) do quote(do: ^unquote(var)) end defp wrap_binding(_, var) do var end @doc """ Provides an `if/2` macro. This macro expects the first argument to be a condition and the second argument to be a keyword list. ## One-liner examples if(foo, do: bar) In the example above, `bar` will be returned if `foo` evaluates to a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be returned. An `else` option can be given to specify the opposite: if(foo, do: bar, else: baz) ## Blocks examples It's also possible to pass a block to the `if/2` macro. The first example above would be translated to: if foo do bar end Note that `do`-`end` become delimiters. The second example would translate to: if foo do bar else baz end In order to compare more than two clauses, the `cond/1` macro has to be used. """ defmacro if(condition, clauses) do build_if(condition, clauses) end defp build_if(condition, do: do_clause) do build_if(condition, do: do_clause, else: nil) end defp build_if(condition, do: do_clause, else: else_clause) do optimize_boolean( quote do case unquote(condition) do x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(else_clause) _ -> unquote(do_clause) end end ) end defp build_if(_condition, _arguments) do raise ArgumentError, "invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted" end @doc """ Provides an `unless` macro. This macro evaluates and returns the `do` block passed in as the second argument if `condition` evaluates to a falsy value (`false` or `nil`). Otherwise, it returns the value of the `else` block if present or `nil` if not. See also `if/2`. ## Examples iex> unless(Enum.empty?([]), do: "Hello") nil iex> unless(Enum.empty?([1, 2, 3]), do: "Hello") "Hello" iex> unless Enum.sum([2, 2]) == 5 do ...> "Math still works" ...> else ...> "Math is broken" ...> end "Math still works" """ defmacro unless(condition, clauses) do build_unless(condition, clauses) end defp build_unless(condition, do: do_clause) do build_unless(condition, do: do_clause, else: nil) end defp build_unless(condition, do: do_clause, else: else_clause) do quote do if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause)) end end defp build_unless(_condition, _arguments) do raise ArgumentError, "invalid or duplicate keys for unless, " <> "only \"do\" and an optional \"else\" are permitted" end @doc """ Destructures two lists, assigning each term in the right one to the matching term in the left one. Unlike pattern matching via `=`, if the sizes of the left and right lists don't match, destructuring simply stops instead of raising an error. ## Examples iex> destructure([x, y, z], [1, 2, 3, 4, 5]) iex> {x, y, z} {1, 2, 3} In the example above, even though the right list has more entries than the left one, destructuring works fine. If the right list is smaller, the remaining elements are simply set to `nil`: iex> destructure([x, y, z], [1]) iex> {x, y, z} {1, nil, nil} The left-hand side supports any expression you would use on the left-hand side of a match: x = 1 destructure([^x, y, z], [1, 2, 3]) The example above will only work if `x` matches the first value in the right list. Otherwise, it will raise a `MatchError` (like the `=` operator would do). """ defmacro destructure(left, right) when is_list(left) do quote do unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left))) end end @doc """ Creates a range from `first` to `last`. If first is less than last, the range will be increasing from first to last. If first is equal to last, the range will contain one element, which is the number itself. If first is more than last, the range will be decreasing from first to last, albeit this behaviour is deprecated. Instead prefer to explicitly list the step with `first..last//-1`. See the `Range` module for more information. ## Examples iex> 0 in 1..3 false iex> 2 in 1..3 true iex> Enum.to_list(1..3) [1, 2, 3] """ defmacro first..last do case bootstrapped?(Macro) do true -> first = Macro.expand(first, __CALLER__) last = Macro.expand(last, __CALLER__) validate_range!(first, last) range(__CALLER__.context, first, last) false -> range(__CALLER__.context, first, last) end end defp range(_context, first, last) when is_integer(first) and is_integer(last) do # TODO: Deprecate inferring a range with a step of -1 on Elixir v1.17 step = if first <= last, do: 1, else: -1 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: step]} end defp range(nil, first, last) do quote(do: Elixir.Range.new(unquote(first), unquote(last))) end defp range(:guard, first, last) do # TODO: Deprecate me inside guard when sides are not integers on Elixir v1.17 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: nil]} end defp range(:match, first, last) do # TODO: Deprecate me inside match in all occasions (including literals) on Elixir v1.17 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} end @doc """ Creates a range from `first` to `last` with `step`. See the `Range` module for more information. ## Examples iex> 0 in 1..3//1 false iex> 2 in 1..3//1 true iex> 2 in 1..3//2 false iex> Enum.to_list(1..3//1) [1, 2, 3] iex> Enum.to_list(1..3//2) [1, 3] iex> Enum.to_list(3..1//-1) [3, 2, 1] iex> Enum.to_list(1..0//1) [] """ @doc since: "1.12.0" defmacro first..last//step do case bootstrapped?(Macro) do true -> first = Macro.expand(first, __CALLER__) last = Macro.expand(last, __CALLER__) step = Macro.expand(step, __CALLER__) validate_range!(first, last) validate_step!(step) range(__CALLER__.context, first, last, step) false -> range(__CALLER__.context, first, last, step) end end defp range(context, first, last, step) when is_integer(first) and is_integer(last) and is_integer(step) when context != nil do {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: step]} end defp range(nil, first, last, step) do quote(do: Elixir.Range.new(unquote(first), unquote(last), unquote(step))) end defp validate_range!(first, last) when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do raise ArgumentError, "ranges (first..last//step) expect both sides to be integers, " <> "got: #{Macro.to_string({:.., [], [first, last]})}" end defp validate_range!(_, _), do: :ok defp validate_step!(step) when is_float(step) or is_atom(step) or is_binary(step) or is_list(step) or step == 0 do raise ArgumentError, "ranges (first..last//step) expect the step to be a non-zero integer, " <> "got: #{Macro.to_string(step)}" end defp validate_step!(_), do: :ok @doc """ Creates the full-slice range `0..-1//1`. This macro returns a range with the following properties: * When enumerated, it is empty * When used as a `slice`, it returns the sliced element as is See `..///3` and the `Range` module for more information. ## Examples iex> Enum.to_list(..) [] iex> String.slice("Hello world!", ..) "Hello world!" """ defmacro (..) do range(__CALLER__.context, 0, -1, 1) end @doc """ Boolean "and" operator. Provides a short-circuit operator that evaluates and returns the second expression only if the first one evaluates to a truthy value (neither `false` nor `nil`). Returns the first expression otherwise. Not allowed in guard clauses. ## Examples iex> Enum.empty?([]) && Enum.empty?([]) true iex> List.first([]) && true nil iex> Enum.empty?([]) && List.first([1]) 1 iex> false && throw(:bad) false Note that, unlike `and/2`, this operator accepts any expression as the first argument, not only booleans. """ defmacro left && right do assert_no_match_or_guard_scope(__CALLER__.context, "&&") quote do case unquote(left) do x when :"Elixir.Kernel".in(x, [false, nil]) -> x _ -> unquote(right) end end end @doc """ Boolean "or" operator. Provides a short-circuit operator that evaluates and returns the second expression only if the first one does not evaluate to a truthy value (that is, it is either `nil` or `false`). Returns the first expression otherwise. Not allowed in guard clauses. ## Examples iex> Enum.empty?([1]) || Enum.empty?([1]) false iex> List.first([]) || true true iex> Enum.empty?([1]) || 1 1 iex> Enum.empty?([]) || throw(:bad) true Note that, unlike `or/2`, this operator accepts any expression as the first argument, not only booleans. """ defmacro left || right do assert_no_match_or_guard_scope(__CALLER__.context, "||") quote do case unquote(left) do x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(right) x -> x end end end @doc """ Pipe operator. This operator introduces the expression on the left-hand side as the first argument to the function call on the right-hand side. ## Examples iex> [1, [2], 3] |> List.flatten() [1, 2, 3] The example above is the same as calling `List.flatten([1, [2], 3])`. The `|>/2` operator is mostly useful when there is a desire to execute a series of operations resembling a pipeline: iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end) [2, 4, 6] In the example above, the list `[1, [2], 3]` is passed as the first argument to the `List.flatten/1` function, then the flattened list is passed as the first argument to the `Enum.map/2` function which doubles each element of the list. In other words, the expression above simply translates to: Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end) ## Pitfalls There are two common pitfalls when using the pipe operator. The first one is related to operator precedence. For example, the following expression: String.graphemes "Hello" |> Enum.reverse Translates to: String.graphemes("Hello" |> Enum.reverse()) which results in an error as the `Enumerable` protocol is not defined for binaries. Adding explicit parentheses resolves the ambiguity: String.graphemes("Hello") |> Enum.reverse() Or, even better: "Hello" |> String.graphemes() |> Enum.reverse() The second limitation is that Elixir always pipes to a function call. Therefore, to pipe into an anonymous function, you need to invoke it: some_fun = &Regex.replace(~r/l/, &1, "L") "Hello" |> some_fun.() Alternatively, you can use `then/2` for the same effect: some_fun = &Regex.replace(~r/l/, &1, "L") "Hello" |> then(some_fun) `then/2` is most commonly used when you want to pipe to a function but the value is expected outside of the first argument, such as above. By replacing `some_fun` by its value, we get: "Hello" |> then(&Regex.replace(~r/l/, &1, "L")) """ defmacro left |> right do [{h, _} | t] = Macro.unpipe({:|>, [], [left, right]}) fun = fn {x, pos}, acc -> Macro.pipe(acc, x, pos) end :lists.foldl(fun, h, t) end @doc """ Returns `true` if `module` is loaded and contains a public `function` with the given `arity`, otherwise `false`. Note that this function does not load the module in case it is not loaded. Check `Code.ensure_loaded/1` for more information. Inlined by the compiler. ## Examples iex> function_exported?(Enum, :map, 2) true iex> function_exported?(Enum, :map, 10) false iex> function_exported?(List, :to_string, 1) true """ @spec function_exported?(module, atom, arity) :: boolean def function_exported?(module, function, arity) do :erlang.function_exported(module, function, arity) end @doc """ Returns `true` if `module` is loaded and contains a public `macro` with the given `arity`, otherwise `false`. Note that this function does not load the module in case it is not loaded. Check `Code.ensure_loaded/1` for more information. If `module` is an Erlang module (as opposed to an Elixir module), this function always returns `false`. ## Examples iex> macro_exported?(Kernel, :use, 2) true iex> macro_exported?(:erlang, :abs, 1) false """ @spec macro_exported?(module, atom, arity) :: boolean def macro_exported?(module, macro, arity) when is_atom(module) and is_atom(macro) and is_integer(arity) and (arity >= 0 and arity <= 255) do function_exported?(module, :__info__, 1) and :lists.member({macro, arity}, module.__info__(:macros)) end @doc """ Power operator. It expects two numbers are input. If the left-hand side is an integer and the right-hand side is more than or equal to 0, then the result is integer. Otherwise it returns a float. ## Examples iex> 2 ** 2 4 iex> 2 ** -4 0.0625 iex> 2.0 ** 2 4.0 iex> 2 ** 2.0 4.0 """ @doc since: "1.13.0" @spec integer ** non_neg_integer :: integer @spec integer ** neg_integer :: float @spec float ** float :: float def base ** exponent when is_integer(base) and is_integer(exponent) and exponent >= 0 do integer_pow(base, 1, exponent) end def base ** exponent when is_number(base) and is_number(exponent) do :math.pow(base, exponent) end # https://en.wikipedia.org/wiki/Exponentiation_by_squaring defp integer_pow(_, _, 0), do: 1 defp integer_pow(b, a, 1), do: b * a defp integer_pow(b, a, e) when :erlang.band(e, 1) == 0, do: integer_pow(b * b, a, :erlang.bsr(e, 1)) defp integer_pow(b, a, e), do: integer_pow(b * b, a * b, :erlang.bsr(e, 1)) @doc """ Membership operator. Checks if the element on the left-hand side is a member of the collection on the right-hand side. ## Examples iex> x = 1 iex> x in [1, 2, 3] true This operator (which is a macro) simply translates to a call to `Enum.member?/2`. The example above would translate to: Enum.member?([1, 2, 3], x) Elixir also supports `left not in right`, which evaluates to `not(left in right)`: iex> x = 1 iex> x not in [1, 2, 3] false ## Guards The `in/2` operator (as well as `not in`) can be used in guard clauses as long as the right-hand side is a range or a list. If the right-hand side is a list, Elixir will expand the operator to a valid guard expression which needs to check each value. For example: when x in [1, 2, 3] translates to: when x === 1 or x === 2 or x === 3 However, this construct will be inneficient for large lists. In such cases, it is best to stop using guards and use a more appropriate data structure, such as `MapSet`. If the right-hand side is a range, a more efficient comparison check will be done. For example: when x in 1..1000 translates roughly to: when x >= 1 and x <= 1000 ### AST considerations `left not in right` is parsed by the compiler into the AST: {:not, _, [{:in, _, [left, right]}]} This is the same AST as `not(left in right)`. Additionally, `Macro.to_string/2` and `Code.format_string!/2` will translate all occurrences of this AST to `left not in right`. """ @doc guard: true defmacro left in right do in_body? = __CALLER__.context == nil expand = case bootstrapped?(Macro) do true -> &Macro.expand(&1, __CALLER__) false -> & &1 end case expand.(right) do [] when not in_body? -> false [] -> quote do _ = unquote(left) false end [head | tail] = list -> # We only expand lists in the body if they are relatively # short and it is made only of literal expressions. case not in_body? or small_literal_list?(right) do true -> in_var(in_body?, left, &in_list(&1, head, tail, expand, list, in_body?)) false -> quote(do: :lists.member(unquote(left), unquote(right))) end {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last, step: step]} -> in_var(in_body?, left, &in_range(&1, expand.(first), expand.(last), expand.(step))) right when in_body? -> quote(do: Elixir.Enum.member?(unquote(right), unquote(left))) %{__struct__: Elixir.Range, first: _, last: _, step: _} -> raise ArgumentError, "non-literal range in guard should be escaped with Macro.escape/2" right -> raise_on_invalid_args_in_2(right) end end defp raise_on_invalid_args_in_2(right) do raise ArgumentError, << "invalid right argument for operator \"in\", it expects a compile-time proper list ", "or compile-time range on the right side when used in guard expressions, got: ", Macro.to_string(right)::binary >> end defp in_var(false, ast, fun), do: fun.(ast) defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context), do: fun.(var) defp in_var(true, ast, fun) do quote do var = unquote(ast) unquote(fun.(quote(do: var))) end end defp small_literal_list?(list) when is_list(list) and length(list) <= 32 do :lists.all(fn x -> is_binary(x) or is_atom(x) or is_number(x) end, list) end defp small_literal_list?(_list), do: false defp in_range(left, first, last, nil) do # TODO: nil steps are only supported due to x..y in guards. Remove me on Elixir 2.0. quote do :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and :erlang.is_integer(unquote(last)) and ((:erlang."=<"(unquote(first), unquote(last)) and unquote(increasing_compare(left, first, last))) or (:erlang.<(unquote(last), unquote(first)) and unquote(decreasing_compare(left, first, last)))) end end defp in_range(left, first, last, step) when is_integer(step) do in_range_literal(left, first, last, step) end defp in_range(left, first, last, step) do quoted = quote do :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and :erlang.is_integer(unquote(last)) and ((:erlang.>(unquote(step), 0) and unquote(increasing_compare(left, first, last))) or (:erlang.<(unquote(step), 0) and unquote(decreasing_compare(left, first, last)))) end in_range_step(quoted, left, first, step) end defp in_range_literal(left, first, first, _step) when is_integer(first) do quote do: :erlang."=:="(unquote(left), unquote(first)) end defp in_range_literal(left, first, last, step) when step > 0 do quoted = quote do :erlang.andalso( :erlang.is_integer(unquote(left)), unquote(increasing_compare(left, first, last)) ) end in_range_step(quoted, left, first, step) end defp in_range_literal(left, first, last, step) when step < 0 do quoted = quote do :erlang.andalso( :erlang.is_integer(unquote(left)), unquote(decreasing_compare(left, first, last)) ) end in_range_step(quoted, left, first, step) end defp in_range_step(quoted, _left, _first, step) when step == 1 or step == -1 do quoted end defp in_range_step(quoted, left, first, step) do quote do :erlang.andalso( unquote(quoted), :erlang."=:="(:erlang.rem(unquote(left) - unquote(first), unquote(step)), 0) ) end end defp in_list(left, head, tail, expand, right, in_body?) do [head | tail] = :lists.map(&comp(left, &1, expand, right, in_body?), [head | tail]) :lists.foldl(&quote(do: :erlang.orelse(unquote(&2), unquote(&1))), head, tail) end defp comp(left, {:|, _, [head, tail]}, expand, right, in_body?) do case expand.(tail) do [] -> quote(do: :erlang."=:="(unquote(left), unquote(head))) [tail_head | tail] -> quote do :erlang.orelse( :erlang."=:="(unquote(left), unquote(head)), unquote(in_list(left, tail_head, tail, expand, right, in_body?)) ) end tail when in_body? -> quote do :erlang.orelse( :erlang."=:="(unquote(left), unquote(head)), :lists.member(unquote(left), unquote(tail)) ) end _ -> raise_on_invalid_args_in_2(right) end end defp comp(left, right, _expand, _right, _in_body?) do quote(do: :erlang."=:="(unquote(left), unquote(right))) end defp increasing_compare(var, first, last) do quote do :erlang.andalso( :erlang.>=(unquote(var), unquote(first)), :erlang."=<"(unquote(var), unquote(last)) ) end end defp decreasing_compare(var, first, last) do quote do :erlang.andalso( :erlang."=<"(unquote(var), unquote(first)), :erlang.>=(unquote(var), unquote(last)) ) end end @doc """ Marks that the given variable should not be hygienized. This macro expects a variable and it is typically invoked inside `Kernel.SpecialForms.quote/2` to mark that a variable should not be hygienized. See `Kernel.SpecialForms.quote/2` for more information. ## Examples iex> Kernel.var!(example) = 1 1 iex> Kernel.var!(example) 1 """ defmacro var!(var, context \\ nil) defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do # Remove counter and force them to be vars meta = :lists.keydelete(:counter, 1, meta) meta = :lists.keystore(:if_undefined, 1, meta, {:if_undefined, :raise}) case Macro.expand(context, __CALLER__) do context when is_atom(context) -> {name, meta, context} other -> raise ArgumentError, "expected var! context to expand to an atom, got: #{Macro.to_string(other)}" end end defmacro var!(other, _context) do raise ArgumentError, "expected a variable to be given to var!, got: #{Macro.to_string(other)}" end @doc """ When used inside quoting, marks that the given alias should not be hygienized. This means the alias will be expanded when the macro is expanded. Check `Kernel.SpecialForms.quote/2` for more information. """ defmacro alias!(alias) when is_atom(alias) do alias end defmacro alias!({:__aliases__, meta, args}) do # Simply remove the alias metadata from the node # so it does not affect expansion. {:__aliases__, :lists.keydelete(:alias, 1, meta), args} end @doc """ Returns a binary starting at the offset `start` and of the given `size`. This is similar to `binary_part/3` except that if `start + size` is greater than the binary size, it automatically clips it to the binary size instead of raising. Opposite to `binary_part/3`, this function is not allowed in guards. This function works with bytes. For a slicing operation that considers characters, see `String.slice/3`. ## Examples iex> binary_slice("elixir", 0, 6) "elixir" iex> binary_slice("elixir", 0, 5) "elixi" iex> binary_slice("elixir", 1, 4) "lixi" iex> binary_slice("elixir", 0, 10) "elixir" If `start` is negative, it is normalized against the binary size and clamped to 0: iex> binary_slice("elixir", -3, 10) "xir" iex> binary_slice("elixir", -10, 10) "elixir" If the `size` is zero, an empty binary is returned: iex> binary_slice("elixir", 1, 0) "" If `start` is greater than or equal to the binary size, an empty binary is returned: iex> binary_slice("elixir", 10, 10) "" """ @doc since: "1.14.0" def binary_slice(binary, start, size) when is_binary(binary) and is_integer(start) and is_integer(size) and size >= 0 do total = byte_size(binary) start = if start < 0, do: max(total + start, 0), else: start case start < total do true -> :erlang.binary_part(binary, start, min(size, total - start)) false -> "" end end @doc """ Returns a binary from the offset given by the start of the range to the offset given by the end of the range. If the start or end of the range are negative, they are converted into positive indices based on the binary size. For example, `-1` means the last byte of the binary. This is similar to `binary_part/3` except that it works with ranges and it is not allowed in guards. This function works with bytes. For a slicing operation that considers characters, see `String.slice/2`. ## Examples iex> binary_slice("elixir", 0..5) "elixir" iex> binary_slice("elixir", 1..3) "lix" iex> binary_slice("elixir", 1..10) "lixir" iex> binary_slice("elixir", -4..-1) "ixir" iex> binary_slice("elixir", -4..6) "ixir" iex> binary_slice("elixir", -10..10) "elixir" For ranges where `start > stop`, you need to explicitly mark them as increasing: iex> binary_slice("elixir", 2..-1//1) "ixir" iex> binary_slice("elixir", 1..-2//1) "lixi" You can use `../0` as a shortcut for `0..-1//1`, which returns the whole binary as is: iex> binary_slice("elixir", ..) "elixir" The step can be any positive number. For example, to get every 2 characters of the binary: iex> binary_slice("elixir", 0..-1//2) "eii" If the first position is after the string ends or after the last position of the range, it returns an empty string: iex> binary_slice("elixir", 10..3//1) "" iex> binary_slice("elixir", -10..-7) "" iex> binary_slice("a", 1..1500) "" """ @doc since: "1.14.0" def binary_slice(binary, first..last//step) when is_binary(binary) and step > 0 do total = byte_size(binary) first = case first < 0 do true -> max(first + total, 0) false -> first end last = case last < 0 do true -> last + total false -> last end case first < total do true -> part = binary_part(binary, first, min(total - first, last - first + 1)) case step do 1 -> part _ -> for <<byte, _::size(step - 1)-bytes <- part>>, into: "", do: <<byte>> end false -> "" end end def binary_slice(binary, _.._//_ = range) when is_binary(binary) do raise ArgumentError, "binary_slice/2 does not accept ranges with negative steps, got: #{inspect(range)}" end ## Definitions implemented in Elixir @doc ~S""" Defines a module given by name with the given contents. This macro defines a module with the given `alias` as its name and with the given contents. It returns a tuple with four elements: * `:module` * the module name * the binary contents of the module * the result of evaluating the contents block ## Examples defmodule Number do def one, do: 1 def two, do: 2 end #=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}} Number.one() #=> 1 Number.two() #=> 2 ## Nesting Nesting a module inside another module affects the name of the nested module: defmodule Foo do defmodule Bar do end end In the example above, two modules - `Foo` and `Foo.Bar` - are created. When nesting, Elixir automatically creates an alias to the inner module, allowing the second module `Foo.Bar` to be accessed as `Bar` in the same lexical scope where it's defined (the `Foo` module). This only happens if the nested module is defined via an alias. If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or an alias has to be explicitly set in the `Foo` module with the help of `Kernel.SpecialForms.alias/2`. defmodule Foo.Bar do # code end defmodule Foo do alias Foo.Bar # code here can refer to "Foo.Bar" as just "Bar" end ## Dynamic names Elixir module names can be dynamically generated. This is very useful when working with macros. For instance, one could write: defmodule String.to_atom("Foo#{1}") do # contents ... end Elixir will accept any module name as long as the expression passed as the first argument to `defmodule/2` evaluates to an atom. Note that, when a dynamic name is used, Elixir won't nest the name under the current module nor automatically set up an alias. ## Reserved module names If you attempt to define a module that already exists, you will get a warning saying that a module has been redefined. There are some modules that Elixir does not currently implement but it may be implement in the future. Those modules are reserved and defining them will result in a compilation error: defmodule Any do # code end ** (CompileError) iex:1: module Any is reserved and cannot be defined Elixir reserves the following module names: `Elixir`, `Any`, `BitString`, `PID`, and `Reference`. """ defmacro defmodule(alias, do_block) defmacro defmodule(alias, do: block) do env = __CALLER__ expanded = expand_module_alias(alias, env) {expanded, with_alias} = case is_atom(expanded) do true -> # Expand the module considering the current environment/nesting {full, old, new} = alias_defmodule(alias, expanded, env) meta = [defined: full, context: env.module] ++ alias_meta(alias) {full, {:alias, meta, [old, [as: new, warn: false]]}} false -> {expanded, nil} end # We do this so that the block is not tail-call optimized and stacktraces # are not messed up. Basically, we just insert something between the return # value of the block and what is returned by defmodule. Using just ":ok" or # similar doesn't work because it's likely optimized away by the compiler. block = quote do result = unquote(block) :elixir_utils.noop() result end escaped = case env do %{function: nil, lexical_tracker: pid} when is_pid(pid) -> integer = Kernel.LexicalTracker.write_cache(pid, block) quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer))) %{} -> :elixir_quote.escape(block, :none, false) end module_vars = :lists.map(&module_var/1, :maps.keys(env.versioned_vars)) quote do unquote(with_alias) :elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__) end end defp alias_meta({:__aliases__, meta, _}), do: meta defp alias_meta(_), do: [] # We don't want to trace :alias_reference since we are defining the alias defp expand_module_alias({:__aliases__, _, _} = original, env) do case :elixir_aliases.expand_or_concat(original, env) do receiver when is_atom(receiver) -> receiver aliases -> aliases = :lists.map(&Macro.expand(&1, env), aliases) case :lists.all(&is_atom/1, aliases) do true -> :elixir_aliases.concat(aliases) false -> original end end end defp expand_module_alias(other, env), do: Macro.expand(other, env) # defmodule Elixir.Alias defp alias_defmodule({:__aliases__, _, [:"Elixir", _ | _]}, module, _env), do: {module, module, nil} # defmodule Alias in root defp alias_defmodule({:__aliases__, _, _}, module, %{module: nil}), do: {module, module, nil} # defmodule Alias nested defp alias_defmodule({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do module = :elixir_aliases.concat([env.module, h]) alias = String.to_atom("Elixir." <> Atom.to_string(h)) case t do [] -> {module, module, alias} _ -> {String.to_atom(Enum.join([module | t], ".")), module, alias} end end # defmodule _ defp alias_defmodule(_raw, module, _env) do {module, module, nil} end defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind} defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil} @doc ~S""" Defines a public function with the given name and body. ## Examples defmodule Foo do def bar, do: :baz end Foo.bar() #=> :baz A function that expects arguments can be defined as follows: defmodule Foo do def sum(a, b) do a + b end end In the example above, a `sum/2` function is defined; this function receives two arguments and returns their sum. ## Default arguments `\\` is used to specify a default value for a parameter of a function. For example: defmodule MyMath do def multiply_by(number, factor \\ 2) do number * factor end end MyMath.multiply_by(4, 3) #=> 12 MyMath.multiply_by(4) #=> 8 The compiler translates this into multiple functions with different arities, here `MyMath.multiply_by/1` and `MyMath.multiply_by/2`, that represent cases when arguments for parameters with default values are passed or not passed. When defining a function with default arguments as well as multiple explicitly declared clauses, you must write a function head that declares the defaults. For example: defmodule MyString do def join(string1, string2 \\ nil, separator \\ " ") def join(string1, nil, _separator) do string1 end def join(string1, string2, separator) do string1 <> separator <> string2 end end Note that `\\` can't be used with anonymous functions because they can only have a sole arity. ### Keyword lists with default arguments Functions containing many arguments can benefit from using `Keyword` lists to group and pass attributes as a single value. defmodule MyConfiguration do @default_opts [storage: "local"] def configure(resource, opts \\ []) do opts = Keyword.merge(@default_opts, opts) storage = opts[:storage] # ... end end The difference between using `Map` and `Keyword` to store many arguments is `Keyword`'s keys: * must be atoms * can be given more than once * ordered, as specified by the developer ## Function and variable names Function and variable names have the following syntax: A _lowercase ASCII letter_ or an _underscore_, followed by any number of _lowercase or uppercase ASCII letters_, _numbers_, or _underscores_. Optionally they can end in either an _exclamation mark_ or a _question mark_. For variables, any identifier starting with an underscore should indicate an unused variable. For example: def foo(bar) do [] end #=> warning: variable bar is unused def foo(_bar) do [] end #=> no warning def foo(_bar) do _bar end #=> warning: the underscored variable "_bar" is used after being set ## `rescue`/`catch`/`after`/`else` Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try/1` does (known as "implicit try"). For example, the following two functions are equivalent: def convert(number) do try do String.to_integer(number) rescue e in ArgumentError -> {:error, e.message} end end def convert(number) do String.to_integer(number) rescue e in ArgumentError -> {:error, e.message} end """ defmacro def(call, expr \\ nil) do define(:def, call, expr, __CALLER__) end @doc """ Defines a private function with the given name and body. Private functions are only accessible from within the module in which they are defined. Trying to access a private function from outside the module it's defined in results in an `UndefinedFunctionError` exception. Check `def/2` for more information. ## Examples defmodule Foo do def bar do sum(1, 2) end defp sum(a, b), do: a + b end Foo.bar() #=> 3 Foo.sum(1, 2) ** (UndefinedFunctionError) undefined function Foo.sum/2 """ defmacro defp(call, expr \\ nil) do define(:defp, call, expr, __CALLER__) end @doc """ Defines a public macro with the given name and body. Macros must be defined before its usage. Check `def/2` for rules on naming and default arguments. ## Examples defmodule MyLogic do defmacro unless(expr, opts) do quote do if !unquote(expr), unquote(opts) end end end require MyLogic MyLogic.unless false do IO.puts("It works") end """ defmacro defmacro(call, expr \\ nil) do define(:defmacro, call, expr, __CALLER__) end @doc """ Defines a private macro with the given name and body. Private macros are only accessible from the same module in which they are defined. Private macros must be defined before its usage. Check `defmacro/2` for more information, and check `def/2` for rules on naming and default arguments. """ defmacro defmacrop(call, expr \\ nil) do define(:defmacrop, call, expr, __CALLER__) end defp define(kind, call, expr, env) do module = assert_module_scope(env, kind, 2) assert_no_function_scope(env, kind, 2) unquoted_call = :elixir_quote.has_unquotes(call) unquoted_expr = :elixir_quote.has_unquotes(expr) escaped_call = :elixir_quote.escape(call, :none, true) escaped_expr = case unquoted_expr do true -> :elixir_quote.escape(expr, :none, true) false -> key = :erlang.unique_integer() :elixir_module.write_cache(module, key, expr) quote(do: :elixir_module.read_cache(unquote(module), unquote(key))) end # Do not check clauses if any expression was unquoted check_clauses = not (unquoted_expr or unquoted_call) pos = :elixir_locals.cache_env(env) quote do :elixir_def.store_definition( unquote(kind), unquote(check_clauses), unquote(escaped_call), unquote(escaped_expr), unquote(pos) ) end end @doc """ Defines a struct. A struct is a tagged map that allows developers to provide default values for keys, tags to be used in polymorphic dispatches and compile time assertions. For more information about structs, please check `Kernel.SpecialForms.%/2`. It is only possible to define a struct per module, as the struct it tied to the module itself. Calling `defstruct/1` also defines a `__struct__/0` function that returns the struct itself. ## Examples defmodule User do defstruct name: nil, age: nil end Struct fields are evaluated at compile-time, which allows them to be dynamic. In the example below, `10 + 11` is evaluated at compile-time and the age field is stored with value `21`: defmodule User do defstruct name: nil, age: 10 + 11 end The `fields` argument is usually a keyword list with field names as atom keys and default values as corresponding values. `defstruct/1` also supports a list of atoms as its argument: in that case, the atoms in the list will be used as the struct's field names and they will all default to `nil`. defmodule Post do defstruct [:title, :content, :author] end ## Deriving Although structs are maps, by default structs do not implement any of the protocols implemented for maps. For example, attempting to use a protocol with the `User` struct leads to an error: john = %User{name: "John"} MyProtocol.call(john) ** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...} `defstruct/1`, however, allows protocol implementations to be *derived*. This can be done by defining a `@derive` attribute as a list before invoking `defstruct/1`: defmodule User do @derive [MyProtocol] defstruct name: nil, age: 10 + 11 end MyProtocol.call(john) # it works! For each protocol in the `@derive` list, Elixir will assert the protocol has been implemented for `Any`. If the `Any` implementation defines a `__deriving__/3` callback, the callback will be invoked and it should define the implementation module. Otherwise an implementation that simply points to the `Any` implementation is automatically derived. For more information on the `__deriving__/3` callback, see `Protocol.derive/3`. ## Enforcing keys When building a struct, Elixir will automatically guarantee all keys belongs to the struct: %User{name: "john", unknown: :key} ** (KeyError) key :unknown not found in: %User{age: 21, name: nil} Elixir also allows developers to enforce certain keys must always be given when building the struct: defmodule User do @enforce_keys [:name] defstruct name: nil, age: 10 + 11 end Now trying to build a struct without the name key will fail: %User{age: 21} ** (ArgumentError) the following keys must also be given when building struct User: [:name] Keep in mind `@enforce_keys` is a simple compile-time guarantee to aid developers when building structs. It is not enforced on updates and it does not provide any sort of value-validation. ## Types It is recommended to define types for structs. By convention such type is called `t`. To define a struct inside a type, the struct literal syntax is used: defmodule User do defstruct name: "John", age: 25 @type t :: %__MODULE__{name: String.t(), age: non_neg_integer} end It is recommended to only use the struct syntax when defining the struct's type. When referring to another struct it's better to use `User.t()` instead of `%User{}`. The types of the struct fields that are not included in `%User{}` default to `term()` (see `t:term/0`). Structs whose internal structure is private to the local module (pattern matching them or directly accessing their fields should not be allowed) should use the `@opaque` attribute. Structs whose internal structure is public should use `@type`. """ defmacro defstruct(fields) do quote bind_quoted: [fields: fields, bootstrapped?: bootstrapped?(Enum)] do {struct, derive, body} = Kernel.Utils.defstruct(__MODULE__, fields, bootstrapped?) case derive do [] -> :ok _ -> Protocol.__derive__(derive, __MODULE__, __ENV__) end def __struct__(), do: @__struct__ def __struct__(var!(kv)), do: unquote(body) Kernel.Utils.announce_struct(__MODULE__) struct end end @doc ~S""" Defines an exception. Exceptions are structs backed by a module that implements the `Exception` behaviour. The `Exception` behaviour requires two functions to be implemented: * [`exception/1`](`c:Exception.exception/1`) - receives the arguments given to `raise/2` and returns the exception struct. The default implementation accepts either a set of keyword arguments that is merged into the struct or a string to be used as the exception's message. * [`message/1`](`c:Exception.message/1`) - receives the exception struct and must return its message. Most commonly exceptions have a message field which by default is accessed by this function. However, if an exception does not have a message field, this function must be explicitly implemented. Since exceptions are structs, the API supported by `defstruct/1` is also available in `defexception/1`. ## Raising exceptions The most common way to raise an exception is via `raise/2`: defmodule MyAppError do defexception [:message] end value = [:hello] raise MyAppError, message: "did not get what was expected, got: #{inspect(value)}" In many cases it is more convenient to pass the expected value to `raise/2` and generate the message in the `c:Exception.exception/1` callback: defmodule MyAppError do defexception [:message] @impl true def exception(value) do msg = "did not get what was expected, got: #{inspect(value)}" %MyAppError{message: msg} end end raise MyAppError, value The example above shows the preferred strategy for customizing exception messages. """ defmacro defexception(fields) do quote bind_quoted: [fields: fields] do @behaviour Exception struct = defstruct([__exception__: true] ++ fields) if Map.has_key?(struct, :message) do @impl true def message(exception) do exception.message end defoverridable message: 1 @impl true def exception(msg) when Kernel.is_binary(msg) do exception(message: msg) end end # Calls to Kernel functions must be fully-qualified to ensure # reproducible builds; otherwise, this macro will generate ASTs # with different metadata (:import, :context) depending on if # it is the bootstrapped version or not. # TODO: Change the implementation on v2.0 to simply call Kernel.struct!/2 @impl true def exception(args) when Kernel.is_list(args) do struct = __struct__() {valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end) case invalid do [] -> :ok _ -> IO.warn( "the following fields are unknown when raising " <> "#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. " <> "Please make sure to only give known fields when raising " <> "or redefine #{Kernel.inspect(__MODULE__)}.exception/1 to " <> "discard unknown fields. Future Elixir versions will raise on " <> "unknown fields given to raise/2" ) end Kernel.struct!(struct, valid) end defoverridable exception: 1 end end @doc """ Defines a protocol. See the `Protocol` module for more information. """ defmacro defprotocol(name, do_block) defmacro defprotocol(name, do: block) do Protocol.__protocol__(name, do: block) end @doc """ Defines an implementation for the given protocol. See the `Protocol` module for more information. """ defmacro defimpl(name, opts, do_block \\ []) do merged = Keyword.merge(opts, do_block) merged = Keyword.put_new(merged, :for, __CALLER__.module) if Keyword.fetch!(merged, :for) == nil do raise ArgumentError, "defimpl/3 expects a :for option when declared outside a module" end Protocol.__impl__(name, merged) end @doc """ Makes the given definitions in the current module overridable. If the user defines a new function or macro with the same name and arity, then the overridable ones are discarded. Otherwise, the original definitions are used. It is possible for the overridden definition to have a different visibility than the original: a public function can be overridden by a private function and vice-versa. Macros cannot be overridden as functions and vice-versa. ## Example defmodule DefaultMod do defmacro __using__(_opts) do quote do def test(x, y) do x + y end defoverridable test: 2 end end end defmodule ChildMod do use DefaultMod def test(x, y) do x * y + super(x, y) end end As seen as in the example above, `super` can be used to call the default implementation. > Note: use `defoverridable` with care. If you need to define multiple modules > with the same behaviour, it may be best to move the default implementation > to the caller, and check if a callback exists via `Code.ensure_loaded?/1` and > `function_exported?/3`. > > For example, in the example above, imagine there is a module that calls the > `test/2` function. This module could be defined as such: > > defmodule CallsTest do > def receives_module_and_calls_test(module, x, y) do > if Code.ensure_loaded?(module) and function_exported?(module, :test, 2) do > module.test(x, y) > else > x + y > end > end > end ## Example with behaviour You can also pass a behaviour to `defoverridable` and it will mark all of the callbacks in the behaviour as overridable: defmodule Behaviour do @callback test(number(), number()) :: number() end defmodule DefaultMod do defmacro __using__(_opts) do quote do @behaviour Behaviour def test(x, y) do x + y end defoverridable Behaviour end end end defmodule ChildMod do use DefaultMod def test(x, y) do x * y + super(x, y) end end """ defmacro defoverridable(keywords_or_behaviour) do quote do Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour)) end end @doc """ Generates a macro suitable for use in guard expressions. It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a macro that can be used both inside or outside guards. Note the convention in Elixir is to name functions/macros allowed in guards with the `is_` prefix, such as `is_list/1`. If, however, the function/macro returns a boolean and is not allowed in guards, it should have no prefix and end with a question mark, such as `Keyword.keyword?/1`. ## Example defmodule Integer.Guards do defguard is_even(value) when is_integer(value) and rem(value, 2) == 0 end defmodule Collatz do @moduledoc "Tools for working with the Collatz sequence." import Integer.Guards @doc "Determines the number of steps `n` takes to reach `1`." # If this function never converges, please let me know what `n` you used. def converge(n) when n > 0, do: step(n, 0) defp step(1, step_count) do step_count end defp step(n, step_count) when is_even(n) do step(div(n, 2), step_count + 1) end defp step(n, step_count) do step(3 * n + 1, step_count + 1) end end """ @doc since: "1.6.0" @spec defguard(Macro.t()) :: Macro.t() defmacro defguard(guard) do define_guard(:defmacro, guard, __CALLER__) end @doc """ Generates a private macro suitable for use in guard expressions. It raises at compile time if the definition uses expressions that aren't allowed in guards, and otherwise creates a private macro that can be used both inside or outside guards in the current module. Similar to `defmacrop/2`, `defguardp/1` must be defined before its use in the current module. """ @doc since: "1.6.0" @spec defguardp(Macro.t()) :: Macro.t() defmacro defguardp(guard) do define_guard(:defmacrop, guard, __CALLER__) end defp define_guard(kind, guard, env) do case :elixir_utils.extract_guards(guard) do {call, [_, _ | _]} -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}, " <> "only a single when clause is allowed" {call, impls} -> case Macro.decompose_call(call) do {_name, args} -> validate_variable_only_args!(call, args) macro_definition = case impls do [] -> define(kind, call, nil, env) [guard] -> quoted = quote do require Kernel.Utils Kernel.Utils.defguard(unquote(args), unquote(guard)) end define(kind, call, [do: quoted], env) end quote do @doc guard: true unquote(macro_definition) end _invalid_definition -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" end end end defp validate_variable_only_args!(call, args) do Enum.each(args, fn {ref, _meta, context} when is_atom(ref) and is_atom(context) -> :ok {:\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) -> :ok _match -> raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" end) end @doc """ Uses the given module in the current context. When calling: use MyModule, some: :options Elixir will invoke `MyModule.__using__/1` passing the second argument of `use` as its argument. Since `__using__/1` is typically a macro, all the usual macro rules apply, and its return value should be quoted code that is then inserted where `use/2` is called. > Note: `use MyModule` works as a code injection point in the caller. > Given the caller of `use MyModule` has little control over how the > code is injected, `use/2` should be used with care. If you can, > avoid use in favor of `import/2` or `alias/2` whenever possible. ## Examples For example, to write test cases using the `ExUnit` framework provided with Elixir, a developer should `use` the `ExUnit.Case` module: defmodule AssertionTest do use ExUnit.Case, async: true test "always pass" do assert true end end In this example, Elixir will call the `__using__/1` macro in the `ExUnit.Case` module with the keyword list `[async: true]` as its argument. In other words, `use/2` translates to: defmodule AssertionTest do require ExUnit.Case ExUnit.Case.__using__(async: true) test "always pass" do assert true end end where `ExUnit.Case` defines the `__using__/1` macro: defmodule ExUnit.Case do defmacro __using__(opts) do # do something with opts quote do # return some code to inject in the caller end end end ## Best practices `__using__/1` is typically used when there is a need to set some state (via module attributes) or callbacks (like `@before_compile`, see the documentation for `Module` for more information) into the caller. `__using__/1` may also be used to alias, require, or import functionality from different modules: defmodule MyModule do defmacro __using__(_opts) do quote do import MyModule.Foo import MyModule.Bar import MyModule.Baz alias MyModule.Repo end end end However, do not provide `__using__/1` if all it does is to import, alias or require the module itself. For example, avoid this: defmodule MyModule do defmacro __using__(_opts) do quote do import MyModule end end end In such cases, developers should instead import or alias the module directly, so that they can customize those as they wish, without the indirection behind `use/2`. Finally, developers should also avoid defining functions inside the `__using__/1` callback, unless those functions are the default implementation of a previously defined `@callback` or are functions meant to be overridden (see `defoverridable/1`). Even in these cases, defining functions should be seen as a "last resort". """ defmacro use(module, opts \\ []) do calls = Enum.map(expand_aliases(module, __CALLER__), fn expanded when is_atom(expanded) -> quote do require unquote(expanded) unquote(expanded).__using__(unquote(opts)) end _otherwise -> raise ArgumentError, "invalid arguments for use, " <> "expected a compile time atom or alias, got: #{Macro.to_string(module)}" end) quote(do: (unquote_splicing(calls))) end defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do base = Macro.expand(base, env) Enum.map(refs, fn {:__aliases__, _, ref} -> Module.concat([base | ref]) ref when is_atom(ref) -> Module.concat(base, ref) other -> other end) end defp expand_aliases(module, env) do [Macro.expand(module, env)] end @doc """ Defines a function that delegates to another module. Functions defined with `defdelegate/2` are public and can be invoked from outside the module they're defined in, as if they were defined using `def/2`. Therefore, `defdelegate/2` is about extending the current module's public API. If what you want is to invoke a function defined in another module without using its full module name, then use `alias/2` to shorten the module name or use `import/2` to be able to invoke the function without the module name altogether. Delegation only works with functions; delegating macros is not supported. Check `def/2` for rules on naming and default arguments. ## Options * `:to` - the module to dispatch to. * `:as` - the function to call on the target given in `:to`. This parameter is optional and defaults to the name being delegated (`funs`). ## Examples defmodule MyList do defdelegate reverse(list), to: Enum defdelegate other_reverse(list), to: Enum, as: :reverse end MyList.reverse([1, 2, 3]) #=> [3, 2, 1] MyList.other_reverse([1, 2, 3]) #=> [3, 2, 1] """ defmacro defdelegate(funs, opts) do funs = Macro.escape(funs, unquote: true) # don't add compile-time dependency on :to opts = with true <- is_list(opts), {:ok, target} <- Keyword.fetch(opts, :to), {:__aliases__, _, _} <- target do target = Macro.expand(target, %{__CALLER__ | function: {:__info__, 1}}) Keyword.replace!(opts, :to, target) else _ -> opts end quote bind_quoted: [funs: funs, opts: opts] do target = Kernel.Utils.defdelegate_all(funs, opts, __ENV__) # TODO: Remove List.wrap when multiple funs are no longer supported for fun <- List.wrap(funs) do {name, args, as, as_args} = Kernel.Utils.defdelegate_each(fun, opts) @doc delegate_to: {target, as, :erlang.length(as_args)} # Build the call AST by hand so it doesn't get a # context and it warns on things like missing @impl def unquote({name, [line: __ENV__.line], args}) do unquote(target).unquote(as)(unquote_splicing(as_args)) end end end end ## Sigils @doc ~S""" Handles the sigil `~S` for strings. It returns a string without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Examples iex> ~S(foo) "foo" iex> ~S(f#{o}o) "f\#{o}o" iex> ~S(\o/) "\\o/" However, if you want to re-use the sigil character itself on the string, you need to escape it: iex> ~S((\)) "()" """ defmacro sigil_S(term, modifiers) defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary @doc ~S""" Handles the sigil `~s` for strings. It returns a string as if it was a double quoted string, unescaping characters and replacing interpolations. ## Examples iex> ~s(foo) "foo" iex> ~s(f#{:o}o) "foo" iex> ~s(f\#{:o}o) "f\#{:o}o" """ defmacro sigil_s(term, modifiers) defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do :elixir_interpolation.unescape_string(piece) end defmacro sigil_s({:<<>>, line, pieces}, []) do {:<<>>, line, unescape_tokens(pieces)} end @doc ~S""" Handles the sigil `~C` for charlists. It returns a charlist without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Examples iex> ~C(foo) 'foo' iex> ~C(f#{o}o) 'f\#{o}o' """ defmacro sigil_C(term, modifiers) defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do String.to_charlist(string) end @doc ~S""" Handles the sigil `~c` for charlists. It returns a charlist as if it was a single quoted string, unescaping characters and replacing interpolations. ## Examples iex> ~c(foo) 'foo' iex> ~c(f#{:o}o) 'foo' iex> ~c(f\#{:o}o) 'f\#{:o}o' """ defmacro sigil_c(term, modifiers) # We can skip the runtime conversion if we are # creating a binary made solely of series of chars. defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do String.to_charlist(:elixir_interpolation.unescape_string(string)) end defmacro sigil_c({:<<>>, _meta, pieces}, []) do quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces)))) end @doc ~S""" Handles the sigil `~r` for regular expressions. It returns a regular expression pattern, unescaping characters and replacing interpolations. More information on regular expressions can be found in the `Regex` module. ## Examples iex> Regex.match?(~r/foo/, "foo") true iex> Regex.match?(~r/a#{:b}c/, "abc") true While the `~r` sigil allows parens and brackets to be used as delimiters, it is preferred to use `"` or `/` to avoid escaping conflicts with reserved regex characters. """ defmacro sigil_r(term, modifiers) defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do binary = :elixir_interpolation.unescape_string(string, &Regex.unescape_map/1) regex = Regex.compile!(binary, :binary.list_to_bin(options)) Macro.escape(regex) end defmacro sigil_r({:<<>>, meta, pieces}, options) do binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map/1)} quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))) end @doc ~S""" Handles the sigil `~R` for regular expressions. It returns a regular expression pattern without interpolations and without escape characters. Note it still supports escape of Regex tokens (such as escaping `+` or `?`) and it also requires you to escape the closing sigil character itself if it appears on the Regex. More information on regexes can be found in the `Regex` module. ## Examples iex> Regex.match?(~R(f#{1,3}o), "f#o") true """ defmacro sigil_R(term, modifiers) defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do regex = Regex.compile!(string, :binary.list_to_bin(options)) Macro.escape(regex) end @doc ~S""" Handles the sigil `~D` for dates. By default, this sigil uses the built-in `Calendar.ISO`, which requires dates to be written in the ISO8601 format: ~D[yyyy-mm-dd] such as: ~D[2015-01-13] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~D[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~d` variant does not exist as interpolation and escape characters are not useful for date sigils. More information on dates can be found in the `Date` module. ## Examples iex> ~D[2015-01-13] ~D[2015-01-13] """ defmacro sigil_D(date_string, modifiers) defmacro sigil_D({:<<>>, _, [string]}, []) do {{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, "Date") to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day) end @doc ~S""" Handles the sigil `~T` for times. By default, this sigil uses the built-in `Calendar.ISO`, which requires times to be written in the ISO8601 format: ~T[hh:mm:ss] ~T[hh:mm:ss.ssssss] such as: ~T[13:00:07] ~T[13:00:07.123] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~T[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~t` variant does not exist as interpolation and escape characters are not useful for time sigils. More information on times can be found in the `Time` module. ## Examples iex> ~T[13:00:07] ~T[13:00:07] iex> ~T[13:00:07.001] ~T[13:00:07.001] """ defmacro sigil_T(time_string, modifiers) defmacro sigil_T({:<<>>, _, [string]}, []) do {{:ok, {hour, minute, second, microsecond}}, calendar} = parse_with_calendar!(string, :parse_time, "Time") to_calendar_struct(Time, calendar: calendar, hour: hour, minute: minute, second: second, microsecond: microsecond ) end @doc ~S""" Handles the sigil `~N` for naive date times. By default, this sigil uses the built-in `Calendar.ISO`, which requires naive date times to be written in the ISO8601 format: ~N[yyyy-mm-dd hh:mm:ss] ~N[yyyy-mm-dd hh:mm:ss.ssssss] ~N[yyyy-mm-ddThh:mm:ss.ssssss] such as: ~N[2015-01-13 13:00:07] ~N[2015-01-13T13:00:07.123] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~N[SOME-REPRESENTATION My.Alternative.Calendar] The lower case `~n` variant does not exist as interpolation and escape characters are not useful for date time sigils. More information on naive date times can be found in the `NaiveDateTime` module. ## Examples iex> ~N[2015-01-13 13:00:07] ~N[2015-01-13 13:00:07] iex> ~N[2015-01-13T13:00:07.001] ~N[2015-01-13 13:00:07.001] """ defmacro sigil_N(naive_datetime_string, modifiers) defmacro sigil_N({:<<>>, _, [string]}, []) do {{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} = parse_with_calendar!(string, :parse_naive_datetime, "NaiveDateTime") to_calendar_struct(NaiveDateTime, calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond ) end @doc ~S""" Handles the sigil `~U` to create a UTC `DateTime`. By default, this sigil uses the built-in `Calendar.ISO`, which requires UTC date times to be written in the ISO8601 format: ~U[yyyy-mm-dd hh:mm:ssZ] ~U[yyyy-mm-dd hh:mm:ss.ssssssZ] ~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00] such as: ~U[2015-01-13 13:00:07Z] ~U[2015-01-13T13:00:07.123+00:00] If you are using alternative calendars, any representation can be used as long as you follow the representation by a single space and the calendar name: ~U[SOME-REPRESENTATION My.Alternative.Calendar] The given `datetime_string` must include "Z" or "00:00" offset which marks it as UTC, otherwise an error is raised. The lower case `~u` variant does not exist as interpolation and escape characters are not useful for date time sigils. More information on date times can be found in the `DateTime` module. ## Examples iex> ~U[2015-01-13 13:00:07Z] ~U[2015-01-13 13:00:07Z] iex> ~U[2015-01-13T13:00:07.001+00:00] ~U[2015-01-13 13:00:07.001Z] """ @doc since: "1.9.0" defmacro sigil_U(datetime_string, modifiers) defmacro sigil_U({:<<>>, _, [string]}, []) do {{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} = parse_with_calendar!(string, :parse_utc_datetime, "UTC DateTime") if offset != 0 do raise ArgumentError, "cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset" end to_calendar_struct(DateTime, calendar: calendar, year: year, month: month, day: day, hour: hour, minute: minute, second: second, microsecond: microsecond, time_zone: "Etc/UTC", zone_abbr: "UTC", utc_offset: 0, std_offset: 0 ) end defp parse_with_calendar!(string, fun, context) do {calendar, string} = extract_calendar(string) result = apply(calendar, fun, [string]) {maybe_raise!(result, calendar, context, string), calendar} end defp extract_calendar(string) do case :binary.split(string, " ", [:global]) do [_] -> {Calendar.ISO, string} parts -> maybe_atomize_calendar(List.last(parts), string) end end defp maybe_atomize_calendar(<<alias, _::binary>> = last_part, string) when alias >= ?A and alias <= ?Z do string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1) {String.to_atom("Elixir." <> last_part), string} end defp maybe_atomize_calendar(_last_part, string) do {Calendar.ISO, string} end defp maybe_raise!({:error, reason}, calendar, type, string) do raise ArgumentError, "cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, " <> "reason: #{inspect(reason)}" end defp maybe_raise!(other, _calendar, _type, _string), do: other defp to_calendar_struct(type, fields) do quote do %{unquote_splicing([__struct__: type] ++ fields)} end end @doc ~S""" Handles the sigil `~w` for list of words. It returns a list of "words" split by whitespace. Character unescaping and interpolation happens for each word. ## Modifiers * `s`: words in the list are strings (default) * `a`: words in the list are atoms * `c`: words in the list are charlists ## Examples iex> ~w(foo #{:bar} baz) ["foo", "bar", "baz"] iex> ~w(foo #{" bar baz "}) ["foo", "bar", "baz"] iex> ~w(--source test/enum_test.exs) ["--source", "test/enum_test.exs"] iex> ~w(foo bar baz)a [:foo, :bar, :baz] iex> ~w(foo bar baz)c ['foo', 'bar', 'baz'] """ defmacro sigil_w(term, modifiers) defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do split_words(:elixir_interpolation.unescape_string(string), modifiers, __CALLER__) end defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do binary = {:<<>>, meta, unescape_tokens(pieces)} split_words(binary, modifiers, __CALLER__) end @doc ~S""" Handles the sigil `~W` for list of words. It returns a list of "words" split by whitespace without interpolations and without escape characters, except for the escaping of the closing sigil character itself. ## Modifiers * `s`: words in the list are strings (default) * `a`: words in the list are atoms * `c`: words in the list are charlists ## Examples iex> ~W(foo #{bar} baz) ["foo", "\#{bar}", "baz"] """ defmacro sigil_W(term, modifiers) defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do split_words(string, modifiers, __CALLER__) end defp split_words(string, [], caller) do split_words(string, [?s], caller) end defp split_words(string, [mod], caller) when mod == ?s or mod == ?a or mod == ?c do case is_binary(string) do true -> parts = String.split(string) parts_with_trailing_comma = :lists.filter(&(byte_size(&1) > 1 and :binary.last(&1) == ?,), parts) if parts_with_trailing_comma != [] do stacktrace = Macro.Env.stacktrace(caller) IO.warn( "the sigils ~w/~W do not allow trailing commas at the end of each word. " <> "If the comma is necessary, define a regular list with [...], otherwise remove the comma.", stacktrace ) end case mod do ?s -> parts ?a -> :lists.map(&String.to_atom/1, parts) ?c -> :lists.map(&String.to_charlist/1, parts) end false -> parts = quote(do: String.split(unquote(string))) case mod do ?s -> parts ?a -> quote(do: :lists.map(&String.to_atom/1, unquote(parts))) ?c -> quote(do: :lists.map(&String.to_charlist/1, unquote(parts))) end end end defp split_words(_string, _mods, _caller) do raise ArgumentError, "modifier must be one of: s, a, c" end ## Shared functions defp assert_module_scope(env, fun, arity) do case env.module do nil -> raise ArgumentError, "cannot invoke #{fun}/#{arity} outside module" mod -> mod end end defp assert_no_function_scope(env, fun, arity) do case env.function do nil -> :ok _ -> raise ArgumentError, "cannot invoke #{fun}/#{arity} inside function/macro" end end defp assert_no_match_or_guard_scope(context, exp) do case context do :match -> invalid_match!(exp) :guard -> raise ArgumentError, "invalid expression in guard, #{exp} is not allowed in guards. " <> "To learn more about guards, visit: https://hexdocs.pm/elixir/patterns-and-guards.html" _ -> :ok end end defp invalid_match!(exp) do raise ArgumentError, "invalid expression in match, #{exp} is not allowed in patterns " <> "such as function clauses, case clauses or on the left side of the = operator" end # Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens # We need to do this for bootstrapping purposes, actual code can use Macro.unescape_string. defp unescape_tokens(tokens) do :lists.map( fn token -> case is_binary(token) do true -> :elixir_interpolation.unescape_string(token) false -> token end end, tokens ) end defp unescape_tokens(tokens, unescape_map) do :lists.map( fn token -> case is_binary(token) do true -> :elixir_interpolation.unescape_string(token, unescape_map) false -> token end end, tokens ) end defp unescape_list_tokens(tokens) do escape = fn {:"::", _, [expr, _]} -> expr binary when is_binary(binary) -> :elixir_interpolation.unescape_string(binary) end :lists.map(escape, tokens) end @doc false defmacro to_char_list(arg) do IO.warn( "Kernel.to_char_list/1 is deprecated, use Kernel.to_charlist/1 instead", Macro.Env.stacktrace(__CALLER__) ) quote(do: Kernel.to_charlist(unquote(arg))) end end
27.053538
116
0.634782
79e39f9e45d6a5ab44a0313d4ebac21a24b86f64
16,306
ex
Elixir
lib/guardian/permissions/bitwise.ex
jsangilve/guardian
5d13afc9792396c955a83a35596b54eceab26e78
[ "MIT" ]
null
null
null
lib/guardian/permissions/bitwise.ex
jsangilve/guardian
5d13afc9792396c955a83a35596b54eceab26e78
[ "MIT" ]
null
null
null
lib/guardian/permissions/bitwise.ex
jsangilve/guardian
5d13afc9792396c955a83a35596b54eceab26e78
[ "MIT" ]
null
null
null
defmodule Guardian.Permissions.Bitwise do @moduledoc """ An optional plugin to Guardian to provide permissions for your tokens These can be used for any token types since they only work on the `claims`. Permissions are set on a per implementation module basis. Each implementation module can have their own sets. Permissions are similar in concept to OAuth2 scopes. They're encoded into a token and the permissions granted last as long as the token does. This makes it unsuitable for highly dynamic permission schemes. They're best left to an application to implement. For example. (at the time of writing) some of the Facebook permissions are: * public_profile * user_about_me * user_actions.books * user_actions.fitness * user_actions.music To create permissions for your application similar to these: ```elixir defmodule MyApp.Auth.Token do use Guardian, otp_app: :my_app, permissions: %{ default: [:public_profile, :user_about_me] user_actions: %{ books: 0b1, fitness: 0b100, music: 0b1000, } } use Guardian.Permissions.Bitwise # snip def build_claims(claims, _resource, opts) do claims = claims |> encode_permissions_into_claims!(Keyword.get(opts, :permissions)) {:ok, claims} end end ``` This will take the permission set in the `opts` at `:permissions` and put it into the `"pems"` key of the claims as a map of: `%{set_name => integer}` The permissions can be defined as a list (positional value based on index) or a map where the value for each permission is manually provided. They can be provided either as options to `use Guardian` or in the config for your implementation module. Once you have a token, you can interact with it. ```elixir # Get the encoded permissions from the claims found_perms = MyApp.Auth.Token.decode_permissions_from_claims(claims) # Check if all permissions are present has_all_these_things? = claims |> MyApp.Auth.Token.decode_permissions_from_claims |> MyApp.Auth.Token.all_permissions?(%{default: [:user_about_me, :public_profile]}) # Checks if any permissions are present show_any_media_things? = claims |> MyApp.Auth.Token.decode_permissions_from_claims |> MyApp.Auth.Token.any_permissions?(%{user_actions: [:books, :fitness, :music]}) ``` ### Using with Plug To use a plug for ensuring permissions you can use the `Guardian.Permissions.Bitwise` module as part of a Guardian pipeline. ```elixir # After a pipeline has setup the implementation module and error handler # Ensure that both the `public_profile` and `user_actions.books` permissions are present in the token plug Guardian.Permissions.Bitwise, ensure: %{default: [:public_profile], user_actions: [:books]} # Allow the request to continue when the token contains any of the permission sets specified plug Guardian.Permissions.Bitwise, one_of: [ %{default: [:public_profile], user_actions: [:books]}, %{default: [:public_profile], user_actions: [:music]}, ] # Look for permissions for a token in a different location plug Guardian.Permissions.Bitwise, key: :impersonate, ensure: %{default: [:public_profile]} ``` If the token satisfies either the permissions listed in `ensure` or one of the sets in the `one_of` key the request will continue. If not, then `auth_error` callback will be called on the error handler with `auth_error(conn, {:unauthorized, reason}, options)` """ @type label :: atom @type permission_set :: %{optional(label) => pos_integer} @type t :: %{optional(label) => permission_set} @type input_label :: String.t() :: atom @type input_set :: [input_label, ...] | pos_integer @type input_permissions :: %{optional(input_label) => input_set} @type plug_option :: {:ensure, permission_set} | {:one_of, [permission_set, ...]} | {:key, atom} | {:module, module} | {:error_handler, module} defmodule PermissionNotFoundError do defexception [:message] end defmacro __using__(_opts \\ []) do # Credo is incorrectly identifying an unless block with negated condition 2017-06-10 # credo:disable-for-next-line /\.Refactor\./ quote do use Bitwise alias Guardian.Permissions.Bitwise.PermissionNotFoundError defdelegate max(), to: Guardian.Permissions.Bitwise raw_perms = @config_with_key.(:permissions) unless raw_perms do raise "Permissions are not defined for #{to_string(__MODULE__)}" end @normalized_perms Guardian.Permissions.Bitwise.normalize_permissions(raw_perms) @available_permissions Guardian.Permissions.Bitwise.available_from_normalized( @normalized_perms ) @doc """ Lists all permissions in a normalized way using %{permission_set_name => [permission_name, ...]} """ @spec available_permissions() :: Guardian.Permissions.Bitwise.t() def available_permissions, do: @available_permissions @doc """ Decodes permissions from the permissions found in claims (encoded to integers) or from a list of permissions. iex> MyTokens.decode_permissions(%{default: [:public_profile]}) %{default: [:public_profile]} iex> MyTokens.decode_permissions{%{"default" => 1, "user_actions" => 1}} %{default: [:public_profile], user_actions: [:books]} When using integers (after encoding to claims), unknown bit positions are ignored. iex> MyTokens.decode_permissions(%{"default" => -1}) %{default: [:public_profile, :user_about_me]} """ @spec decode_permissions(Guardian.Permissions.Bitwise.input_permissions() | nil) :: Guardian.Permissions.Bitwise.t() def decode_permissions(nil), do: %{} def decode_permissions(map) when is_map(map) do for {k, v} <- map, Map.get(@normalized_perms, to_string(k)) != nil, into: %{} do key = k |> to_string() |> String.to_atom() {key, do_decode_permissions(v, k)} end end @doc """ Decodes permissions directly from a claims map. This does the same as `decode_permissions` but will fetch the permissions map from the `"pem"` key where `Guardian.Permissions.Bitwise` places them when it encodes them into claims. """ @spec decode_permissions_from_claims(Guardian.Token.claims()) :: Guardian.Permissions.Bitwise.t() def decode_permissions_from_claims(%{"pem" => perms}), do: decode_permissions(perms) def decode_permissions_from_claims(_), do: %{} @doc """ Encodes the permissions provided into the claims in the `"pem"` key. Permissions are encoded into an integer inside the token corresponding with the value provided in the configuration. """ @spec encode_permissions_into_claims!( Guardian.Token.claims(), Guardian.Permissions.Bitwise.input_permissions() | nil ) :: Guardian.Token.claims() def encode_permissions_into_claims!(claims, nil), do: claims def encode_permissions_into_claims!(claims, perms) do encoded_perms = encode_permissions!(perms) Map.put(claims, "pem", encoded_perms) end @doc """ Checks to see if any of the permissions provided are present in the permissions (previously extracted from claims) iex> claims |> MyTokens.decode_permissions() |> any_permissions?(%{user_actions: [:books, :music]}) true """ @spec any_permissions?( Guardian.Permissions.Bitwise.input_permissions(), Guardian.Permissions.Bitwise.input_permissions() ) :: boolean def any_permissions?(has_perms, test_perms) when is_map(test_perms) do has_perms = decode_permissions(has_perms) test_perms = decode_permissions(test_perms) Enum.any?(test_perms, fn {k, needs} -> has_perms |> Map.get(k) |> do_any_permissions?(MapSet.new(needs)) end) end defp do_any_permissions?(nil, %MapSet{}), do: false defp do_any_permissions?(list, %MapSet{} = needs) do matches = needs |> MapSet.intersection(MapSet.new(list)) MapSet.size(matches) > 0 end @doc """ Checks to see if all of the permissions provided are present in the permissions (previously extracted from claims) iex> claims |> MyTokens.decode_permissions() |> all_permissions?(%{user_actions: [:books, :music]}) true """ @spec all_permissions?( Guardian.Permissions.Bitwise.input_permissions(), Guardian.Permissions.Bitwise.input_permissions() ) :: boolean def all_permissions?(has_perms, test_perms) when is_map(test_perms) do has_perms_bits = encode_permissions!(has_perms) test_perms_bits = encode_permissions!(test_perms) Enum.all?(test_perms_bits, fn {k, needs} -> has = Map.get(has_perms_bits, k, 0) Bitwise.band(has, needs) == needs end) end @doc """ Encodes the permissions provided into numeric form iex> MyTokens.encode_permissions!(%{user_actions: [:books, :music]}) %{user_actions: 9} """ @spec encode_permissions!(Guardian.Permissions.Bitwise.input_permissions() | nil) :: Guardian.Permissions.Bitwise.t() def encode_permissions!(nil), do: %{} def encode_permissions!(map) when is_map(map) do for {k, v} <- map, into: %{} do key = String.to_atom(to_string(k)) {key, do_encode_permissions!(v, k)} end end @doc """ Validates that all permissions provided exist in the configuration. iex> MyTokens.validate_permissions!(%{default: [:user_about_me]}) iex> MyTokens.validate_permissions!(%{not: [:a, :thing]}) raise Guardian.Permissions.Bitwise.PermissionNotFoundError """ def validate_permissions!(map) when is_map(map) do Enum.all?(&do_validate_permissions!/1) end defp do_decode_permissions(other), do: do_decode_permissions(other, "default") defp do_decode_permissions(value, type) when is_atom(type), do: do_decode_permissions(value, to_string(type)) defp do_decode_permissions(value, type) when is_list(value) do do_validate_permissions!({type, value}) value |> Enum.map(&to_string/1) |> Enum.map(&String.to_atom/1) end defp do_decode_permissions(value, type) when is_integer(value) do perms = Map.get(@normalized_perms, type) for {k, v} <- perms, band(value, v) == v, into: [] do k |> to_string() |> String.to_atom() end end defp do_encode_permissions!(value, type) when is_atom(type), do: do_encode_permissions!(value, to_string(type)) defp do_encode_permissions!(value, _type) when is_integer(value), do: value defp do_encode_permissions!(value, type) when is_list(value) do do_validate_permissions!({type, value}) perms = Map.get(@normalized_perms, type) Enum.reduce(value, 0, &encode_value(&1, perms, &2)) end defp encode_value(value, perm_set, acc), do: perm_set |> Map.get(to_string(value)) |> bor(acc) defp do_validate_permissions!({type, value}) when is_atom(type), do: do_validate_permissions!({to_string(type), value}) defp do_validate_permissions!({type, map}) when is_map(map) do list = map |> Map.keys() |> Enum.map(&to_string/1) do_validate_permissions!({type, list}) end defp do_validate_permissions!({type, list}) do perm_set = Map.get(@normalized_perms, type) if perm_set do provided_set = list |> Enum.map(&to_string/1) |> MapSet.new() known_set = perm_set |> Map.keys() |> MapSet.new() diff = MapSet.difference(provided_set, known_set) if MapSet.size(diff) > 0 do message = "#{to_string(__MODULE__)} Type: #{type} Missing Permissions: #{ Enum.join(diff, ", ") }" raise PermissionNotFoundError, message: message end :ok else raise PermissionNotFoundError, message: "#{to_string(__MODULE__)} - Type: #{type}" end end end end @doc """ Provides an encoded version of all permissions, and all possible future permissions for a permission set """ def max, do: -1 @doc false def normalize_permissions(perms) do perms = Enum.into(perms, %{}) for {k, v} <- perms, into: %{} do case v do # A list of permission names. # Positional values list when is_list(list) -> perms = for {perm, idx} <- Enum.with_index(list), into: %{} do {to_string(perm), trunc(:math.pow(2, idx))} end {to_string(k), perms} # A map of permissions. The permissions should be name => bit value map when is_map(map) -> perms = for {perm, val} <- map, into: %{}, do: {to_string(perm), val} {to_string(k), perms} end end end @doc false def available_from_normalized(perms) do for {k, v} <- perms, into: %{} do list = v |> Map.keys() |> Enum.map(&String.to_atom/1) {String.to_atom(k), list} end end if Code.ensure_loaded?(Plug) do defmodule PlugImpl do @moduledoc false import Plug.Conn alias Guardian.Plug.Pipeline @doc false @spec init([Guardian.Permissions.Bitwise.plug_option()]) :: [ Guardian.Permissions.Bitwise.plug_option() ] def init(opts) do ensure = Keyword.get(opts, :ensure) one_of = Keyword.get(opts, :one_of) if ensure && one_of do raise ":permissions and a :one_of cannot both be specified for plug #{ to_string(__MODULE__) } " end opts = if Keyword.keyword?(ensure) do ensure = ensure |> Enum.into(%{}) Keyword.put(opts, :ensure, ensure) else opts end opts end @doc false @spec call(conn :: Plug.Conn.t(), opts :: Keyword.t()) :: Plug.Conn.t() def call(conn, opts) do context = %{ claims: Guardian.Plug.current_claims(conn, opts), ensure: Keyword.get(opts, :ensure), handler: Pipeline.fetch_error_handler!(conn, opts), impl: Pipeline.fetch_module!(conn, opts), one_of: Keyword.get(opts, :one_of) } do_call(conn, context, opts) end defp do_call(conn, %{ensure: nil, one_of: nil}, _), do: conn defp do_call(conn, %{claims: nil} = ctx, opts) do ctx.handler |> apply(:auth_error, [conn, {:unauthorized, :unauthorized}, opts]) |> halt() end # single set of permissions to check defp do_call(conn, %{one_of: nil} = ctx, opts) do has_perms = apply(ctx.impl, :decode_permissions_from_claims, [ctx.claims]) is_ok? = apply(ctx.impl, :all_permissions?, [has_perms, ctx.ensure]) if is_ok? do conn else ctx.handler |> apply(:auth_error, [conn, {:unauthorized, :unauthorized}, opts]) |> halt() end end # one_of sets of permissions to check defp do_call(conn, %{ensure: nil} = ctx, opts) do has_perms = apply(ctx.impl, :decode_permissions_from_claims, [ctx.claims]) is_ok? = Enum.any?(ctx.one_of, fn test_perms -> apply(ctx.impl, :all_permissions?, [has_perms, test_perms]) end) if is_ok? do conn else ctx.handler |> apply(:auth_error, [conn, {:unauthorized, :unauthorized}, opts]) |> halt() end end end defdelegate init(opts), to: PlugImpl defdelegate call(conn, opts), to: PlugImpl end end
34.041754
107
0.629523
79e3f3591c7b7e4635282dcb90904f43d3482d01
12,233
ex
Elixir
lib/phoenix_live_view/static.ex
HoJSim/phoenix_live_view
8cb3b4c872e6e0a0fb4209cb651aab84309ea6c8
[ "MIT" ]
1
2020-09-15T22:13:16.000Z
2020-09-15T22:13:16.000Z
lib/phoenix_live_view/static.ex
HoJSim/phoenix_live_view
8cb3b4c872e6e0a0fb4209cb651aab84309ea6c8
[ "MIT" ]
null
null
null
lib/phoenix_live_view/static.ex
HoJSim/phoenix_live_view
8cb3b4c872e6e0a0fb4209cb651aab84309ea6c8
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveView.Static do # Holds the logic for static rendering. @moduledoc false alias Phoenix.LiveView.{Socket, Utils, Diff} # Token version. Should be changed whenever new data is stored. @token_vsn 4 def token_vsn, do: @token_vsn # Max session age in seconds. Equivalent to 2 weeks. @max_session_age 1_209_600 @doc """ Acts as a view via put_view to maintain the controller render + instrumentation stack. """ def render("template.html", %{content: content}) do content end def render(_other, _assigns), do: nil @doc """ Verifies the session token. Returns the decoded map of session data or an error. ## Examples iex> verify_session(AppWeb.Endpoint, encoded_token, static_token) {:ok, %{} = decoded_session} iex> verify_session(AppWeb.Endpoint, "bad token", "bac static") {:error, :invalid} iex> verify_session(AppWeb.Endpoint, "expired", "expired static") {:error, :expired} """ def verify_session(endpoint, session_token, static_token) do with {:ok, %{id: id} = session} <- verify_token(endpoint, session_token), {:ok, static} <- verify_static_token(endpoint, id, static_token) do {:ok, Map.merge(session, static)} end end defp verify_static_token(_endpoint, _id, nil), do: {:ok, %{assigned_new: []}} defp verify_static_token(endpoint, id, token) do case verify_token(endpoint, token) do {:ok, %{id: ^id}} = ok -> ok {:ok, _} -> {:error, :invalid} {:error, _} = error -> error end end defp verify_token(endpoint, token) do case Phoenix.Token.verify(endpoint, Utils.salt!(endpoint), token, max_age: @max_session_age) do {:ok, {@token_vsn, term}} -> {:ok, term} {:ok, _} -> {:error, :outdated} {:error, _} = error -> error end end defp load_session(conn_or_socket_session, opts) do user_session = Keyword.get(opts, :session, %{}) validate_session(user_session) {user_session, Map.merge(conn_or_socket_session, user_session)} end defp validate_session(session) do if is_map(session) and Enum.all?(session, fn {k, _} -> is_binary(k) end) do :ok else raise ArgumentError, "LiveView :session must be a map with string keys, got: #{inspect(session)}" end end defp maybe_get_session(conn) do Plug.Conn.get_session(conn) rescue _ -> %{} end @doc """ Renders a live view without spawning a LiveView server. * `conn` - the Plug.Conn struct form the HTTP request * `view` - the LiveView module ## Options * `:router` - the router the live view was built at * `:action` - the router action * `:session` - the required map of session data * `:container` - the optional tuple for the HTML tag and DOM attributes to be used for the LiveView container. For example: `{:li, style: "color: blue;"}` """ def render(%Plug.Conn{} = conn, view, opts) do conn_session = maybe_get_session(conn) {to_sign_session, mount_session} = load_session(conn_session, opts) config = load_live!(view, :view) {tag, extended_attrs} = container(config, opts) router = Keyword.get(opts, :router) action = Keyword.get(opts, :action) endpoint = Phoenix.Controller.endpoint_module(conn) flash = Phoenix.Controller.get_flash(conn) request_url = Plug.Conn.request_url(conn) socket = Utils.configure_socket( %Socket{endpoint: endpoint, view: view, root_view: view, router: router}, %{assigned_new: {conn.assigns, []}, connect_params: %{}, conn_session: conn_session}, action, flash ) case call_mount_and_handle_params!(socket, view, mount_session, conn.params, request_url) do {:ok, socket} -> data_attrs = [ phx_view: config.name, phx_session: sign_root_session(socket, router, view, to_sign_session), phx_static: sign_static_token(socket), ] data_attrs = if(router, do: [phx_main: true], else: []) ++ data_attrs attrs = [ {:id, socket.id}, {:data, data_attrs} | extended_attrs ] try do {:ok, to_rendered_content_tag(socket, tag, view, attrs), socket.assigns} catch :throw, {:phoenix, :child_redirect, redir_opts, flash} -> {:stop, socket |> rewrite_redir(redir_opts) |> Utils.merge_flash(flash)} end {:stop, socket} -> {:stop, socket} end end @doc """ Renders only the static container of the LiveView. Accepts same options as `render/3`. This is called by external live links. """ def container_render(%Plug.Conn{} = conn, view, opts) do {to_sign_session, _mount_session} = load_session(maybe_get_session(conn), opts) config = load_live!(view, :view) {tag, extended_attrs} = container(config, opts) router = Keyword.get(opts, :router) action = Keyword.get(opts, :action) endpoint = Phoenix.Controller.endpoint_module(conn) flash = Phoenix.Controller.get_flash(conn) socket = Utils.configure_socket( %Socket{endpoint: endpoint, view: view, root_view: view}, %{assigned_new: {conn.assigns, []}, connect_params: %{}}, action, flash ) session_token = sign_root_session(socket, router, view, to_sign_session) attrs = [ {:id, socket.id}, {:data, phx_view: config.name, phx_session: session_token} | extended_attrs ] tag |> Phoenix.HTML.Tag.content_tag(attrs, do: nil) |> Phoenix.HTML.safe_to_string() end @doc """ Renders a nested live view without spawning a server. * `parent` - the parent `%Phoenix.LiveView.Socket{}` * `view` - the child LiveView module Accepts the same options as `render/3`. """ def nested_render(%Socket{endpoint: endpoint, connected?: connected?} = parent, view, opts) do config = load_live!(view, :view) container = container(config, opts) flash = Utils.get_flash(parent) child_id = opts[:id] || raise ArgumentError, "an :id is required when rendering child LiveView. " <> "The :id must uniquely identify the child." socket = Utils.configure_socket( %Socket{ id: to_string(child_id), root_view: parent.root_view, view: view, endpoint: endpoint, root_pid: parent.root_pid, parent_pid: self() }, %{assigned_new: {parent.assigns, []}}, nil, flash ) if connected? do connected_nested_render(parent, config, socket, view, container, opts) else disconnected_nested_render(parent, config, socket, view, container, opts) end end defp disconnected_nested_render(parent, config, socket, view, container, opts) do conn_session = parent.private.conn_session {_, mount_session} = load_session(conn_session, opts) {tag, extended_attrs} = container socket = put_in(socket.private[:conn_session], conn_session) socket = Utils.maybe_call_mount!(socket, view, [:not_mounted_at_router, mount_session, socket]) if socket.redirected do throw {:phoenix, :child_redirect, redirect_opts(socket), Utils.get_flash(socket)} end if exports_handle_params?(view) do raise ArgumentError, "handle_params/3 is not allowed on child LiveViews, only at the root" end attrs = [ {:id, socket.id}, {:data, phx_view: config.name, phx_session: "", phx_static: sign_static_token(socket), phx_parent_id: parent.id} | extended_attrs ] to_rendered_content_tag(socket, tag, view, attrs) end defp connected_nested_render(parent, config, socket, view, container, opts) do {to_sign_session, _} = load_session(%{}, opts) {tag, extended_attrs} = container session_token = sign_nested_session(parent, socket, view, to_sign_session) attrs = [ {:id, socket.id}, {:data, phx_parent_id: parent.id, phx_view: config.name, phx_session: session_token, phx_static: ""} | extended_attrs ] Phoenix.HTML.Tag.content_tag(tag, "", attrs) end defp to_rendered_content_tag(socket, tag, view, attrs) do rendered = Utils.to_rendered(socket, view) {_, diff, _} = Diff.render(socket, rendered, Diff.new_components()) Phoenix.HTML.Tag.content_tag(tag, {:safe, Diff.to_iodata(diff)}, attrs) end defp load_live!(view_or_component, kind) do case view_or_component.__live__() do %{kind: ^kind} = config -> config %{kind: other} -> raise "expected #{inspect(view_or_component)} to be a #{kind}, but it is a #{other}" end end defp call_mount_and_handle_params!(socket, view, session, params, uri) do mount_params = if socket.router, do: params, else: :not_mounted_at_router socket |> Utils.maybe_call_mount!(view, [mount_params, session, socket]) |> mount_handle_params(view, params, uri) |> case do {:noreply, %Socket{redirected: {:live, :redirect, opts}} = socket} -> {:stop, rewrite_redir(socket, opts)} {:noreply, %Socket{redirected: {:live, {_, _} = _patch, opts}}} -> {:stop, rewrite_redir(socket, opts)} {:noreply, %Socket{redirected: {:redirect, _opts}} = new_socket} -> {:stop, new_socket} {:noreply, %Socket{redirected: nil} = new_socket} -> {:ok, new_socket} other -> raise ArgumentError, """ invalid result returned from #{inspect(view)}.handle_params/3. Expected {:noreply, socket}, got: #{inspect(other)} """ end end defp rewrite_redir(%Socket{} = socket, live_redir_opts) do %Socket{socket | redirected: {:redirect, live_redir_opts}} end defp redirect_opts(%Socket{redirected: {:redirect, opts}}), do: opts defp redirect_opts(%Socket{redirected: {:live, :redirect, opts}}), do: opts defp redirect_opts(%Socket{redirected: {:live, {_, _} = _patch, opts}}), do: opts defp redirect_opts(%Socket{}), do: raise(ArgumentError, "no redirect present") defp mount_handle_params(%Socket{redirected: mount_redir} = socket, view, params, uri) do cond do mount_redir -> {:noreply, socket} not exports_handle_params?(view) -> {:noreply, socket} is_nil(socket.router) -> # Let the callback fail for the usual reasons Utils.live_link_info!(nil, view, uri) true -> view.handle_params(params, uri, socket) end end defp exports_handle_params?(view), do: function_exported?(view, :handle_params, 3) defp sign_root_session(%Socket{id: id, endpoint: endpoint}, router, view, session) do # IMPORTANT: If you change the third argument, @token_vsn has to be bumped. sign_token(endpoint, %{ id: id, view: view, root_view: view, router: router, parent_pid: nil, root_pid: nil, session: session }) end defp sign_nested_session(%Socket{} = parent, %Socket{} = child, view, session) do # IMPORTANT: If you change the third argument, @token_vsn has to be bumped. sign_token(parent.endpoint, %{ id: child.id, view: view, root_view: parent.root_view, router: parent.router, parent_pid: self(), root_pid: parent.root_pid, session: session }) end # THe static token is computed only on disconnected render and it keeps # the information that is only available during disconnected renders, # such as assign_new. defp sign_static_token(%Socket{id: id, endpoint: endpoint} = socket) do # IMPORTANT: If you change the third argument, @token_vsn has to be bumped. sign_token(endpoint, %{ id: id, flash: socket.assigns.flash, assigned_new: assigned_new_keys(socket) }) end defp sign_token(endpoint, data) do Phoenix.Token.sign(endpoint, Utils.salt!(endpoint), {@token_vsn, data}) end defp container(%{container: {tag, attrs}}, opts) do case opts[:container] do {tag, extra} -> {tag, Keyword.merge(attrs, extra)} nil -> {tag, attrs} end end defp assigned_new_keys(socket) do {_, keys} = socket.private.assigned_new keys end end
30.813602
99
0.647347
79e3febbd15bd4e0453149af1f48926758396f18
2,588
ex
Elixir
cp/lib/cpsim/cp/actions/calls/stop_transaction.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
cp/lib/cpsim/cp/actions/calls/stop_transaction.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
cp/lib/cpsim/cp/actions/calls/stop_transaction.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
defmodule CPSIM.CP.Actions.Calls.StopTransaction do require Logger alias CPSIM.CP.Connection.Messages.{Call, CallResult, CallError} # TODO: properly handle stop transactions without id_tag def send(state, id_tag \\ nil, action_callback \\ nil) do connector_id = get_in(state, [:modules, CPSIM.CP.Actions, :state, :started_transaction_connector]) Call.new( "StopTransaction", %{ idTag: id_tag, meterStop: get_in(state, [:internal_config, :connector_meters, connector_id]) |> trunc(), timestamp: DateTime.utc_now() |> DateTime.to_iso8601(), transactionId: get_in(state, [:modules, CPSIM.CP.Actions, :state, :started_transaction_id]) }, __MODULE__ ) |> CPSIM.CP.Connection.Calls.enqueue(state) |> put_in([:modules, CPSIM.CP.Actions, :state, :action_callback], action_callback) end # TODO: handle parentIdTag # TODO: handle expire def handle_call_response(%CallResult{payload: %{"idTagInfo" => %{"status" => "Accepted"}}}, _call, state) do state |> put_in([:modules, CPSIM.CP.Actions, :state, :started_transaction_id], nil) |> put_in([:modules, CPSIM.CP.Actions, :state, :started_transaction_connector], nil) |> maybe_call_action_callback() |> then(&{:ok, &1}) end def handle_call_response(%CallResult{payload: %{"idTagInfo" => %{"status" => status}}}, _call, state) when status in ~w[Blocked Expired Invalid ConcurrentTx] do state |> CPSIM.CP.Actions.skip_current_batch() |> then(&{:ok, &1}) end def handle_call_response(%CallResult{payload: %{}}, _call, state) do state |> put_in([:modules, CPSIM.CP.Actions, :state, :started_transaction_id], nil) |> put_in([:modules, CPSIM.CP.Actions, :state, :started_transaction_connector], nil) |> maybe_call_action_callback() |> then(&{:ok, &1}) end def handle_call_response(%CallError{error_code: code, error_desc: desc, error_details: details}, _call, state) do Logger.warn( "Received error response from server: code=#{inspect(code)}, desc=#{inspect(desc)}, details=#{inspect(details)}" ) state |> CPSIM.CP.Actions.skip_current_batch() |> then(&{:ok, &1}) end defp maybe_call_action_callback(state) do case get_in(state, [:modules, CPSIM.CP.Actions, :state, :action_callback]) do action_callback when not is_nil(action_callback) -> state |> put_in([:modules, CPSIM.CP.Actions, :state, :action_callback], nil) |> CPSIM.CP.Actions.call_action_callback(action_callback) nil -> state end end end
36.450704
118
0.674266
79e409fb4c145ae80d44890fb18e11fe23b1670d
899
ex
Elixir
lib/appsignal/monitor.ex
oliver-kriska/appsignal-elixir
2de2759a67257c5325434f190084f53c4ab5f913
[ "MIT" ]
null
null
null
lib/appsignal/monitor.ex
oliver-kriska/appsignal-elixir
2de2759a67257c5325434f190084f53c4ab5f913
[ "MIT" ]
null
null
null
lib/appsignal/monitor.ex
oliver-kriska/appsignal-elixir
2de2759a67257c5325434f190084f53c4ab5f913
[ "MIT" ]
null
null
null
defmodule Appsignal.Monitor do @moduledoc false @deletion_delay Application.get_env(:appsignal, :deletion_delay, 5_000) use GenServer alias Appsignal.Tracer def start_link do GenServer.start_link(__MODULE__, [], name: __MODULE__) end def init(state) do {:ok, state} end def add do GenServer.cast(__MODULE__, {:monitor, self()}) end def handle_cast({:monitor, pid}, state) do unless pid in monitors(), do: Process.monitor(pid) {:noreply, state} end def handle_info({:DOWN, _ref, :process, pid, _}, state) do Process.send_after(self(), {:delete, pid}, @deletion_delay) {:noreply, state} end def handle_info({:delete, pid}, state) do Tracer.delete(pid) {:noreply, state} end defp monitors do {:monitors, monitors} = Process.info(self(), :monitors) Enum.map(monitors, fn {:process, process} -> process end) end end
22.475
73
0.674082
79e418b4f653762b6ba028d5eacdcd121a77bcca
2,316
ex
Elixir
lib/blaine/persistance/repository/dets.ex
eeng/blaine
d91d94034925d64632789925ef90a198c0a1d8ea
[ "MIT" ]
null
null
null
lib/blaine/persistance/repository/dets.ex
eeng/blaine
d91d94034925d64632789925ef90a198c0a1d8ea
[ "MIT" ]
null
null
null
lib/blaine/persistance/repository/dets.ex
eeng/blaine
d91d94034925d64632789925ef90a198c0a1d8ea
[ "MIT" ]
null
null
null
defmodule Blaine.Persistence.Repository.Dets do @moduledoc """ This GenServer handles the system persistance in a DETS table. """ use Blaine.Persistance.Repository use GenServer @me __MODULE__ def start_link(opts) do table = Keyword.get(opts, :table, :blaine) GenServer.start_link(@me, table, name: @me) end @impl Repository def accounts(role) do GenServer.call(@me, {:accounts, role}) end @impl Repository def add_account(account) do GenServer.call(@me, {:add_account, account}) end @impl Repository def remove_account(id) do GenServer.call(@me, {:remove_account, id}) end @impl Repository def save_last_run_at(last_run_at) do GenServer.call(@me, {:save_last_run_at, last_run_at}) end @impl Repository def last_run_at() do GenServer.call(@me, :last_run_at) end @impl GenServer def init(table) do File.mkdir("priv") path = "priv/#{table}.db" |> String.to_charlist() :dets.open_file(table, [{:file, path}]) {:ok, table} end @impl GenServer def terminate(_reason, table) do :dets.close(table) end @impl GenServer def handle_call({:accounts, role}, _from, table) do accounts = get_accounts(table) |> Map.values() |> Enum.filter(&role_matches?(&1, role)) {:reply, accounts, table} end @impl GenServer def handle_call({:add_account, account}, _from, table) do new_accounts = get_accounts(table) |> Map.put(account.id, account) {:reply, store(table, :accounts, new_accounts), table} end @impl GenServer def handle_call({:remove_account, id}, _from, table) do new_accounts = get_accounts(table) |> Map.delete(id) {:reply, store(table, :accounts, new_accounts), table} end @impl GenServer def handle_call({:save_last_run_at, last_run_at}, _from, table) do {:reply, store(table, :last_run_at, last_run_at), table} end @impl GenServer def handle_call(:last_run_at, _from, table) do {:reply, get(table, :last_run_at), table} end defp store(table, key, value) do :dets.insert(table, {key, value}) end defp get(table, key, default \\ nil) do case :dets.lookup(table, key) do [{^key, value}] -> value _ -> default end end defp get_accounts(table) do get(table, :accounts, %{}) end end
22.930693
70
0.66753
79e43749a3b57e7a94ecd218822121d707067ea0
7,519
ex
Elixir
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/product.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/product.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/product.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.AndroidEnterprise.V1.Model.Product do @moduledoc """ A Products resource represents an app in the Google Play store that is available to at least some users in the enterprise. (Some apps are restricted to a single enterprise, and no information about them is made available outside that enterprise.) The information provided for each product (localized name, icon, link to the full Google Play details page) is intended to allow a basic representation of the product within an EMM user interface. ## Attributes * `appTracks` (*type:* `list(GoogleApi.AndroidEnterprise.V1.Model.TrackInfo.t)`, *default:* `nil`) - The tracks visible to the enterprise. * `appVersion` (*type:* `list(GoogleApi.AndroidEnterprise.V1.Model.AppVersion.t)`, *default:* `nil`) - App versions currently available for this product. * `authorName` (*type:* `String.t`, *default:* `nil`) - The name of the author of the product (for example, the app developer). * `availableCountries` (*type:* `list(String.t)`, *default:* `nil`) - The countries which this app is available in. * `availableTracks` (*type:* `list(String.t)`, *default:* `nil`) - Deprecated, use appTracks instead. * `category` (*type:* `String.t`, *default:* `nil`) - The app category (e.g. RACING, SOCIAL, etc.) * `contentRating` (*type:* `String.t`, *default:* `nil`) - The content rating for this app. * `description` (*type:* `String.t`, *default:* `nil`) - The localized promotional description, if available. * `detailsUrl` (*type:* `String.t`, *default:* `nil`) - A link to the (consumer) Google Play details page for the product. * `distributionChannel` (*type:* `String.t`, *default:* `nil`) - How and to whom the package is made available. The value publicGoogleHosted means that the package is available through the Play store and not restricted to a specific enterprise. The value privateGoogleHosted means that the package is a private app (restricted to an enterprise) but hosted by Google. The value privateSelfHosted means that the package is a private app (restricted to an enterprise) and is privately hosted. * `iconUrl` (*type:* `String.t`, *default:* `nil`) - A link to an image that can be used as an icon for the product. This image is suitable for use at up to 512px x 512px. * `kind` (*type:* `String.t`, *default:* `androidenterprise#product`) - Identifies what kind of resource this is. Value: the fixed string "androidenterprise#product". * `lastUpdatedTimestampMillis` (*type:* `String.t`, *default:* `nil`) - The approximate time (within 7 days) the app was last published, expressed in milliseconds since epoch. * `minAndroidSdkVersion` (*type:* `integer()`, *default:* `nil`) - The minimum Android SDK necessary to run the app. * `permissions` (*type:* `list(GoogleApi.AndroidEnterprise.V1.Model.ProductPermission.t)`, *default:* `nil`) - A list of permissions required by the app. * `productId` (*type:* `String.t`, *default:* `nil`) - A string of the form app:<package name>. For example, app:com.google.android.gm represents the Gmail app. * `productPricing` (*type:* `String.t`, *default:* `nil`) - Whether this product is free, free with in-app purchases, or paid. If the pricing is unknown, this means the product is not generally available anymore (even though it might still be available to people who own it). * `recentChanges` (*type:* `String.t`, *default:* `nil`) - A description of the recent changes made to the app. * `requiresContainerApp` (*type:* `boolean()`, *default:* `nil`) - Deprecated. * `screenshotUrls` (*type:* `list(String.t)`, *default:* `nil`) - A list of screenshot links representing the app. * `signingCertificate` (*type:* `GoogleApi.AndroidEnterprise.V1.Model.ProductSigningCertificate.t`, *default:* `nil`) - The certificate used to sign this product. * `smallIconUrl` (*type:* `String.t`, *default:* `nil`) - A link to a smaller image that can be used as an icon for the product. This image is suitable for use at up to 128px x 128px. * `title` (*type:* `String.t`, *default:* `nil`) - The name of the product. * `workDetailsUrl` (*type:* `String.t`, *default:* `nil`) - A link to the managed Google Play details page for the product, for use by an Enterprise admin. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :appTracks => list(GoogleApi.AndroidEnterprise.V1.Model.TrackInfo.t()), :appVersion => list(GoogleApi.AndroidEnterprise.V1.Model.AppVersion.t()), :authorName => String.t(), :availableCountries => list(String.t()), :availableTracks => list(String.t()), :category => String.t(), :contentRating => String.t(), :description => String.t(), :detailsUrl => String.t(), :distributionChannel => String.t(), :iconUrl => String.t(), :kind => String.t(), :lastUpdatedTimestampMillis => String.t(), :minAndroidSdkVersion => integer(), :permissions => list(GoogleApi.AndroidEnterprise.V1.Model.ProductPermission.t()), :productId => String.t(), :productPricing => String.t(), :recentChanges => String.t(), :requiresContainerApp => boolean(), :screenshotUrls => list(String.t()), :signingCertificate => GoogleApi.AndroidEnterprise.V1.Model.ProductSigningCertificate.t(), :smallIconUrl => String.t(), :title => String.t(), :workDetailsUrl => String.t() } field(:appTracks, as: GoogleApi.AndroidEnterprise.V1.Model.TrackInfo, type: :list) field(:appVersion, as: GoogleApi.AndroidEnterprise.V1.Model.AppVersion, type: :list) field(:authorName) field(:availableCountries, type: :list) field(:availableTracks, type: :list) field(:category) field(:contentRating) field(:description) field(:detailsUrl) field(:distributionChannel) field(:iconUrl) field(:kind) field(:lastUpdatedTimestampMillis) field(:minAndroidSdkVersion) field(:permissions, as: GoogleApi.AndroidEnterprise.V1.Model.ProductPermission, type: :list) field(:productId) field(:productPricing) field(:recentChanges) field(:requiresContainerApp) field(:screenshotUrls, type: :list) field(:signingCertificate, as: GoogleApi.AndroidEnterprise.V1.Model.ProductSigningCertificate) field(:smallIconUrl) field(:title) field(:workDetailsUrl) end defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.Product do def decode(value, options) do GoogleApi.AndroidEnterprise.V1.Model.Product.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.Product do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
63.184874
493
0.700758
79e44cc14f9264b035a5aba1670bd6f22b2799ca
8,780
ex
Elixir
lib/elasticsearch/indexing/index.ex
Eein/elasticsearch-elixir
2f8a63069d6ba64ff9d572c66c10449a287837b8
[ "MIT" ]
null
null
null
lib/elasticsearch/indexing/index.ex
Eein/elasticsearch-elixir
2f8a63069d6ba64ff9d572c66c10449a287837b8
[ "MIT" ]
null
null
null
lib/elasticsearch/indexing/index.ex
Eein/elasticsearch-elixir
2f8a63069d6ba64ff9d572c66c10449a287837b8
[ "MIT" ]
null
null
null
defmodule Elasticsearch.Index do @moduledoc """ Functions for manipulating Elasticsearch indexes. """ alias Elasticsearch.{ Cluster.Config, Index.Bulk } @doc """ Creates an index using a zero-downtime hot-swap technique. 1. Build an index for the given `alias`, with a timestamp: `alias-12323123` 2. Bulk upload data to that index using `store` and `sources`. 3. Alias the `alias` to `alias-12323123`. 4. Remove old indexes beginning with `alias`. 5. Refresh `alias-12323123`. This allows an old index to be served while a new index for `alias` is built. ## Example iex> Index.hot_swap(Cluster, "posts") :ok """ @spec hot_swap(Cluster.t(), alias :: String.t() | atom) :: :ok | {:error, Elasticsearch.Exception.t()} | {:error, :enoent} def hot_swap(cluster, alias) do alias = alias_to_atom(alias) name = build_name(alias) config = Config.get(cluster) %{settings: settings_file} = index_config = config[:indexes][alias] with :ok <- create_from_file(config, name, settings_file), :ok <- Bulk.upload(config, name, index_config), :ok <- __MODULE__.alias(config, name, to_string(alias)), :ok <- clean_starting_with(config, to_string(alias), 2), :ok <- refresh(config, name) do :ok end end defp alias_to_atom(atom) when is_atom(atom), do: atom defp alias_to_atom(str) when is_binary(str), do: String.to_existing_atom(str) @doc """ Returns all indexes which start with a given string. ## Example iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.starting_with(Cluster, "posts") {:ok, ["posts-1"]} """ @spec starting_with(Cluster.t(), String.t() | atom) :: {:ok, [String.t()]} | {:error, Elasticsearch.Exception.t()} def starting_with(cluster, prefix) do with {:ok, indexes} <- Elasticsearch.get(cluster, "/_cat/indices?format=json") do prefix = prefix |> to_string() |> Regex.escape() {:ok, regex} = Regex.compile("^#{prefix}-[0-9]+$") indexes = indexes |> Enum.map(& &1["index"]) |> Enum.filter(&Regex.match?(regex, &1)) |> Enum.sort() {:ok, indexes} end end @doc """ Assigns an alias to a given index, simultaneously removing it from prior indexes, with zero downtime. ## Example iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.alias(Cluster, "posts-1", "posts") :ok """ @spec alias(Cluster.t(), String.t(), String.t()) :: :ok | {:error, Elasticsearch.Exception.t()} def alias(cluster, name, alias) do with {:ok, indexes} <- starting_with(cluster, alias), indexes = Enum.reject(indexes, &(&1 == name)) do remove_actions = Enum.map(indexes, fn index -> %{"remove" => %{"index" => index, "alias" => alias}} end) actions = %{ "actions" => remove_actions ++ [%{"add" => %{"index" => name, "alias" => alias}}] } with {:ok, _response} <- Elasticsearch.post(cluster, "/_aliases", actions), do: :ok end end @doc """ Gets the most recent index name with the given prefix. ## Examples iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.create_from_file(Cluster, "posts-2", "test/support/settings/posts.json") ...> Index.latest_starting_with(Cluster, "posts") {:ok, "posts-2"} If there are no indexes matching that prefix: iex> Index.latest_starting_with(Cluster, "nonexistent") {:error, :not_found} """ @spec latest_starting_with(Cluster.t(), String.t() | atom) :: {:ok, String.t()} | {:error, :not_found} | {:error, Elasticsearch.Exception.t()} def latest_starting_with(cluster, prefix) do with {:ok, indexes} <- starting_with(cluster, prefix) do index = indexes |> Enum.sort() |> List.last() case index do nil -> {:error, :not_found} index -> {:ok, index} end end end @doc """ Refreshes a given index with recently added data. ## Example iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.refresh(Cluster, "posts-1") :ok """ @spec refresh(Cluster.t(), String.t()) :: :ok | {:error, Elasticsearch.Exception.t()} def refresh(cluster, name) do with {:ok, _} <- Elasticsearch.post(cluster, "/#{name}/_forcemerge?max_num_segments=5", %{}), {:ok, _} <- Elasticsearch.post(cluster, "/#{name}/_refresh", %{}), do: :ok end @doc """ Same as `refresh/1`, but raises an error on failure. ## Examples iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.refresh!(Cluster, "posts-1") :ok iex> Index.refresh!(Cluster, "nonexistent") ** (Elasticsearch.Exception) (index_not_found_exception) no such index """ @spec refresh!(Cluster.t(), String.t()) :: :ok def refresh!(cluster, name) do case refresh(cluster, name) do :ok -> :ok {:error, error} -> raise error end end @doc """ Removes indexes starting with the given prefix, keeping a certain number. Can be used to garbage collect old indexes that are no longer used. ## Examples If there is only one index, and `num_to_keep` is >= 1, the index is not deleted. iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.clean_starting_with(Cluster, "posts", 1) ...> Index.starting_with(Cluster, "posts") {:ok, ["posts-1"]} If `num_to_keep` is less than the number of indexes, the older indexes are deleted. iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") ...> Index.clean_starting_with(Cluster, "posts", 0) ...> Index.starting_with(Cluster, "posts") {:ok, []} """ @spec clean_starting_with(Cluster.t(), String.t(), integer) :: :ok | {:error, [Elasticsearch.Exception.t()]} def clean_starting_with(cluster, prefix, num_to_keep) when is_integer(num_to_keep) do with {:ok, indexes} <- starting_with(cluster, prefix) do total = length(indexes) num_to_delete = total - num_to_keep num_to_delete = if num_to_delete >= 0, do: num_to_delete, else: 0 errors = indexes |> Enum.sort() |> Enum.take(num_to_delete) |> Enum.map(&Elasticsearch.delete(cluster, "/#{&1}")) |> Enum.filter(&(elem(&1, 0) == :error)) |> Enum.map(&elem(&1, 1)) if length(errors) > 0 do {:error, errors} else :ok end end end @doc """ Creates an index with the given name from either a JSON string or Elixir map. ## Examples iex> Index.create(Cluster, "posts-1", "{}") :ok """ @spec create(Cluster.t(), String.t(), map | String.t()) :: :ok | {:error, Elasticsearch.Exception.t()} def create(cluster, name, settings) do with {:ok, _response} <- Elasticsearch.put(cluster, "/#{name}", settings), do: :ok end @doc """ Creates an index with the given name, with settings loaded from a JSON file. ## Example iex> Index.create_from_file(Cluster, "posts-1", "test/support/settings/posts.json") :ok iex> Index.create_from_file(Cluster, "posts-1", "nonexistent.json") {:error, :enoent} The `posts.json` file contains regular index settings as described in the Elasticsearch [documentation](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping.html#_example_mapping): { "mappings": { "post": { "properties": { "title": { "type": "string" }, "author": { "type": "string" } } } } } """ @spec create_from_file(Cluster.t(), String.t(), Path.t()) :: :ok | {:error, File.posix()} | {:error, Elasticsearch.Exception.t()} def create_from_file(cluster, name, file) do with {:ok, settings} <- File.read(file) do create(cluster, name, settings) end end @doc """ Generates a name for an index that will be aliased to a given `alias`. Similar to migrations, the name will contain a timestamp. ## Example Index.build_name("main") # => "main-1509581256" """ @spec build_name(String.t() | atom) :: String.t() def build_name(alias) do "#{alias}-#{system_timestamp()}" end defp system_timestamp do DateTime.to_unix(DateTime.utc_now(), :microsecond) end end
29.863946
127
0.602733
79e454d3800f1d5a3e2ef97a68abaa409ed781b2
1,988
exs
Elixir
apps/service_aggregate/test/aggregate/reducer/bounding_box_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
12
2020-01-27T19:43:02.000Z
2021-07-28T19:46:29.000Z
apps/service_aggregate/test/aggregate/reducer/bounding_box_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
81
2020-01-28T18:07:23.000Z
2021-11-22T02:12:13.000Z
apps/service_aggregate/test/aggregate/reducer/bounding_box_test.exs
jdenen/hindsight
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
[ "Apache-2.0" ]
10
2020-02-13T21:24:09.000Z
2020-05-21T18:39:35.000Z
defmodule Aggregate.Reducer.BoundingBoxTest do use ExUnit.Case import Checkov setup do reducer = Aggregate.Reducer.BoundingBox.new( latitude_path: ["lat"], longitude_path: ["long"] ) [reducer: reducer] end describe "init/2" do test "will read from stats", %{reducer: reducer} do stats = %{ "bounding_box" => [1.0, 2.0, 3.0, 4.0] } output = Aggregate.Reducer.init(reducer, stats) assert output.xmin == 1.0 assert output.ymin == 2.0 assert output.xmax == 3.0 assert output.ymax == 4.0 end end describe "reduce/2" do data_test "reducing (#{long}, #{lat}) into #{inspect(bbox)}", %{reducer: reducer} do stats = %{ "bounding_box" => bbox } reducer = Aggregate.Reducer.init(reducer, stats) event = %{"long" => long, "lat" => lat} output = Aggregate.Reducer.reduce(reducer, event) assert output.xmin == xmin assert output.ymin == ymin assert output.xmax == xmax assert output.ymax == ymax where [ [:bbox, :long, :lat, :xmin, :ymin, :xmax, :ymax], [[1.0, 2.0, 3.0, 4.0], 4.0, 1.0, 1.0, 1.0, 4.0, 4.0], [[nil, nil, nil, nil], 2.7, 4.7, 2.7, 4.7, 2.7, 4.7] ] end end describe "merge/2" do data_test "will merge the bounding box from two reducers", %{reducer: reducer} do stats1 = %{ "bounding_box" => bbox1 } reducer1 = Aggregate.Reducer.init(reducer, stats1) stats2 = %{ "bounding_box" => bbox2 } reducer2 = Aggregate.Reducer.init(reducer, stats2) output = Aggregate.Reducer.merge(reducer1, reducer2) assert output.xmin == xmin assert output.ymin == ymin assert output.xmax == xmax assert output.ymax == ymax where [ [:bbox1, :bbox2, :xmin, :ymin, :xmax, :ymax], [[1.0, 2.0, 3.0, 4.0], [2.0, 3.0, 4.0, 5.0], 1.0, 2.0, 4.0, 5.0] ] end end end
24.243902
88
0.554829
79e46fa536a4ab12d6801a13bc47428d15b42789
1,996
ex
Elixir
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_uiv1beta3_update_human_review_config_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_uiv1beta3_update_human_review_config_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_uiv1beta3_update_human_review_config_metadata.ex
mcrumm/elixir-google-api
544f22797cec52b3a23dfb6e39117f0018448610
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3UpdateHumanReviewConfigMetadata do @moduledoc """ The long running operation metadata for updating the human review configuration. ## Attributes * `commonMetadata` (*type:* `GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3CommonOperationMetadata.t`, *default:* `nil`) - The basic metadata of the long running operation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :commonMetadata => GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3CommonOperationMetadata.t() } field(:commonMetadata, as: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3CommonOperationMetadata ) end defimpl Poison.Decoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3UpdateHumanReviewConfigMetadata do def decode(value, options) do GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3UpdateHumanReviewConfigMetadata.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3UpdateHumanReviewConfigMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.017544
195
0.778056
79e48e24ad9ad8b1aae866347fccf68c36d98e02
2,364
ex
Elixir
clients/health_care/lib/google_api/health_care/v1beta1/model/parser_config.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/health_care/lib/google_api/health_care/v1beta1/model/parser_config.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/health_care/lib/google_api/health_care/v1beta1/model/parser_config.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.HealthCare.V1beta1.Model.ParserConfig do @moduledoc """ The configuration for the parser. It determines how the server parses the messages. ## Attributes * `allowNullHeader` (*type:* `boolean()`, *default:* `nil`) - Determines whether messages with no header are allowed. * `schema` (*type:* `GoogleApi.HealthCare.V1beta1.Model.SchemaPackage.t`, *default:* `nil`) - Schemas used to parse messages in this store, if schematized parsing is desired. * `segmentTerminator` (*type:* `String.t`, *default:* `nil`) - Byte(s) to use as the segment terminator. If this is unset, '\\r' is used as segment terminator, matching the HL7 version 2 specification. * `version` (*type:* `String.t`, *default:* `nil`) - Immutable. Determines the version of the unschematized parser to be used when `schema` is not given. This field is immutable after store creation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :allowNullHeader => boolean(), :schema => GoogleApi.HealthCare.V1beta1.Model.SchemaPackage.t(), :segmentTerminator => String.t(), :version => String.t() } field(:allowNullHeader) field(:schema, as: GoogleApi.HealthCare.V1beta1.Model.SchemaPackage) field(:segmentTerminator) field(:version) end defimpl Poison.Decoder, for: GoogleApi.HealthCare.V1beta1.Model.ParserConfig do def decode(value, options) do GoogleApi.HealthCare.V1beta1.Model.ParserConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.HealthCare.V1beta1.Model.ParserConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.214286
205
0.730118