hexsha
stringlengths
40
40
size
int64
2
991k
ext
stringclasses
2 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
208
max_stars_repo_name
stringlengths
6
106
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
list
max_stars_count
int64
1
33.5k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
208
max_issues_repo_name
stringlengths
6
106
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
list
max_issues_count
int64
1
16.3k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
208
max_forks_repo_name
stringlengths
6
106
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
list
max_forks_count
int64
1
6.91k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
2
991k
avg_line_length
float64
1
36k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
035ad7c8cb1092e4cd5639961477af0bc71729f2
6,570
ex
Elixir
samples/client/petstore/elixir/lib/swagger_petstore/api/pet.ex
derBiggi/swagger-codegen
99dad052ec506796f3ed13b19364cf827ff0f256
[ "Apache-2.0" ]
14,570
2015-01-01T21:46:46.000Z
2022-03-31T22:28:15.000Z
samples/client/petstore/elixir/lib/swagger_petstore/api/pet.ex
derBiggi/swagger-codegen
99dad052ec506796f3ed13b19364cf827ff0f256
[ "Apache-2.0" ]
9,058
2015-01-08T15:49:17.000Z
2022-03-31T13:10:01.000Z
samples/client/petstore/elixir/lib/swagger_petstore/api/pet.ex
LaudateCorpus1/swagger-codegen
e4f322ce197f1d6a0643de80f9a20bb521480426
[ "Apache-2.0" ]
6,907
2015-01-02T05:29:47.000Z
2022-03-31T00:55:45.000Z
# 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 SwaggerPetstore.Api.Pet do @moduledoc """ API calls for all endpoints tagged `Pet`. """ alias SwaggerPetstore.Connection import SwaggerPetstore.RequestBuilder @doc """ Add a new pet to the store ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - body (Pet): Pet object that needs to be added to the store - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec add_pet(Tesla.Env.client, SwaggerPetstore.Model.Pet.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def add_pet(connection, body, _opts \\ []) do %{} |> method(:post) |> url("/pet") |> add_param(:body, :"body", body) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Deletes a pet ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - pet_id (integer()): Pet id to delete - opts (KeywordList): [optional] Optional parameters - :api_key (String.t): ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec delete_pet(Tesla.Env.client, integer(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def delete_pet(connection, pet_id, opts \\ []) do optional_params = %{ :"api_key" => :headers } %{} |> method(:delete) |> url("/pet/#{pet_id}") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Finds Pets by status Multiple status values can be provided with comma separated strings ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - status ([String.t]): Status values that need to be considered for filter - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, [%Pet{}, ...]} on success {:error, info} on failure """ @spec find_pets_by_status(Tesla.Env.client, list(String.t), keyword()) :: {:ok, list(SwaggerPetstore.Model.Pet.t)} | {:error, Tesla.Env.t} def find_pets_by_status(connection, status, _opts \\ []) do %{} |> method(:get) |> url("/pet/findByStatus") |> add_param(:query, :"status", status) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode([%SwaggerPetstore.Model.Pet{}]) end @doc """ Finds Pets by tags Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - tags ([String.t]): Tags to filter by - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, [%Pet{}, ...]} on success {:error, info} on failure """ @spec find_pets_by_tags(Tesla.Env.client, list(String.t), keyword()) :: {:ok, list(SwaggerPetstore.Model.Pet.t)} | {:error, Tesla.Env.t} def find_pets_by_tags(connection, tags, _opts \\ []) do %{} |> method(:get) |> url("/pet/findByTags") |> add_param(:query, :"tags", tags) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode([%SwaggerPetstore.Model.Pet{}]) end @doc """ Find pet by ID Returns a single pet ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - pet_id (integer()): ID of pet to return - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %SwaggerPetstore.Model.Pet{}} on success {:error, info} on failure """ @spec get_pet_by_id(Tesla.Env.client, integer(), keyword()) :: {:ok, SwaggerPetstore.Model.Pet.t} | {:error, Tesla.Env.t} def get_pet_by_id(connection, pet_id, _opts \\ []) do %{} |> method(:get) |> url("/pet/#{pet_id}") |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%SwaggerPetstore.Model.Pet{}) end @doc """ Update an existing pet ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - body (Pet): Pet object that needs to be added to the store - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec update_pet(Tesla.Env.client, SwaggerPetstore.Model.Pet.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def update_pet(connection, body, _opts \\ []) do %{} |> method(:put) |> url("/pet") |> add_param(:body, :"body", body) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Updates a pet in the store with form data ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - pet_id (integer()): ID of pet that needs to be updated - opts (KeywordList): [optional] Optional parameters - :name (String.t): Updated name of the pet - :status (String.t): Updated status of the pet ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec update_pet_with_form(Tesla.Env.client, integer(), keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def update_pet_with_form(connection, pet_id, opts \\ []) do optional_params = %{ :"name" => :form, :"status" => :form } %{} |> method(:post) |> url("/pet/#{pet_id}") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ uploads an image ## Parameters - connection (SwaggerPetstore.Connection): Connection to server - pet_id (integer()): ID of pet to update - opts (KeywordList): [optional] Optional parameters - :additional_metadata (String.t): Additional data to pass to server - :file (String.t): file to upload ## Returns {:ok, %SwaggerPetstore.Model.ApiResponse{}} on success {:error, info} on failure """ @spec upload_file(Tesla.Env.client, integer(), keyword()) :: {:ok, SwaggerPetstore.Model.ApiResponse.t} | {:error, Tesla.Env.t} def upload_file(connection, pet_id, opts \\ []) do optional_params = %{ :"additionalMetadata" => :form, :"file" => :form } %{} |> method(:post) |> url("/pet/#{pet_id}/uploadImage") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%SwaggerPetstore.Model.ApiResponse{}) end end
27.721519
140
0.630746
035adaae3feaa427e125e3e31b93a1e8eef99249
455
ex
Elixir
lib/booking/permission.ex
mattiaslundberg/booking
469d1469f306b2ab62ce1ee971a825101af6fc7e
[ "MIT" ]
null
null
null
lib/booking/permission.ex
mattiaslundberg/booking
469d1469f306b2ab62ce1ee971a825101af6fc7e
[ "MIT" ]
2
2021-03-10T16:49:07.000Z
2021-05-11T12:50:22.000Z
lib/booking/permission.ex
mattiaslundberg/booking
469d1469f306b2ab62ce1ee971a825101af6fc7e
[ "MIT" ]
null
null
null
defmodule Booking.Permission do use Ecto.Schema import Ecto.Changeset @moduledoc """ Relation to assign user permission to a location """ schema "permissions" do belongs_to :location, Booking.Location belongs_to :user, Booking.Location timestamps() end @doc false def changeset(permission, attrs) do permission |> cast(attrs, [:user_id, :location_id]) |> validate_required([:user_id, :location_id]) end end
19.782609
50
0.701099
035b110e36ca2556edd417a26d2dd96b34ed17a5
389
exs
Elixir
elixir-intro/kode/eksempler/gjenta1.exs
kentdahl/nektar-nuby
03f6624c8bf8de41dd63a0adda5456639b256bc5
[ "MIT" ]
null
null
null
elixir-intro/kode/eksempler/gjenta1.exs
kentdahl/nektar-nuby
03f6624c8bf8de41dd63a0adda5456639b256bc5
[ "MIT" ]
null
null
null
elixir-intro/kode/eksempler/gjenta1.exs
kentdahl/nektar-nuby
03f6624c8bf8de41dd63a0adda5456639b256bc5
[ "MIT" ]
null
null
null
# Løkker implementeres ved rekursjon! defmodule Gjenta do def loop do IO.write "En gutt og ei jente satt i ett tre. \n" IO.write "Så falt gutten ned. \n" svar = IO.gets("Hvem satt igjen? :> ") |> String.strip |> String.downcase if svar == "jenten" do IO.puts "Er du en luring? Eller Bergenser?" else loop # Hale-rekursjon! end end end Gjenta.loop
24.3125
77
0.637532
035b45a764b78a5c433e7d6ec187b0ba3c6b07f2
5,299
exs
Elixir
test/elaxto/query_test.exs
secretworry/elaxto
d4e66dc554f7dfe7786d9caf2dc3def5d231d37f
[ "Apache-2.0" ]
2
2016-12-13T05:51:13.000Z
2017-02-18T18:29:09.000Z
test/elaxto/query_test.exs
secretworry/elaxto
d4e66dc554f7dfe7786d9caf2dc3def5d231d37f
[ "Apache-2.0" ]
null
null
null
test/elaxto/query_test.exs
secretworry/elaxto
d4e66dc554f7dfe7786d9caf2dc3def5d231d37f
[ "Apache-2.0" ]
null
null
null
defmodule Elaxto.QueryTest do use ExUnit.Case import Elaxto.Query describe "query/1" do test "bool query" do assert query( bool( must: term(user: "kimchy"), filter: term(tag: "tech"), must_not: range(age: [from: 10, to: 20]), should: [term(tag: "wow"), term(tag: "elasticsearch")], minimum_should_match: 1, boost: 1.0 ) ) == %{"query"=> %{ "bool" => %{ "must" => %{ "term" => %{ "user" => "kimchy" } }, "filter"=> %{ "term" => %{ "tag" => "tech" } }, "must_not" => %{ "range" => %{ "age" => %{ "from" => 10, "to" => 20 } } }, "should" => [ %{ "term" => %{ "tag" => "wow" } }, %{ "term" => %{ "tag" => "elasticsearch" } } ], "minimum_should_match" => 1, "boost" => 1.0 } } } end test "dis_max query" do assert query( dis_max( tie_breaker: 0.7, boost: 1.2, queries: [term(age: 34), term(age: 35)] ) ) == %{"query"=> %{ "dis_max" => %{ "tie_breaker" => 0.7, "boost" => 1.2, "queries" => [%{ "term" => %{ "age" => 34 } }, %{ "term" => %{ "age" => 35 } }]}}} end test "nested query" do assert query( nested( path: "obj1", score_mode: "avg", query: bool( must: [match("obj1.name": "blue"), range("obj1.count": [gt: 5])] ) ) ) == %{"query"=> %{ "nested" => %{ "path" => "obj1", "score_mode" => "avg", "query" => %{ "bool" => %{ "must" => [ %{ "match" => %{"obj1.name" => "blue"} }, %{ "range" => %{"obj1.count" => %{"gt" => 5}} } ]} } } } } end test "escape complex fields" do query = "query" assert query( multi_match( query: ^query, fields: ^["field0.raw", "field1.raw"] ) ) == %{"query" => %{ "multi_match" => %{ "query" => "query", "fields" => ["field0.raw", "field1.raw"] } }} end end describe "suggest/1" do test "smoke case" do assert suggest( my_suggestion( term(field: "message"), text: "trying out Elasticsearch" ) ) == %{ "suggest" => %{ "my_suggestion" => %{ "text" => "trying out Elasticsearch", "term" => %{ "field" => "message" } } } } end test "should be able to merge maps into maps" do assert suggest( user_suggest: [ prefix: "prefix", complection: [field: "suggest"] ] ) == %{ "suggest" => %{ "user_suggest" => %{ "prefix" => "prefix", "complection" => %{ "field" => "suggest" } } } } end end describe "aggregations/1" do test "smoke case" do assert aggregations( red_products( filter(term(color: "red")), aggs( avg_price(avg(field: "price")) ) ) ) == %{ "aggs" => %{ "red_products" => %{ "filter" => %{ "term" => %{ "color" => "red" } }, "aggs" => %{ "avg_price" => %{ "avg" => %{ "field" => "price"} } } } } } end end describe "sort/1" do test "smoke case" do assert sort(["offer.price": %{mode: "avg", order: "asc", nested_path: "offer", nested_filter: term("offer.color": "blue")}]) == %{ "sort" => [%{ "offer.price" => %{ "mode" => "avg", "order" => "asc", "nested_path" => "offer", "nested_filter" => %{ "term" => %{ "offer.color" => "blue" } } } }] } end end describe "merge/2" do test "should merge without error" do query1 = query( bool( must: term(user: "kimchy") ) ) query2 = query( bool( must: term(user: "remy") ) ) assert merge(query1, query2) == %{"query" => %{"bool" => %{"must" => %{"term" => %{"user" => ["kimchy", "remy"]}}}}} end end describe "&&&/2" do test "should merge without error" do query1 = query( bool( must: term(user: "kimchy") ) ) query2 = query( bool( must: term(user: "remy") ) ) assert (query1 &&& query2) == %{"query" => %{"bool" => %{"must" => %{"term" => %{"user" => ["kimchy", "remy"]}}}}} end end end
23.139738
130
0.351387
035b5ee6cb5ee7a7e2c545ceb618fa1d9cfe852c
1,815
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_test_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_test_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_test_config.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.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1TestConfig do @moduledoc """ Represents configurations for a test case. ## Attributes * `flow` (*type:* `String.t`, *default:* `nil`) - Flow name. If not set, default start flow is assumed. Format: `projects//locations//agents//flows/`. * `trackingParameters` (*type:* `list(String.t)`, *default:* `nil`) - Session parameters to be compared when calculating differences. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :flow => String.t() | nil, :trackingParameters => list(String.t()) | nil } field(:flow) field(:trackingParameters, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1TestConfig do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1TestConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1TestConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.903846
154
0.739394
035ba650eadb4f0b45162f2290c7ea60b1699f4a
555
ex
Elixir
services/fc_identity/lib/fc_identity/events/app_added.ex
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
46
2018-10-13T23:18:13.000Z
2021-08-07T07:46:51.000Z
services/fc_identity/lib/fc_identity/events/app_added.ex
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
25
2018-10-14T00:56:07.000Z
2019-12-23T19:41:02.000Z
services/fc_identity/lib/fc_identity/events/app_added.ex
fleadope/freshcom
8d5944befaa6eea8d31e5f5995939be2a1a44262
[ "BSD-3-Clause" ]
5
2018-12-16T04:39:51.000Z
2020-10-01T12:17:03.000Z
defmodule FCIdentity.AppAdded do use TypedStruct @derive Jason.Encoder @version 1 typedstruct do field :__version__, integer(), default: @version field :request_id, String.t() field :requester_id, String.t() field :requester_type, String.t() field :requester_role, String.t() field :client_id, String.t() field :client_type, String.t() field :account_id, String.t() field :app_id, String.t() field :status, String.t(), default: "active" field :type, String.t() field :name, String.t() end end
23.125
52
0.666667
035bc00deb192ee7286e0005ca19d731fe225d33
867
exs
Elixir
test/grizzly/zwave/commands/multi_channel_aggregated_members_get_test.exs
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
76
2019-09-04T16:56:58.000Z
2022-03-29T06:54:36.000Z
test/grizzly/zwave/commands/multi_channel_aggregated_members_get_test.exs
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
124
2019-09-05T14:01:24.000Z
2022-02-28T22:58:14.000Z
test/grizzly/zwave/commands/multi_channel_aggregated_members_get_test.exs
jellybob/grizzly
290bee04cb16acbb9dc996925f5c501697b7ac94
[ "Apache-2.0" ]
10
2019-10-23T19:25:45.000Z
2021-11-17T13:21:20.000Z
defmodule Grizzly.ZWave.Commands.MultiChannelAggregatedMembersGetTest do use ExUnit.Case, async: true alias Grizzly.ZWave.Commands.MultiChannelAggregatedMembersGet test "creates the command and validates params" do params = [aggregated_end_point: 1] {:ok, _command} = MultiChannelAggregatedMembersGet.new(params) end test "encodes params correctly" do params = [aggregated_end_point: 1] {:ok, command} = MultiChannelAggregatedMembersGet.new(params) expected_binary = <<0x00::size(1), 0x01::size(7)>> assert expected_binary == MultiChannelAggregatedMembersGet.encode_params(command) end test "decodes params correctly" do params_binary = <<0x00::size(1), 0x01::size(7)>> {:ok, params} = MultiChannelAggregatedMembersGet.decode_params(params_binary) assert Keyword.get(params, :aggregated_end_point) == 1 end end
36.125
85
0.756632
035c074998ca891742a5a2d4cf4848953480b0b0
760
ex
Elixir
lib/omise/bank_account.ex
keeratita/omise-elixir
2c89fe9ca60a8c2a8f5e523e7f7a6d51a68c0ed6
[ "MIT" ]
12
2016-09-10T16:17:32.000Z
2020-06-04T01:35:54.000Z
lib/omise/bank_account.ex
keeratita/omise-elixir
2c89fe9ca60a8c2a8f5e523e7f7a6d51a68c0ed6
[ "MIT" ]
8
2016-09-19T05:36:27.000Z
2020-09-14T08:46:06.000Z
lib/omise/bank_account.ex
keeratita/omise-elixir
2c89fe9ca60a8c2a8f5e523e7f7a6d51a68c0ed6
[ "MIT" ]
10
2016-07-19T05:03:01.000Z
2021-02-08T03:20:54.000Z
defmodule Omise.BankAccount do @moduledoc ~S""" Omise Bank Account Struct. <https://www.omise.co/bank-account-api> """ defstruct object: "bank_account", brand: nil, bank_code: nil, branch_code: nil, account_type: nil, last_digits: nil, name: nil, created: nil, deleted: false, type: nil @type t :: %__MODULE__{ object: String.t(), brand: String.t(), bank_code: String.t(), branch_code: String.t(), account_type: String.t(), last_digits: String.t(), name: String.t(), created: String.t(), deleted: boolean, type: String.t() } end
23.75
41
0.497368
035c4ce8751bf874a5723b6b187e95173a28a861
2,380
ex
Elixir
deps/ecto/lib/ecto/query/builder/dynamic.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/ecto/lib/ecto/query/builder/dynamic.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
deps/ecto/lib/ecto/query/builder/dynamic.ex
rpillar/Top5_Elixir
9c450d2e9b291108ff1465dc066dfe442dbca822
[ "MIT" ]
null
null
null
import Kernel, except: [apply: 2] defmodule Ecto.Query.Builder.Dynamic do @moduledoc false alias Ecto.Query.Builder @doc """ Builds a dynamic expression. """ @spec build([Macro.t], Macro.t, Macro.Env.t) :: Macro.t def build(binding, expr, env) do {query, vars} = Builder.escape_binding(quote(do: query), binding, env) {expr, {params, :acc}} = Builder.escape(expr, :any, {[], :acc}, vars, env) params = Builder.escape_params(params) quote do %Ecto.Query.DynamicExpr{fun: fn query -> _ = unquote(query) {unquote(expr), unquote(params)} end, binding: unquote(Macro.escape(binding)), file: unquote(env.file), line: unquote(env.line)} end end @doc """ Expands a dynamic expression for insertion into the given query. """ def fully_expand(query, %{file: file, line: line, binding: binding} = dynamic) do {expr, {binding, params, _count}} = expand(query, dynamic, {binding, [], 0}) {expr, binding, Enum.reverse(params), file, line} end @doc """ Expands a dynamic expression as part of an existing expression. Any dynamic expression parameter is prepended and the parameters list is not reversed. This is useful when the dynamic expression is given in the middle of an expression. """ def partially_expand(query, %{binding: binding} = dynamic, params, count) do {expr, {_binding, params, count}} = expand(query, dynamic, {binding, params, count}) {expr, params, count} end defp expand(query, %{fun: fun}, {binding, params, count}) do {dynamic_expr, dynamic_params} = fun.(query) Macro.postwalk(dynamic_expr, {binding, params, count}, fn {:^, meta, [ix]}, {binding, params, count} -> case Enum.fetch!(dynamic_params, ix) do {%Ecto.Query.DynamicExpr{binding: new_binding} = dynamic, _} -> binding = if length(new_binding) > length(binding), do: new_binding, else: binding expand(query, dynamic, {binding, params, count}) param -> {{:^, meta, [count]}, {binding, [param | params], count + 1}} end expr, acc -> {expr, acc} end) end end
36.060606
95
0.578992
035c633409fcb27d9de111badd8494d7eaa5f513
1,357
exs
Elixir
mix.exs
linjunpop/geetest
91f21e01958e68d6d423c426ccf5c88d1f29342f
[ "MIT" ]
null
null
null
mix.exs
linjunpop/geetest
91f21e01958e68d6d423c426ccf5c88d1f29342f
[ "MIT" ]
null
null
null
mix.exs
linjunpop/geetest
91f21e01958e68d6d423c426ccf5c88d1f29342f
[ "MIT" ]
null
null
null
defmodule Geetest.Mixfile do use Mix.Project def project do [app: :geetest, version: "0.0.1", name: "Geetest", description: description, source_url: "https://github.com/linjunpop/geetest", homepage_url: "https://github.com/linjunpop/geetest", elixir: "~> 1.2", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, package: package, deps: deps, docs: [ extras: ["README.md", ] ] ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger, :httpoison]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [ {:httpoison, "~> 0.8"}, {:earmark, "~> 0.1", only: :dev}, {:ex_doc, "~> 0.11", only: :dev} ] end defp description do "Elixir toolkit for Geetest" end defp package do [ name: :geetest, files: ["lib", "mix.exs", "README*", "LICENSE"], maintainers: ["Jun Lin"], licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/linjunpop/geetest" } ] end end
21.887097
77
0.568165
035c8ebee5d7c03ce180f8831466f5157794ff7c
3,010
exs
Elixir
day_21/solution.exs
polarfoxgirl/advent-of-code-2020
549794d5aefca5d413b97a29244b228b470383bb
[ "Unlicense" ]
null
null
null
day_21/solution.exs
polarfoxgirl/advent-of-code-2020
549794d5aefca5d413b97a29244b228b470383bb
[ "Unlicense" ]
null
null
null
day_21/solution.exs
polarfoxgirl/advent-of-code-2020
549794d5aefca5d413b97a29244b228b470383bb
[ "Unlicense" ]
null
null
null
{:ok, input} = File.read("input") defmodule AllergenAssessment do def parse_line(line) do regex = ~r/(.*) \(contains ([^\)]+)\)/ [ingredient_str, allergen_str] = Regex.run(regex, line, capture: :all_but_first) ingredients = String.split(ingredient_str) |> MapSet.new() allergens = String.split(allergen_str, ", ") {ingredients, allergens} end def update_suspect_map(product, suspect_map) do {ingredients, allergens} = product process_allergen = fn allergen, acc_map -> if Map.has_key?(acc_map, allergen) do current_set = Map.fetch!(acc_map, allergen) updated_set = MapSet.intersection(current_set, ingredients) Map.replace!(acc_map, allergen, updated_set) else Map.put_new(acc_map, allergen, ingredients) end end Enum.reduce(allergens, suspect_map, process_allergen) end def try_reduce_map(suspect_map, known_allergens) do new_known_allergens = suspect_map |> Enum.filter(fn {_a, ingrs} -> Enum.count(ingrs) == 1 end) |> Enum.map(fn {a, ingrs} -> {a, Enum.at(ingrs, 0)} end) |> Map.new() if Enum.empty?(new_known_allergens) do {suspect_map, known_allergens} else new_ided_ingredients = MapSet.new(Map.values(new_known_allergens)) updated_suspect_map = suspect_map |> Enum.reject(fn {a, _} -> Map.has_key?(new_known_allergens, a) end) |> Enum.map(fn {a, ingrs} -> {a, MapSet.difference(ingrs, new_ided_ingredients)} end) |> Map.new() updated_known_allergens = Map.merge(known_allergens, new_known_allergens) try_reduce_map(updated_suspect_map, updated_known_allergens) end end def solve(input) do products = input |> String.split("\n") |> Enum.map(&parse_line/1) IO.puts("Input count: #{Enum.count(products)}") # First find indgredients that are present in all products # where the allegen is listed. suspect_map = Enum.reduce(products, %{}, &update_suspect_map/2) # Then we reduce suspect map as much as possible {reduced_suspect_map, known_allergens} = try_reduce_map(suspect_map, %{}) IO.puts("Reduced to #{Enum.count(reduced_suspect_map)} unknown and #{Enum.count(known_allergens)} known allergens") all_ingredients = products |> Enum.map(fn {ingrs, _a} -> ingrs end) |> Enum.reduce(&MapSet.union/2) known_allergen_ingredients = Map.values(known_allergens) |> MapSet.new() known_non_allergens = MapSet.difference(all_ingredients, known_allergen_ingredients) IO.puts("Found #{Enum.count(known_non_allergens)} non-allergen ingredients") result = products |> Enum.map(fn {ingrs, _a} -> Enum.count(ingrs, &MapSet.member?(known_non_allergens, &1)) end) |> Enum.sum() IO.puts("Result: #{result}") result_2 = known_allergens |> Enum.sort_by(fn {a, _i} -> a end) |> Enum.map(fn {_a, i} -> i end) |> Enum.join(",") IO.puts("Result 2: #{result_2}") end end AllergenAssessment.solve(input)
33.820225
119
0.670432
035c9d8a143ac6caa56f189d9dc3087f5b648a6a
1,217
exs
Elixir
13_organizing_a_project/issues/config/config.exs
gshaw/elixir
8d2ff9b883242696008b35a715b2f13a8291772d
[ "MIT" ]
1
2016-10-19T20:44:37.000Z
2016-10-19T20:44:37.000Z
13_organizing_a_project/issues/config/config.exs
gshaw/elixir
8d2ff9b883242696008b35a715b2f13a8291772d
[ "MIT" ]
null
null
null
13_organizing_a_project/issues/config/config.exs
gshaw/elixir
8d2ff9b883242696008b35a715b2f13a8291772d
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :issues, key: :value # # And access this configuration in your application as: # # Application.get_env(:issues, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # config :issues, github_url: "https://api.github.com" config :logger, compile_time_purge_level: :info # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
35.794118
73
0.752671
035ca520e47a3fa3ece38d93ed6aab24e268dc83
641
ex
Elixir
lib/exchema/types/optional.ex
bamorim/exchema
4e11136fae6092e0e64870b455fd6a68cf36603c
[ "Apache-2.0" ]
21
2018-01-06T22:33:20.000Z
2020-02-07T18:49:22.000Z
lib/exchema/types/optional.ex
bamorim/exchema
4e11136fae6092e0e64870b455fd6a68cf36603c
[ "Apache-2.0" ]
5
2018-02-15T16:39:14.000Z
2018-11-30T21:06:08.000Z
lib/exchema/types/optional.ex
bamorim/exchema
4e11136fae6092e0e64870b455fd6a68cf36603c
[ "Apache-2.0" ]
4
2018-05-21T21:26:27.000Z
2019-04-17T16:45:14.000Z
defmodule Exchema.Types.Optional do @moduledoc """ Represents a value which can be nil You can specify the type when it is not nil, so if you want an integer that can be nil you can represent it with `{Exchema.Types.Optional, Exchema.Types.Integer}` With that, either `nil` and `1` are valid values, however `"this"` is not a valid one. """ @doc false def __type__({type}) do {:ref, :any, [{{__MODULE__, :pred}, type}]} end @doc false def pred(nil, _), do: :ok def pred(val, type) do case Exchema.errors(val, type) do [] -> :ok errors -> {:error, errors} end end end
22.103448
64
0.624025
035d9085154607f76d7635dcdfbf352de52e8c22
1,060
ex
Elixir
test/support/conn_case.ex
tfwright/phoenix_live_vue_test
f560401c28fdf0132c33e4943a80357110d16160
[ "MIT" ]
null
null
null
test/support/conn_case.ex
tfwright/phoenix_live_vue_test
f560401c28fdf0132c33e4943a80357110d16160
[ "MIT" ]
1
2021-05-11T13:17:32.000Z
2021-05-11T13:17:32.000Z
test/support/conn_case.ex
tfwright/phoenix_live_vue_test
f560401c28fdf0132c33e4943a80357110d16160
[ "MIT" ]
null
null
null
defmodule PhoenixLiveVueTestWeb.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also import other functionality to make it easier to build common data structures and query the data layer. Finally, if the test case interacts with the database, we enable the SQL sandbox, so changes done to the database are reverted at the end of every test. If you are using PostgreSQL, you can even run database tests asynchronously by setting `use PhoenixLiveVueTestWeb.ConnCase, async: true`, although this option is not recommended for other databases. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias PhoenixLiveVueTestWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint PhoenixLiveVueTestWeb.Endpoint end end setup _tags do {:ok, conn: Phoenix.ConnTest.build_conn()} end end
30.285714
72
0.748113
035da60edabfe471b341ead23ac7ce80040e783e
143
ex
Elixir
lib/bootstrap_ex.ex
MortadaAK/bootstrap_ex
ee62af4e43978e801bd7f4bbea7e6e0e3e80c9d6
[ "MIT" ]
null
null
null
lib/bootstrap_ex.ex
MortadaAK/bootstrap_ex
ee62af4e43978e801bd7f4bbea7e6e0e3e80c9d6
[ "MIT" ]
null
null
null
lib/bootstrap_ex.ex
MortadaAK/bootstrap_ex
ee62af4e43978e801bd7f4bbea7e6e0e3e80c9d6
[ "MIT" ]
null
null
null
defmodule BootstrapEx do require BootstrapEx.Helper require BootstrapEx.Alert require BootstrapEx.Badge require BootstrapEx.Breadcrumb end
20.428571
31
0.86014
035dadb9acad2d38627fa03044de1cda410dc9ce
3,811
exs
Elixir
apps/mcam_server_web/test/mcam_server_web/live/unregistered_cameras_live_test.exs
paulanthonywilson/mcam
df9c5aaae00b568749dff22613636f5cb92f905a
[ "MIT" ]
null
null
null
apps/mcam_server_web/test/mcam_server_web/live/unregistered_cameras_live_test.exs
paulanthonywilson/mcam
df9c5aaae00b568749dff22613636f5cb92f905a
[ "MIT" ]
8
2020-11-16T09:59:12.000Z
2020-11-16T10:13:07.000Z
apps/mcam_server_web/test/mcam_server_web/live/unregistered_cameras_live_test.exs
paulanthonywilson/mcam
df9c5aaae00b568749dff22613636f5cb92f905a
[ "MIT" ]
null
null
null
defmodule McamServerWeb.UnregisteredCamerasLiveTest do use McamServerWeb.ConnCase, async: true import McamServer.AccountsFixtures import Phoenix.ConnTest import Phoenix.LiveViewTest alias McamServer.UnregisteredCameras import Common, only: [wait_until_equals: 2] import McamServer.UnregisteredCamerasSupport setup_all do {:ok, counter} = Agent.start_link(fn -> 2 end) {:ok, counter: counter} end setup %{conn: conn, counter: counter} do count = Agent.get_and_update(counter, fn i -> {i, i + 1} end) # Modify the remote ip to avoid cross-contamination between tests # (The live view only lists cameras from the remote ip) remote_ip = {157, 35, 2, count} user = user_fixture() :ok = UnregisteredCameras.subscribe() conn = conn |> log_in_user(user) |> Map.put(:remote_ip, remote_ip) {:ok, conn: conn, user: user, remote_ip: remote_ip} end test "no registered cameras", %{conn: conn} do {:ok, _view, html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) assert html =~ "No unregistered cameras" end test "Lists registered cameras", %{conn: conn, remote_ip: remote_ip} do UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-bb12", "10.20.1.23"}) {:ok, _view, html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) assert html =~ "nerves-bb12" assert html =~ "http://10.20.1.23:4000" end test "adds registered cameras when one arrives on the scene", %{ conn: conn, remote_ip: remote_ip } do UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-c3p0", "10.20.1.30"}) {:ok, view, _html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-bb12", "10.20.1.23"}) :sys.get_state(UnregisteredCameras) html = render(view) assert html =~ "nerves-bb12" assert html =~ "http://10.20.1.23:4000" assert html =~ "http://10.20.1.30:4000" end test "updates ammend the existing camera listing rather than duplicating it", %{ conn: conn, remote_ip: remote_ip } do UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-bb12", "10.20.1.23"}) {:ok, view, _html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-bb12", "10.20.1.24"}) :sys.get_state(UnregisteredCameras) html = render(view) assert html =~ "http://10.20.1.24:4000" refute html =~ "http://10.20.1.23:4000" end test "does not list new cameras from other ips", %{conn: conn} do {:ok, view, _html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) UnregisteredCameras.record_camera_from_ip({{192, 168, 1, 1}, "nerves-bb12", "10.20.1.23"}) :sys.get_state(UnregisteredCameras) html = render(view) refute html =~ "nerves-bb12" end test "camera updated to be on a different remote ip is removed", %{ conn: conn, remote_ip: remote_ip } do UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-bb12", "10.20.1.23"}) {:ok, view, _html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) UnregisteredCameras.record_camera_from_ip({{192, 168, 1, 1}, "nerves-bb12", "10.20.1.23"}) :sys.get_state(UnregisteredCameras) html = render(view) refute html =~ "nerves-bb12" end test "camera expires", %{conn: conn, remote_ip: remote_ip} do UnregisteredCameras.record_camera_from_ip({remote_ip, "nerves-bb12", "10.20.1.23"}) {:ok, view, _html} = live(conn, Routes.unregistered_cameras_path(conn, :index)) expire_camera("nerves-bb12") wait_until_equals(false, fn -> render(view) =~ "nerves-bb12" end) html = render(view) refute html =~ "nerves-bb12" end end
34.333333
94
0.688533
035dbeff2c3e5ccd2110f1992dd38f00f0cc1b51
283
ex
Elixir
lib/langue/formatter/xliff_1_2/xliff_1_2.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
806
2018-04-07T20:40:33.000Z
2022-03-30T01:39:57.000Z
lib/langue/formatter/xliff_1_2/xliff_1_2.ex
isshindev/accent
ae4c13139b0a0dfd64ff536b94c940a4e2862150
[ "BSD-3-Clause" ]
194
2018-04-07T13:49:37.000Z
2022-03-30T19:58:45.000Z
lib/langue/formatter/xliff_1_2/xliff_1_2.ex
doc-ai/accent
e337e16f3658cc0728364f952c0d9c13710ebb06
[ "BSD-3-Clause" ]
89
2018-04-09T13:55:49.000Z
2022-03-24T07:09:31.000Z
defmodule Langue.Formatter.XLIFF12 do @behaviour Langue.Formatter alias Langue.Formatter.XLIFF12.{Parser, Serializer} def name, do: "xliff_1_2" def placeholder_regex, do: :not_supported defdelegate parse(map), to: Parser defdelegate serialize(map), to: Serializer end
23.583333
53
0.770318
035dc6a7b57af0cff5504bf808398fbfd5014d6b
1,001
ex
Elixir
test/support/data_case.ex
topherhunt/reassembling-the-line
c6823b3394ee98d9b0149fa3d09448928ac5c0db
[ "MIT" ]
1
2019-04-27T15:39:20.000Z
2019-04-27T15:39:20.000Z
test/support/data_case.ex
topherhunt/reassembling-the-line
c6823b3394ee98d9b0149fa3d09448928ac5c0db
[ "MIT" ]
11
2020-07-16T11:40:53.000Z
2021-08-16T07:03:33.000Z
test/support/data_case.ex
topherhunt/reassembling-the-line
c6823b3394ee98d9b0149fa3d09448928ac5c0db
[ "MIT" ]
null
null
null
defmodule RTL.DataCase do @moduledoc """ This module defines the test case to be used by model tests. You may define functions here to be used as helpers in your model tests. See `errors_on/2`'s definition as reference. 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 RTL.Factory import RTL.DataCase import RTL.DataHelpers import RTL.EmailHelpers import RTL.ValidationHelpers alias RTL.{Repo, Factory, Accounts} alias RTL.Accounts.User alias RTL.Helpers, as: H end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(RTL.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(RTL.Repo, {:shared, self()}) end RTL.Factory.empty_database() :ok end end
23.833333
65
0.692308
035dd3cb894219998530f3a23313d62f5664ee1b
4,153
ex
Elixir
lib/ssh_client_key_api.ex
sequin-io/ssh_client_key_api
59b9fd80c0ee44e0db86a224f0006c19b1159531
[ "MIT" ]
null
null
null
lib/ssh_client_key_api.ex
sequin-io/ssh_client_key_api
59b9fd80c0ee44e0db86a224f0006c19b1159531
[ "MIT" ]
null
null
null
lib/ssh_client_key_api.ex
sequin-io/ssh_client_key_api
59b9fd80c0ee44e0db86a224f0006c19b1159531
[ "MIT" ]
null
null
null
defmodule SSHClientKeyAPI do @external_resource "README.md" @moduledoc "README.md" |> File.read!() |> String.split("<!-- MDOC !-->") |> Enum.fetch!(1) alias SSHClientKeyAPI.KeyError @behaviour :ssh_client_key_api @key_algorithms :ssh.default_algorithms()[:public_key] @doc """ Returns a tuple suitable for passing the `SSHKit.SSH.connect/2` as the `key_cb` option. ## Options * `:identity` - [`binary`] providing the ssh key (required) * `:known_hosts` - [`IO.device`] providing the known hosts list. If providing a File IO, it should have been opened in `:write` mode (required) * `:silently_accept_hosts` - [`boolean`] silently accept and add new hosts to the known hosts. By default only known hosts will be accepted. * `:passphrase` - [`binary`] passphrase if your key is protected (optional) By default it will use the the files found in `System.user_home!/0`. ## Examples key = File.read!("path/to/keyfile") known_hosts = File.open!("path/to/known_hosts") cb = SSHClientKeyAPI.with_options(identity: key, known_hosts: known_hosts) SSHKit.SSH.connect("example.com", key_cb: cb) """ @spec with_options(opts :: list) :: {atom, list} def with_options(opts \\ []) do opts = with_defaults(opts) opts = if opts[:known_hosts] do Keyword.put(opts, :known_hosts_data, IO.binread(opts[:known_hosts], :all)) else opts end {__MODULE__, opts} end def add_host_key(hostname, key, opts) do case silently_accept_hosts(opts) do true -> if known_hosts = known_hosts_data(opts) do :ssh_file.decode(known_hosts, :known_hosts) |> (fn decoded -> decoded ++ [{key, [{:hostnames, [hostname]}]}] end).() |> :ssh_file.encode(:known_hosts) |> (fn encoded -> IO.binwrite(known_hosts(opts), encoded) end).() else :ok end _ -> message = """ Error: unknown fingerprint found for #{inspect(hostname)} #{inspect(key)}. You either need to add a known good fingerprint to your known hosts file for this host, *or* pass the silently_accept_hosts option to your client key callback """ {:error, message} end end def is_host_key(key, hostname, alg, opts) when alg in @key_algorithms do silently_accept_hosts(opts) || opts |> known_hosts_data |> to_string |> :ssh_file.decode(:known_hosts) |> has_fingerprint(key, hostname) end def is_host_key(_, _, alg, _) do IO.puts("unsupported host key algorithm #{inspect(alg)}") false end def user_key(_alg, opts) do opts |> identity |> to_string |> :public_key.pem_decode() |> List.first() |> decode_pem_entry(passphrase(opts)) end defp decode_pem_entry(nil, _phrase) do raise KeyError, {:unsupported_algorithm, :unknown} end defp decode_pem_entry({_type, _data, :not_encrypted} = entry, _) do {:ok, :public_key.pem_entry_decode(entry)} end defp decode_pem_entry({_type, _data, {alg, _}}, nil) do raise KeyError, {:passphrase_required, alg} end defp decode_pem_entry({_type, _data, {alg, _}} = entry, phrase) do {:ok, :public_key.pem_entry_decode(entry, phrase)} rescue _e in MatchError -> # credo:disable-for-next-line Credo.Check.Warning.RaiseInsideRescue raise KeyError, {:incorrect_passphrase, alg} end defp identity(opts) do cb_opts(opts)[:identity] end defp silently_accept_hosts(opts) do cb_opts(opts)[:silently_accept_hosts] end defp known_hosts(opts) do cb_opts(opts)[:known_hosts] end defp known_hosts_data(opts) do cb_opts(opts)[:known_hosts_data] end defp passphrase(opts) do cb_opts(opts)[:passphrase] end defp cb_opts(opts) do opts[:key_cb_private] end defp has_fingerprint(fingerprints, key, hostname) do Enum.any?(fingerprints, fn {k, v} -> k == key && Enum.member?(v[:hostnames], hostname) end) end defp with_defaults(opts) do opts |> Keyword.put_new(:silently_accept_hosts, false) end end
27.503311
95
0.650373
035dda38eeadba57f684ca37d671b0de9e6558fe
179
exs
Elixir
priv/repo/migrations/20160412184358_create_post.exs
judas-christ/final-forum
c42f0f1a2913eb2373353779ced9b4566183422b
[ "MIT" ]
null
null
null
priv/repo/migrations/20160412184358_create_post.exs
judas-christ/final-forum
c42f0f1a2913eb2373353779ced9b4566183422b
[ "MIT" ]
null
null
null
priv/repo/migrations/20160412184358_create_post.exs
judas-christ/final-forum
c42f0f1a2913eb2373353779ced9b4566183422b
[ "MIT" ]
null
null
null
defmodule FinalForum.Repo.Migrations.CreatePost do use Ecto.Migration def change do create table(:posts) do add :body, :string timestamps end end end
13.769231
50
0.681564
035de2083a0074e6d0b37ba8df35c512c2d8024c
1,208
ex
Elixir
lib/ex_raja_ongkir/request.ex
giraphme/ex_raja_ongkir
6c7e7a811879d0adfd7eb574d0bbc665f1b7084d
[ "MIT" ]
null
null
null
lib/ex_raja_ongkir/request.ex
giraphme/ex_raja_ongkir
6c7e7a811879d0adfd7eb574d0bbc665f1b7084d
[ "MIT" ]
1
2018-04-24T08:27:20.000Z
2018-04-24T08:27:20.000Z
lib/ex_raja_ongkir/request.ex
giraphme/ex_raja_ongkir
6c7e7a811879d0adfd7eb574d0bbc665f1b7084d
[ "MIT" ]
null
null
null
defmodule ExRajaOngkir.Request do use HTTPotion.Base def process_url(url) do ExRajaOngkir.base_url() <> url end def process_request_headers(headers) do headers |> Keyword.put(:key, ExRajaOngkir.api_key()) end def process_response_body(body) do body |> Jason.decode!() end def cast_to(response, module) do response |> take_result() |> case do {:ok, result} -> {:ok, into(result, module)} {:error, reason} -> {:error, reason} end end def take_result(%HTTPotion.Response{ body: %{"rajaongkir" => %{"results" => result, "status" => %{"code" => 200}}} }) do {:ok, result} end def take_result(%{ body: %{"rajaongkir" => %{"status" => %{"code" => code, "description" => description}}} }) do {:error, "#{description} (#{code})"} end def take_result(_) do {:error, "Request failure"} end def into(result, module) when is_list(result) do Enum.map(result, &into(&1, module)) end def into(result, module) when is_map(result) do struct( module, module.scheme |> Enum.map(fn {key, result_key} -> {key, result[result_key]} end) |> Enum.into(%{}) ) end end
21.963636
95
0.593543
035df157cd15828f90f097e07d84b9fae3ec1341
2,397
ex
Elixir
lib/ticketo_web/resolvers/session_resolver.ex
alejandronanez/phoenix-absinthe-auth-template
e4e72f52247cb4c880ddc058beaa7b5eecb68980
[ "MIT" ]
8
2020-06-25T03:15:06.000Z
2021-12-10T10:52:26.000Z
lib/ticketo_web/resolvers/session_resolver.ex
alejandronanez/phoenix-absinthe-auth-template
e4e72f52247cb4c880ddc058beaa7b5eecb68980
[ "MIT" ]
null
null
null
lib/ticketo_web/resolvers/session_resolver.ex
alejandronanez/phoenix-absinthe-auth-template
e4e72f52247cb4c880ddc058beaa7b5eecb68980
[ "MIT" ]
null
null
null
defmodule TicketoWeb.Resolvers.SessionResolver do @auth_error "Something went wrong" @logged_out_map %{message: "Logged out"} @moduledoc """ Session Resolver. Takes care of: - Login users Should take care of: - Refresh tokens - Register users """ alias Ticketo.Accounts alias Ticketo.Tokens.Tokens def login_user(_, %{input: input}, _) do input |> Accounts.authenticate() |> get_new_session() end def logout_user(_, _, ctx) do current_user = ctx |> get_current_user_id_from_context() |> Accounts.get_user() |> Accounts.update_token(%{refresh_token: ""}) case current_user do {:error, _reason} -> {:error, @auth_error} {:ok, _user} -> {:ok, @logged_out_map} end end defp get_current_user_id_from_context(ctx) do ctx |> Map.get(:context, %{}) |> Map.get(:current_user, %{}) |> Map.get(:id, -1) end def refresh_token(_, _input, ctx) do with token <- ctx |> Map.get(:context) |> Map.get(:auth_token), {:ok, claims} <- Tokens.decode_token(token), {:ok, user_from_claims} <- Tokens.get_resource_from_claims(claims), user <- Accounts.get_user(user_from_claims.id), {:ok, result} <- get_new_session({:ok, user}) do case compare_tokens(user.refresh_token, token) do true -> {:ok, result} false -> {:error, @auth_error} end else _ -> {:error, @auth_error} end end defp compare_tokens(user_refresh_token, cookie_refresh_token) when is_nil(user_refresh_token) or is_nil(cookie_refresh_token) do false end defp compare_tokens(user_refresh_token, cookie_refresh_token) do String.equivalent?(user_refresh_token, cookie_refresh_token) end defp get_new_session(:error) do {:error, @auth_error} end defp get_new_session({:ok, user}) do with {:ok, jwt_token, _} <- Tokens.sign_token(user, %{type: "access"}), {:ok, refresh_token, _} <- Tokens.sign_token(user, %{type: "refresh"}), {:ok, _updated_user} <- Accounts.update_token(user, %{refresh_token: refresh_token}) do {:ok, %{ token: jwt_token, refresh_token: refresh_token, token_expiry: Tokens.get_token_expiry(), user: Map.take(user, [:id, :email]) }} else {:error, _reason} -> {:error, @auth_error} end end end
27.238636
96
0.631623
035e2c6c81a72fbeba67ea475c30d355ab5be187
2,152
ex
Elixir
clients/app_engine/lib/google_api/app_engine/v1/deserializer.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/app_engine/lib/google_api/app_engine/v1/deserializer.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/app_engine/lib/google_api/app_engine/v1/deserializer.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
1
2018-07-28T20:50:50.000Z
2018-07-28T20:50:50.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AppEngine.V1.Deserializer do @moduledoc """ Helper functions for deserializing responses into models """ @doc """ Update the provided model with a deserialization of a nested value """ @spec deserialize(struct(), :atom, :atom, struct(), keyword()) :: struct() def deserialize(model, _field, :list, nil, _options), do: model def deserialize(model, field, :list, mod, options) do model |> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: [struct(mod)]])))) end def deserialize(model, field, :struct, mod, options) do model |> Map.update!(field, &(Poison.Decode.decode(&1, Keyword.merge(options, [as: struct(mod)])))) end def deserialize(model, _field, :map, nil, _options), do: model def deserialize(model, field, :map, mod, options) do model |> Map.update!(field, &(Map.new(&1, fn {key, val} -> {key, Poison.Decode.decode(val, Keyword.merge(options, [as: struct(mod)]))} end))) end def deserialize(model, field, :date, _, _options) do case DateTime.from_iso8601(Map.get(model, field)) do {:ok, datetime} -> Map.put(model, field, datetime) _ -> model end end def serialize_non_nil(model, options) do model |> Map.from_struct |> Enum.filter(fn {_k, v} -> v != nil end) |> Enum.into(%{}) |> Poison.Encoder.encode(options) end end
35.866667
139
0.688197
035e38bd8a1eb0e0170dc3f7ef92bdd2bef6a905
1,946
ex
Elixir
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1beta2__explicit_content_frame.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1beta2__explicit_content_frame.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/video_intelligence/lib/google_api/video_intelligence/v1/model/google_cloud_videointelligence_v1beta2__explicit_content_frame.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.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame do @moduledoc """ Video frame level annotation results for explicit content. ## Attributes * `pornographyLikelihood` (*type:* `String.t`, *default:* `nil`) - Likelihood of the pornography content.. * `timeOffset` (*type:* `String.t`, *default:* `nil`) - Time-offset, relative to the beginning of the video, corresponding to the video frame for this location. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :pornographyLikelihood => String.t(), :timeOffset => String.t() } field(:pornographyLikelihood) field(:timeOffset) end defimpl Poison.Decoder, for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame do def decode(value, options) do GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.VideoIntelligence.V1.Model.GoogleCloudVideointelligenceV1beta2_ExplicitContentFrame do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.551724
133
0.749229
035e7348392ac62bab37ed0c3db48359424ee52f
4,515
ex
Elixir
lib/grapple/hook.ex
bka9/grapple
0506220256e8d7e99943648aef9300d36e045d2d
[ "MIT" ]
null
null
null
lib/grapple/hook.ex
bka9/grapple
0506220256e8d7e99943648aef9300d36e045d2d
[ "MIT" ]
null
null
null
lib/grapple/hook.ex
bka9/grapple
0506220256e8d7e99943648aef9300d36e045d2d
[ "MIT" ]
null
null
null
defmodule Grapple.Hook do @moduledoc false use GenServer @http Application.get_env(:grapple, :http, HTTPoison) @enforce_keys [:url] defstruct [ :url, :api_key, :owner, :life, :ref, :interval, method: "GET", body: %{}, headers: [], options: [], query: %{} ] # API def start_link(hook) do GenServer.start_link(__MODULE__, hook) end def get_info(pid) do GenServer.call(pid, :get_info) end def get_responses(pid) do GenServer.call(pid, :get_responses) end def start_polling(pid) do GenServer.call(pid, :start_polling) end def start_polling(pid, interval) when is_integer(interval) do GenServer.call(pid, {:start_polling, interval}) end def broadcast(pid) do GenServer.cast(pid, :broadcast) end def broadcast(pid, body) when is_nil(body) do GenServer.cast(pid, :broadcast) end def broadcast(pid, body) do GenServer.cast(pid, {:broadcast, body}) end def stop_polling(pid) do GenServer.cast(pid, :stop_polling) end # Callbacks def init(%{interval: interval} = hook) when is_integer(interval) do {:ok, tref} = start_timer(interval) {:ok, %{responses: [], hook: hook, tref: tref}} end def init(hook) do {:ok, %{responses: [], hook: hook, tref: nil}} end def handle_call(:get_info, _from, %{hook: hook} = state) do {:reply, hook, state} end def handle_call(:get_responses, _from, %{responses: responses} = state) do {:reply, responses, state} end def handle_call(:start_polling, _from, %{hook: %{interval: interval}} = state) do case interval do nil -> {:reply, {:error, "No interval specified, use `start_polling/2`."}, state} _ -> {:ok, tref} = start_timer(interval) {:reply, :ok, %{state | tref: tref}} end end def handle_call({:start_polling, interval}, _from, %{hook: hook} = state) do {:ok, tref} = start_timer(interval) new_hook = Map.put(hook, :interval, interval) {:reply, :ok, %{state | tref: tref, hook: new_hook}} end def handle_cast(:broadcast, %{hook: hook, responses: responses} = state) do response = notify(hook, hook.body) new_state = %{state | responses: [response | responses]} send_to_owner(hook, response) {:noreply, new_state} end def handle_cast({:broadcast, body}, %{hook: hook, responses: responses} = state) do response = notify(hook, body) new_state = %{state | responses: [response | responses]} send_to_owner(hook, response) {:noreply, new_state} end def handle_cast(:stop_polling, %{tref: tref} = state) do {:ok, _cancel} = stop_timer(tref) {:noreply, %{state | tref: nil}} end # Helpers defp notify(hook = %Grapple.Hook{method: "GET"}, _body) do @http.get(hook.url, hook.headers, hook.options) end defp notify(hook = %Grapple.Hook{method: "POST", api_key: api_key}, body) when is_nil(api_key) do @http.post(hook.url, body, hook.headers, hook.options) end defp notify(hook = %Grapple.Hook{method: "POST", api_key: api_key}, body) do auth_header = :crypto.hmac(:sha256, api_key, Jason.encode!(body)) |> Base.encode64() @http.post(hook.url, body, hook.headers ++ [{"Authorization", "Bearer #{auth_header}"}], hook.options) end defp notify(hook = %Grapple.Hook{method: "PUT", api_key: api_key}, body) when is_nil(api_key) do @http.put(hook.url, body, hook.headers, hook.options) end defp notify(hook = %Grapple.Hook{method: "POST", api_key: api_key}, body) do auth_header = :crypto.hmac(:sha256, api_key, Jason.encode!(body)) |> Base.encode64() @http.put(hook.url, body, hook.headers ++ [{"Authorization", "Bearer #{auth_header}"}], hook.options) end defp notify(hook = %Grapple.Hook{method: "DELETE"}, _body) do @http.delete(hook.url, hook.headers, hook.options) end defp send_to_owner(%{owner: owner}, response) when is_pid(owner) do if Process.alive?(owner) do send(owner, {:hook_response, self(), response}) end end defp send_to_owner(_, _), do: nil defp start_timer(interval) do # Uses Erlang :timer to `broadcast` at the given interval :timer.apply_interval(interval, __MODULE__, :broadcast, [self()]) end defp stop_timer(tref) when is_nil(tref) do # if :timer ref is nil then nothing needs to be done {:ok, "No timer"} end defp stop_timer(tref) do # Stops the :timer with the given ref :timer.cancel(tref) end end
26.098266
106
0.647176
035ec6b16f4a4eae60ef2998c183fc01306bdcdc
485
ex
Elixir
lib/app_web/views/image_view.ex
ThanhUong/Chronos
5e1b0823c585b784f5c51212513d518cab53a571
[ "MIT" ]
null
null
null
lib/app_web/views/image_view.ex
ThanhUong/Chronos
5e1b0823c585b784f5c51212513d518cab53a571
[ "MIT" ]
null
null
null
lib/app_web/views/image_view.ex
ThanhUong/Chronos
5e1b0823c585b784f5c51212513d518cab53a571
[ "MIT" ]
null
null
null
defmodule AppWeb.ImageView do use AppWeb, :view alias AppWeb.ImageView alias App.FileImage def render("index.json", %{images: images}) do %{data: render_many(images, ImageView, "image.json")} end def render("show.json", %{image: image}) do %{data: render_one(image, ImageView, "image.json")} end def render("image.json", %{image: image}) do %{ id: image.id, image: image.image, url: FileImage.url(image.image.file_name) } end end
22.045455
57
0.645361
035ecda48abfe6d7f141c4c070f043778b9e4cc3
1,832
ex
Elixir
lib/ex_bank_id/auth.ex
anfly0/exBankID
8e62f4250b533543a6b4b423b0c2fb3ec262dc7b
[ "MIT" ]
15
2020-08-05T11:20:03.000Z
2021-09-22T15:20:41.000Z
lib/ex_bank_id/auth.ex
anfly0/exBankID
8e62f4250b533543a6b4b423b0c2fb3ec262dc7b
[ "MIT" ]
9
2020-08-10T14:42:27.000Z
2021-06-14T14:45:05.000Z
lib/ex_bank_id/auth.ex
anfly0/exBankID
8e62f4250b533543a6b4b423b0c2fb3ec262dc7b
[ "MIT" ]
2
2020-08-10T13:42:15.000Z
2020-10-03T04:10:06.000Z
defmodule ExBankID.Auth do def options() do [ url: [ type: :string, default: Application.get_env(:ex_bank_id, :url, "https://appapi2.test.bankid.com/rp/v5.1/") ], cert_file: [ type: :string, default: Application.get_env(:ex_bank_id, :cert_file, __DIR__ <> "/../../assets/test.pem"), doc: "If no certificate path is specified, the publicly available test certificate will be used." ], personal_number: [ type: :string, doc: "This option can be used to specify the personal number of the person authenticating. See: [BankID Relying party guidelines section 14.1](https://www.bankid.com/assets/bankid/rp/bankid-relying-party-guidelines-v3.4.pdf)" # TODO: Add validator ], requirement: [ doc: "See: [BankID Relying party guidelines section 14.5](https://www.bankid.com/assets/bankid/rp/bankid-relying-party-guidelines-v3.4.pdf)" ], http_client: [ type: :atom, default: Application.get_env(:ex_bank_id, :http_client, ExBankID.Http.Default), doc: "Specify a custom http client. Should be a module that implements ExBankID.Http.Client." ], json_handler: [ type: :atom, default: Application.get_env(:ex_bank_id, :json_handler, ExBankID.Json.Default), doc: "Specify a custom json handler. Should be a module that implements ExBankID.Json.Handler." ] ] end def auth(ip_address, opts) when is_binary(ip_address) and is_list(opts) do with {:ok, opts} <- NimbleOptions.validate(opts, options()), payload = %ExBankID.Auth.Payload{} <- ExBankID.Auth.Payload.new(ip_address, opts) do ExBankID.HttpRequest.send_request(payload, opts) end end end
38.166667
231
0.63155
035f3f647ce5ca6fc085ab0bb39a396ab20fd7ad
717
ex
Elixir
apps/dead_letter/lib/dead_letter.ex
PillarTechnology/smartcitiesdata
9420a26820e38267513cd1bfa82c7f5583222bb1
[ "Apache-2.0" ]
null
null
null
apps/dead_letter/lib/dead_letter.ex
PillarTechnology/smartcitiesdata
9420a26820e38267513cd1bfa82c7f5583222bb1
[ "Apache-2.0" ]
null
null
null
apps/dead_letter/lib/dead_letter.ex
PillarTechnology/smartcitiesdata
9420a26820e38267513cd1bfa82c7f5583222bb1
[ "Apache-2.0" ]
null
null
null
defmodule DeadLetter do @moduledoc """ Provides functions and processes for sanitizing messages that are unable to be processed by a standard data processing pipeline and sending them to a configurable dead letter message queue service. """ defdelegate start_link(opts), to: DeadLetter.Supervisor defdelegate child_spec(args), to: DeadLetter.Supervisor @doc """ Given a message with a dataset id and app name, send a message to the dead letter queue that contains that message, along with additional metadata. """ @spec process(String.t(), any(), String.t(), keyword()) :: :ok | {:error, any()} defdelegate process(dataset_id, message, app_name, options \\ []), to: DeadLetter.Server end
37.736842
149
0.737796
035f53ae0d32bb586787b0629a5eb909d8c4283f
3,054
ex
Elixir
lib/ex_unit/lib/ex_unit/capture_server.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
2
2018-11-15T06:38:14.000Z
2018-11-17T18:03:14.000Z
lib/ex_unit/lib/ex_unit/capture_server.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
1
2018-09-10T23:36:45.000Z
2018-09-10T23:36:45.000Z
lib/ex_unit/lib/ex_unit/capture_server.ex
chulkilee/elixir
699231dcad52916a76f38856cbd7cf7c7bdadc51
[ "Apache-2.0" ]
8
2018-02-20T18:30:53.000Z
2019-06-18T14:23:31.000Z
defmodule ExUnit.CaptureServer do @moduledoc false @timeout 30000 @name __MODULE__ use GenServer def start_link(_opts) do GenServer.start_link(__MODULE__, :ok, name: @name) end def device_capture_on(device, pid) do GenServer.call(@name, {:device_capture_on, device, pid}, @timeout) end def device_capture_off(ref) do GenServer.call(@name, {:device_capture_off, ref}, @timeout) end def log_capture_on(pid) do GenServer.call(@name, {:log_capture_on, pid}, @timeout) end def log_capture_off(ref) do GenServer.call(@name, {:log_capture_off, ref}, @timeout) end ## Callbacks def init(:ok) do state = %{ devices: {%{}, %{}}, log_captures: %{}, log_status: nil } {:ok, state} end def handle_call({:device_capture_on, name, pid}, _from, config) do {names, refs} = config.devices if Map.has_key?(names, name) do {:reply, {:error, :already_captured}, config} else orig_pid = Process.whereis(name) Process.unregister(name) Process.register(pid, name) ref = Process.monitor(pid) refs = Map.put(refs, ref, {name, orig_pid}) names = Map.put(names, name, true) {:reply, {:ok, ref}, %{config | devices: {names, refs}}} end end def handle_call({:device_capture_off, ref}, _from, config) do config = release_device(ref, config) {:reply, :ok, config} end def handle_call({:log_capture_on, pid}, _from, config) do ref = Process.monitor(pid) refs = Map.put(config.log_captures, ref, true) if map_size(refs) == 1 do status = Logger.remove_backend(:console) {:reply, ref, %{config | log_captures: refs, log_status: status}} else {:reply, ref, %{config | log_captures: refs}} end end def handle_call({:log_capture_off, ref}, _from, config) do Process.demonitor(ref, [:flush]) config = remove_log_capture(ref, config) {:reply, :ok, config} end def handle_info({:DOWN, ref, _, _, _}, config) do config = remove_log_capture(ref, config) config = release_device(ref, config) {:noreply, config} end defp release_device(ref, %{devices: {names, refs}} = config) do case Map.pop(refs, ref) do {{name, pid}, refs} -> names = Map.delete(names, name) Process.demonitor(ref, [:flush]) try do try do Process.unregister(name) after Process.register(pid, name) end rescue ArgumentError -> nil end %{config | devices: {names, refs}} {nil, _refs} -> config end end defp remove_log_capture(ref, %{log_captures: refs} = config) do case Map.pop(refs, ref, false) do {true, refs} -> maybe_add_console(refs, config.log_status) %{config | log_captures: refs} {false, _refs} -> config end end defp maybe_add_console(refs, status) do if status == :ok and map_size(refs) == 0 do Logger.add_backend(:console, flush: true) end end end
24.432
71
0.617551
035f57d4fd51cf4010a834db255b8d0c7dcea694
1,006
ex
Elixir
lib/sequence/sequence_manager.ex
FarmBot-Labs/laughing-octo-telegram
9d3d161362b17da82378c51a815f4c46e0a7a09d
[ "MIT" ]
2
2016-09-18T03:06:37.000Z
2016-12-26T23:55:40.000Z
lib/sequence/sequence_manager.ex
FarmBot-Labs/laughing-octo-telegram
9d3d161362b17da82378c51a815f4c46e0a7a09d
[ "MIT" ]
3
2016-09-30T08:38:15.000Z
2016-10-01T19:26:10.000Z
lib/sequence/sequence_manager.ex
FarmBot-Labs/laughing-octo-telegram
9d3d161362b17da82378c51a815f4c46e0a7a09d
[ "MIT" ]
5
2016-09-30T17:13:42.000Z
2021-01-06T17:58:15.000Z
alias Experimental.{GenStage} defmodule SequenceManager do use GenStage def start_link() do GenStage.start_link(__MODULE__, :ok, name: __MODULE__) end def sync_notify(event, timeout \\ 5000) do GenStage.call(__MODULE__, {:notify, event}, timeout) end def init(:ok) do {:producer, {:queue.new, 0}, dispatcher: GenStage.BroadcastDispatcher} end def handle_call({:notify, event}, from, {queue, demand}) do dispatch_events(:queue.in({from, event}, queue), demand, []) end def handle_demand(incoming_demand, {queue, demand}) do dispatch_events(queue, incoming_demand + demand, []) end # This is some copy paste magic, not touching it. defp dispatch_events(queue, demand, events) do with d when d > 0 <- demand, {{:value, {from, event}}, queue} <- :queue.out(queue) do GenStage.reply(from, :ok) dispatch_events(queue, demand - 1, [event | events]) else _ -> {:noreply, Enum.reverse(events), {queue, demand}} end end end
28.742857
74
0.66998
035f7b1f7deaf062ca3a5c9b14b8e8bd7a27bb49
157
ex
Elixir
test/support/time_helper.ex
RobertDober/lab42_f
2bf3aa3a82db337192d0e0fca3bf5cf7d153f8c3
[ "Apache-2.0" ]
null
null
null
test/support/time_helper.ex
RobertDober/lab42_f
2bf3aa3a82db337192d0e0fca3bf5cf7d153f8c3
[ "Apache-2.0" ]
null
null
null
test/support/time_helper.ex
RobertDober/lab42_f
2bf3aa3a82db337192d0e0fca3bf5cf7d153f8c3
[ "Apache-2.0" ]
null
null
null
defmodule Test.Support.TimeHelper do def ntime(y, m, d, h \\ 0, mi \\ 0, s \\ 0, ms \\ {0, 0}) do NaiveDateTime.new!(y, m, d, h, mi, s, ms) end end
22.428571
62
0.55414
035f7d624a757dcca98880c0b813ecc91dbb44bd
2,680
ex
Elixir
clients/recaptcha_enterprise/lib/google_api/recaptcha_enterprise/v1/model/google_cloud_recaptchaenterprise_v1_search_related_account_group_memberships_request.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/recaptcha_enterprise/lib/google_api/recaptcha_enterprise/v1/model/google_cloud_recaptchaenterprise_v1_search_related_account_group_memberships_request.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/recaptcha_enterprise/lib/google_api/recaptcha_enterprise/v1/model/google_cloud_recaptchaenterprise_v1_search_related_account_group_memberships_request.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.RecaptchaEnterprise.V1.Model.GoogleCloudRecaptchaenterpriseV1SearchRelatedAccountGroupMembershipsRequest do @moduledoc """ The request message to search related account group memberships. ## Attributes * `hashedAccountId` (*type:* `String.t`, *default:* `nil`) - Optional. The unique stable hashed user identifier we should search connections to. The identifier should correspond to a `hashed_account_id` provided in a previous CreateAssessment or AnnotateAssessment call. * `pageSize` (*type:* `integer()`, *default:* `nil`) - Optional. The maximum number of groups to return. The service may return fewer than this value. If unspecified, at most 50 groups will be returned. The maximum value is 1000; values above 1000 will be coerced to 1000. * `pageToken` (*type:* `String.t`, *default:* `nil`) - Optional. A page token, received from a previous `SearchRelatedAccountGroupMemberships` call. Provide this to retrieve the subsequent page. When paginating, all other parameters provided to `SearchRelatedAccountGroupMemberships` must match the call that provided the page token. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :hashedAccountId => String.t() | nil, :pageSize => integer() | nil, :pageToken => String.t() | nil } field(:hashedAccountId) field(:pageSize) field(:pageToken) end defimpl Poison.Decoder, for: GoogleApi.RecaptchaEnterprise.V1.Model.GoogleCloudRecaptchaenterpriseV1SearchRelatedAccountGroupMembershipsRequest do def decode(value, options) do GoogleApi.RecaptchaEnterprise.V1.Model.GoogleCloudRecaptchaenterpriseV1SearchRelatedAccountGroupMembershipsRequest.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.RecaptchaEnterprise.V1.Model.GoogleCloudRecaptchaenterpriseV1SearchRelatedAccountGroupMembershipsRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.666667
337
0.762313
035f94fd6d59e3dbeeaac9c27e26b72fee0ad027
4,842
ex
Elixir
clients/page_speed_online/lib/google_api/page_speed_online/v5/model/renderer_formatted_strings.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/page_speed_online/lib/google_api/page_speed_online/v5/model/renderer_formatted_strings.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/page_speed_online/lib/google_api/page_speed_online/v5/model/renderer_formatted_strings.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.PageSpeedOnline.V5.Model.RendererFormattedStrings do @moduledoc """ Message holding the formatted strings used in the renderer. ## Attributes * `auditGroupExpandTooltip` (*type:* `String.t`, *default:* `nil`) - The tooltip text on an expandable chevron icon. * `crcInitialNavigation` (*type:* `String.t`, *default:* `nil`) - The label for the initial request in a critical request chain. * `crcLongestDurationLabel` (*type:* `String.t`, *default:* `nil`) - The label for values shown in the summary of critical request chains. * `errorLabel` (*type:* `String.t`, *default:* `nil`) - The label shown next to an audit or metric that has had an error. * `errorMissingAuditInfo` (*type:* `String.t`, *default:* `nil`) - The error string shown next to an erroring audit. * `labDataTitle` (*type:* `String.t`, *default:* `nil`) - The title of the lab data performance category. * `lsPerformanceCategoryDescription` (*type:* `String.t`, *default:* `nil`) - The disclaimer shown under performance explaning that the network can vary. * `manualAuditsGroupTitle` (*type:* `String.t`, *default:* `nil`) - The heading shown above a list of audits that were not computerd in the run. * `notApplicableAuditsGroupTitle` (*type:* `String.t`, *default:* `nil`) - The heading shown above a list of audits that do not apply to a page. * `opportunityResourceColumnLabel` (*type:* `String.t`, *default:* `nil`) - The heading for the estimated page load savings opportunity of an audit. * `opportunitySavingsColumnLabel` (*type:* `String.t`, *default:* `nil`) - The heading for the estimated page load savings of opportunity audits. * `passedAuditsGroupTitle` (*type:* `String.t`, *default:* `nil`) - The heading that is shown above a list of audits that are passing. * `scorescaleLabel` (*type:* `String.t`, *default:* `nil`) - The label that explains the score gauges scale (0-49, 50-89, 90-100). * `toplevelWarningsMessage` (*type:* `String.t`, *default:* `nil`) - The label shown preceding important warnings that may have invalidated an entire report. * `varianceDisclaimer` (*type:* `String.t`, *default:* `nil`) - The disclaimer shown below a performance metric value. * `warningHeader` (*type:* `String.t`, *default:* `nil`) - The label shown above a bulleted list of warnings. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :auditGroupExpandTooltip => String.t(), :crcInitialNavigation => String.t(), :crcLongestDurationLabel => String.t(), :errorLabel => String.t(), :errorMissingAuditInfo => String.t(), :labDataTitle => String.t(), :lsPerformanceCategoryDescription => String.t(), :manualAuditsGroupTitle => String.t(), :notApplicableAuditsGroupTitle => String.t(), :opportunityResourceColumnLabel => String.t(), :opportunitySavingsColumnLabel => String.t(), :passedAuditsGroupTitle => String.t(), :scorescaleLabel => String.t(), :toplevelWarningsMessage => String.t(), :varianceDisclaimer => String.t(), :warningHeader => String.t() } field(:auditGroupExpandTooltip) field(:crcInitialNavigation) field(:crcLongestDurationLabel) field(:errorLabel) field(:errorMissingAuditInfo) field(:labDataTitle) field(:lsPerformanceCategoryDescription) field(:manualAuditsGroupTitle) field(:notApplicableAuditsGroupTitle) field(:opportunityResourceColumnLabel) field(:opportunitySavingsColumnLabel) field(:passedAuditsGroupTitle) field(:scorescaleLabel) field(:toplevelWarningsMessage) field(:varianceDisclaimer) field(:warningHeader) end defimpl Poison.Decoder, for: GoogleApi.PageSpeedOnline.V5.Model.RendererFormattedStrings do def decode(value, options) do GoogleApi.PageSpeedOnline.V5.Model.RendererFormattedStrings.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.PageSpeedOnline.V5.Model.RendererFormattedStrings do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
50.4375
151
0.706939
035f9d400bbac280cf6cd29799b6879da541e0f4
2,039
ex
Elixir
apps/world/lib/world/zone_controller.ex
smartlogic/elixir-node-balancing
ddf1ae7ff71f93b7decafa679b2fa4b5fb1937c4
[ "MIT" ]
1
2017-12-01T23:09:10.000Z
2017-12-01T23:09:10.000Z
apps/world/lib/world/zone_controller.ex
smartlogic/elixir-node-balancing
ddf1ae7ff71f93b7decafa679b2fa4b5fb1937c4
[ "MIT" ]
null
null
null
apps/world/lib/world/zone_controller.ex
smartlogic/elixir-node-balancing
ddf1ae7ff71f93b7decafa679b2fa4b5fb1937c4
[ "MIT" ]
null
null
null
defmodule World.ZoneController do @moduledoc """ GenServer that connects with other zone controllers to spawn zones """ use GenServer require Logger alias World.Zone def start_link(_) do GenServer.start_link(__MODULE__, nil, name: __MODULE__) end def start_zone(pid, zone) do GenServer.call(pid, {:start, zone}) end def stop_zones(pid, zones) do GenServer.call(pid, {:stop_zones, zones}) end def online_zones(pid) do GenServer.call(pid, :online_zones) end def init(_) do :ok = :pg2.create(:zone_master) :ok = :pg2.create(:zone_controllers) :ok = :pg2.join(:zone_controllers, self()) :ok = :net_kernel.monitor_nodes(true) {:ok, %{zones: []}} end def handle_call({:start, zone}, _from, state) do Logger.info("Starting zone #{zone.id}") World.Supervisor.start_child(zone) state = %{state | zones: [zone | state.zones]} {:reply, :ok, state} end def handle_call(:online_zones, _from, state) do {:reply, state.zones, state} end def handle_call({:stop_zones, zones}, _from, state) do stop_zones(zones) zone_ids = Enum.map(zones, &(&1.id)) zones = Enum.reject(state.zones, fn (zone) -> zone.id in zone_ids end) state = %{state | zones: zones} {:reply, :ok, state} end def handle_info({:nodeup, _}, state), do: {:noreply, state} def handle_info({:nodedown, _}, state) do :erlang.send_after(500, self(), :maybe_shutdown) {:noreply, state} end def handle_info(:maybe_shutdown, state) do Logger.info("Looking for the master node to still be up") case :pg2.get_members(:zone_master) do [] -> Logger.info("Shutting down all zones") stop_zones(state.zones) state = %{state | zones: []} {:noreply, state} _ -> Logger.info("Master is up") {:noreply, state} end end defp stop_zones(zones) do Enum.each(zones, fn (zone) -> Zone.shutdown(zone.id) World.Supervisor.delete_child(zone.id) end) end end
23.709302
68
0.635115
035fb88de7ccc1262911cd1461458374d98909c0
238
ex
Elixir
packages/engine_umbrella/apps/message_generator/lib/osrm.ex
PredictiveMovement/predictivemovement
f5e62d4aed4d2068026aecf3f7f8b6749a0b0563
[ "MIT" ]
2
2021-12-09T16:06:51.000Z
2021-12-09T16:06:55.000Z
packages/engine_umbrella/apps/message_generator/lib/osrm.ex
PredictiveMovement/predictivemovement
f5e62d4aed4d2068026aecf3f7f8b6749a0b0563
[ "MIT" ]
18
2021-09-20T08:04:41.000Z
2021-11-08T14:58:47.000Z
packages/engine_umbrella/apps/message_generator/lib/osrm.ex
PredictiveMovement/predictivemovement
f5e62d4aed4d2068026aecf3f7f8b6749a0b0563
[ "MIT" ]
null
null
null
defmodule MessageGenerator.Osrm do @osrmBase "https://osrm.iteamdev.io/" def nearest(%{lon: lon, lat: lat}) do HTTPoison.get!("#{@osrmBase}nearest/v1/driving/#{lon},#{lat}") |> Map.get(:body) |> Jason.decode!() end end
23.8
66
0.634454
035fbf419c44e3a31281df40de3946abc95bbac3
3,807
ex
Elixir
lib/mix/lib/mix/tasks/run.ex
xtian/elixir
c680eb1a3992309c272e8f808e15990ea5318d6e
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/run.ex
xtian/elixir
c680eb1a3992309c272e8f808e15990ea5318d6e
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/tasks/run.ex
xtian/elixir
c680eb1a3992309c272e8f808e15990ea5318d6e
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Tasks.Run do use Mix.Task @shortdoc "Runs the given file or expression" @moduledoc """ Runs the given file or expression in the context of the application. You can use this task to execute a particular file or command: mix run -e Hello.world mix run my_script.exs This task provides a subset of the functionality available in the `elixir` executable, including setting up the `System.argv/0` arguments: mix run my_script.exs arg1 arg2 arg3 You can also use this task to simply start an application and keep it running without halting: mix run --no-halt Before running any command, the task compiles and starts the current application. Those can be configured with the options below. You may also pass options specific to the `elixir` executable as follows: elixir --sname hello -S mix run --no-halt ## Command line options * `--config`, `-c` - loads the given configuration file * `--eval`, `-e` - evaluate the given code * `--require`, `-r` - requires pattern before running the command * `--parallel`, `-p` - makes all requires parallel * `--no-compile` - does not compile even if files require compilation * `--no-deps-check` - does not check dependencies * `--no-archives-check` - does not check archives * `--no-halt` - does not halt the system after running the command * `--no-start` - does not start applications after compilation * `--no-elixir-version-check` - does not check the Elixir version from mix.exs """ @spec run(OptionParser.argv) :: :ok def run(args) do {opts, head} = OptionParser.parse_head!(args, aliases: [r: :require, p: :parallel, e: :eval, c: :config], strict: [parallel: :boolean, require: :keep, eval: :keep, config: :keep, halt: :boolean, compile: :boolean, deps_check: :boolean, start: :boolean, archives_check: :boolean, elixir_version_check: :boolean, parallel_require: :keep]) # TODO: Remove on v2.0 opts = Enum.flat_map(opts, fn {:parallel_require, value} -> IO.warn "the --parallel-require option is deprecated in favour of using " <> "--parallel to make all requires parallel and --require VAL for requiring" [require: value, parallel: true] opt -> [opt] end) {file, argv} = case {Keyword.has_key?(opts, :eval), head} do {true, _} -> {nil, head} {_, [h | t]} -> {h, t} {_, []} -> {nil, []} end System.argv(argv) process_config opts # Start app after rewriting System.argv, # but before requiring and evaling Mix.Task.run "app.start", args process_load opts _ = if file do if File.regular?(file) do Code.require_file(file) else Mix.raise "No such file: #{file}" end end unless Keyword.get(opts, :halt, true), do: Process.sleep(:infinity) :ok end defp process_config(opts) do Enum.each opts, fn {:config, value} -> Mix.Task.run "loadconfig", [value] _ -> :ok end end defp process_load(opts) do require_runner = if opts[:parallel] do &Kernel.ParallelRequire.files/1 else fn(files) -> Enum.each(files, &Code.require_file/1) end end Enum.each opts, fn {:require, value} -> case filter_patterns(value) do [] -> Mix.raise "No files matched pattern #{inspect value} given to --require" filtered -> require_runner.(filtered) end {:eval, value} -> Code.eval_string(value) _ -> :ok end end defp filter_patterns(pattern) do Enum.filter(Enum.uniq(Path.wildcard(pattern)), &File.regular?(&1)) end end
29.742188
98
0.620436
035fca3c9623ba05a22fe0c6a678ca336b3c5464
75
exs
Elixir
test/notifications/email_test.exs
troelsim/matchalert
9379796b3046e0ce28674432568f9cb5b01aab6f
[ "Apache-2.0" ]
null
null
null
test/notifications/email_test.exs
troelsim/matchalert
9379796b3046e0ce28674432568f9cb5b01aab6f
[ "Apache-2.0" ]
null
null
null
test/notifications/email_test.exs
troelsim/matchalert
9379796b3046e0ce28674432568f9cb5b01aab6f
[ "Apache-2.0" ]
null
null
null
defmodule EmailTest do use ExUnit.Case doctest Notifications.Email end
15
29
0.813333
035fcc82cb17a8fecede3f7ec31576a697c34c92
2,285
exs
Elixir
services/fc_identity/mix.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
services/fc_identity/mix.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
services/fc_identity/mix.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
defmodule FCIdentity.MixProject do use Mix.Project def project do [ app: :fc_identity, name: "Freshcom Identity", version: "0.1.0", elixir: "~> 1.7", elixirc_paths: elixirc_paths(Mix.env), start_permanent: Mix.env() == :prod, deps: deps(), docs: docs() ] end # Run "mix help compile.app" to learn about applications. def application do [ mod: {FCIdentity.Application, []}, extra_applications: [ :logger, :eventstore ] ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] # Run "mix help deps" to learn about dependencies. defp deps do [ {:fc_base, path: "../../base/fc_base"}, {:commanded, "~> 0.17"}, {:hackney, "~> 1.9"}, {:comeonin, "~> 4.0"}, {:argon2_elixir, "~> 1.3"}, {:faker, "~> 0.11", only: [:test, :dev]}, {:ex_doc, "~> 0.19", only: :dev, runtime: false}, {:dialyxir, "~> 1.0.0-rc.3", only: [:dev], runtime: false} ] end defp docs do [ source_url: "https://github.com/freshcom/freshcom/fc_identity", groups_for_modules: groups_for_modules(), extras: ["README.md"], main: "readme" ] end defp groups_for_modules do [ "Commands": [ FCIdentity.AddUser, FCIdentity.ChangePassword, FCIdentity.ChangeUserRole, FCIdentity.DeleteUser, FCIdentity.GenerateEmailVerificationToken, FCIdentity.GeneratePasswordResetToken, FCIdentity.RegisterUser, FCIdentity.UpdateUserInfo, FCIdentity.VerifyEmail, FCIdentity.CreateAccount, FCIdentity.UpdateAccountInfo ], "Events": [ FCIdentity.EmailVerificationTokenGenerated, FCIdentity.EmailVerified, FCIdentity.PasswordChanged, FCIdentity.PasswordResetTokenGenerated, FCIdentity.UserAdded, FCIdentity.UserDeleted, FCIdentity.UserInfoUpdated, FCIdentity.UserRegistered, FCIdentity.UserRegistrationRequested, FCIdentity.UserRoleChanged, FCIdentity.AccountCreated, FCIdentity.AccountInfoUpdated, ], "Stores": [ FCIdentity.UsernameStore ] ] end end
24.569892
69
0.597812
036010c66bcc0dac462dc8448cdd577e7e40f2b9
433
ex
Elixir
lib/applicator.ex
krisztian-adam-liqid/ev
a4733d531967f0f4d4066f4e33b58a7414702a15
[ "MIT" ]
2
2021-12-29T15:37:34.000Z
2022-01-12T23:52:47.000Z
lib/applicator.ex
krisztian-adam-liqid/ev
a4733d531967f0f4d4066f4e33b58a7414702a15
[ "MIT" ]
null
null
null
lib/applicator.ex
krisztian-adam-liqid/ev
a4733d531967f0f4d4066f4e33b58a7414702a15
[ "MIT" ]
1
2022-01-31T11:07:57.000Z
2022-01-31T11:07:57.000Z
defmodule EV.Applicator do @moduledoc """ Defines a behaviour for applicators. Applicators process events when applied. They should call the given handler. May also persist a given event to a database. """ @callback call( changeset :: Ecto.Changeset.t(), handler :: (EV.Event.t(), any() -> {:ok | :error, any()}), opts :: Keyword.t() ) :: {:ok | :error, any()} end
28.866667
78
0.579677
03601ba21654775b194d137d84677e6f11203ab3
781
exs
Elixir
test/janus_test.exs
naramore/janus
90f7324c5ed667b803472dc89ee8e84d82c1d6d2
[ "MIT" ]
null
null
null
test/janus_test.exs
naramore/janus
90f7324c5ed667b803472dc89ee8e84d82c1d6d2
[ "MIT" ]
null
null
null
test/janus_test.exs
naramore/janus
90f7324c5ed667b803472dc89ee8e84d82c1d6d2
[ "MIT" ]
null
null
null
defmodule JanusTest do use ExUnit.Case use ExUnitProperties doctest Janus end defmodule Janus.GraphTest do use ExUnit.Case use ExUnitProperties doctest Janus.Graph end defmodule Janus.PlanTest do use ExUnit.Case use ExUnitProperties doctest Janus.Plan end defmodule Janus.PlannerTest do use ExUnit.Case use ExUnitProperties doctest Janus.Planner end defmodule Janus.PluginTest do use ExUnit.Case use ExUnitProperties doctest Janus.Plugin end defmodule Janus.ResolverTest do use ExUnit.Case use ExUnitProperties doctest Janus.Resolver end defmodule Janus.ProcessorTest do use ExUnit.Case use ExUnitProperties doctest Janus.Processor end defmodule Janus.UtilsTest do use ExUnit.Case use ExUnitProperties doctest Janus.Utils end
16.270833
32
0.798976
03601bc331dda5930e6d011cf518108afbe5eb5f
3,313
ex
Elixir
lib/abbr/mnesia/sync.ex
elvanja/abbr
b09954df2f68f71c03f308b01927f032bf692ac4
[ "MIT" ]
14
2020-03-25T22:10:42.000Z
2021-02-04T01:31:40.000Z
lib/abbr/mnesia/sync.ex
elvanja/abbr
b09954df2f68f71c03f308b01927f032bf692ac4
[ "MIT" ]
null
null
null
lib/abbr/mnesia/sync.ex
elvanja/abbr
b09954df2f68f71c03f308b01927f032bf692ac4
[ "MIT" ]
null
null
null
defmodule Abbr.Mnesia.Sync do @moduledoc """ Ensures cache stays in sync across cluster. Flow: - monitors the `:inconsistent_database` mnesia system event - and merges local cache with (potentially) out of sync node """ alias Abbr.Cache alias Abbr.Mnesia.Local alias Abbr.Mnesia.Url alias Memento.Schema alias Memento.Table alias Phoenix.PubSub use GenServer require Logger @spec start_link([any()]) :: {:ok, pid()} def start_link(opts) do {:ok, pid} = GenServer.start_link(__MODULE__, :ok, [{:name, __MODULE__} | opts]) :ok = GenServer.cast(__MODULE__, :synchronize_on_startup) {:ok, pid} end @impl GenServer def init(:ok) do Logger.metadata(node: Node.self()) :mnesia.subscribe(:system) {:ok, nil} end @doc """ The node is either the 1st node in the cluster in which case: - it needs to create the table or, it needs to join the Mnesia cluster, which requires: - registering the node via `:mnesia.change_config/2`, which effectively joins the Mnesia cluster - waiting for table to become available We're using Memento master branch due to usage of: - `Memento.wait/1` - `Memento.add_nodes/1` When [PR 20](https://github.com/sheharyarn/memento/pull/20) is released, we can move to release version. """ @impl GenServer def handle_cast(:synchronize_on_startup, state) do if Enum.empty?(Node.list()) do Schema.set_storage_type(Node.self(), :ram_copies) Table.create(Url) Memento.wait([Url]) PubSub.broadcast(Abbr.PubSub, Cache.events_topic(), {:cache_event, :synchronized}) else Memento.add_nodes(Node.list()) Memento.wait([Url]) end {:noreply, state} end @impl GenServer def handle_cast({:merge, cached_data}, state) do Memento.wait([Url]) :ok = Local.merge(cached_data) PubSub.broadcast(Abbr.PubSub, Cache.events_topic(), {:cache_event, :synchronized}) {:noreply, state} end @doc """ Catches the `:inconsistent_database` Mnesia event. It occurs every time a node joins the cluster, for which the schema is not in sync with this node. It can even occur if there are no differences in the underlying data, e.g. if during network split there were no new data added to respective tables. Every time this event occurs, we need to reconcile the data. It needs to be done manually, since Mnesia doesn't know which reconciliation method suits our data. """ @impl true def handle_info({:mnesia_system_event, {:inconsistent_database, _, node}}, state) do :global.trans({__MODULE__, self()}, fn -> join(node) end) {:noreply, state} end @impl true def handle_info(_, state) do {:noreply, state} end defp join(node) do :running_db_nodes |> Memento.system() |> Enum.member?(node) |> case do true -> Logger.info("Already healed and joined #{node}") :ok false -> Logger.warn("Detected netsplit on #{node}") do_join(node) end end defp do_join(node) do :mnesia_controller.connect_nodes([node], fn merge_fun -> case merge_fun.([Url]) do {:merged, _, _} = result -> :ok = GenServer.cast({__MODULE__, node}, {:merge, Local.export()}) result other -> other end end) end end
28.076271
106
0.667371
036057a47328c09aa1e616669f2ee5312800f410
12,957
ex
Elixir
apps/evm/lib/evm/operation.ex
InoMurko/ethereum
282ca2a23a897c5b9684ddf9abae2bf65691b039
[ "MIT" ]
22
2017-06-22T02:50:34.000Z
2022-01-26T20:43:21.000Z
apps/evm/lib/evm/operation.ex
InoMurko/ethereum
282ca2a23a897c5b9684ddf9abae2bf65691b039
[ "MIT" ]
9
2018-10-08T22:56:56.000Z
2018-10-18T20:41:55.000Z
apps/evm/lib/evm/operation.ex
InoMurko/ethereum
282ca2a23a897c5b9684ddf9abae2bf65691b039
[ "MIT" ]
5
2018-10-06T16:30:48.000Z
2022-01-26T20:43:26.000Z
defmodule EVM.Operation do @moduledoc """ Code to handle encoding and decoding operations from opcodes. """ alias MathHelper alias EVM.Helpers alias EVM.ExecEnv alias EVM.MachineState alias EVM.Stack alias EVM.SubState alias EVM.Operation.Metadata.StopAndArithmetic, as: StopAndArithmeticMetadata alias EVM.Operation.Metadata.ComparisonAndBitwiseLogic, as: ComparisonAndBitwiseLogicMetadata alias EVM.Operation.Metadata.SHA3, as: SHA3Metadata alias EVM.Operation.Metadata.EnvironmentalInformation, as: EnvironmentalInformationMetadata alias EVM.Operation.Metadata.BlockInformation, as: BlockInformationMetadata alias EVM.Operation.Metadata.StackMemoryStorageAndFlow, as: StackMemoryStorageAndFlowMetadata alias EVM.Operation.Metadata.Push, as: PushMetadata alias EVM.Operation.Metadata.Duplication, as: DuplicationMetadata alias EVM.Operation.Metadata.Exchange, as: ExchangeMetadata alias EVM.Operation.Metadata.Logging, as: LoggingMetadata alias EVM.Operation.Metadata.System, as: SystemMetadata use Bitwise require Logger @type operation :: atom() @type opcode :: byte() @type stack_args :: [EVM.val()] @type vm_map :: %{ optional(:state) => EVM.world_state(), optional(:stack) => Stack.t(), optional(:machine_state) => MachineState.t(), optional(:sub_state) => SubState.t(), optional(:exec_env) => ExecEnv.t(), optional(:block_interface) => EVM.Interface.BlockInterface.t(), # EVM.Interface.ContractInterface.t() optional(:contract_interface) => any(), optional(:account_interface) => EVM.Interface.AccountInterface.t() } @type noop :: :noop @type op_result :: any() @operations StopAndArithmeticMetadata.operations() ++ ComparisonAndBitwiseLogicMetadata.operations() ++ SHA3Metadata.operations() ++ EnvironmentalInformationMetadata.operations() ++ BlockInformationMetadata.operations() ++ StackMemoryStorageAndFlowMetadata.operations() ++ PushMetadata.operations() ++ DuplicationMetadata.operations() ++ ExchangeMetadata.operations() ++ LoggingMetadata.operations() ++ SystemMetadata.operations() @opcodes_to_metadata for(i <- @operations, do: {i.id, i}) |> Enum.into(%{}) @opcodes_to_operations for({id, i} <- @opcodes_to_metadata, do: {id, i.sym}) |> Enum.into(%{}) @operations_to_opcodes EVM.Helpers.invert(@opcodes_to_operations) @push1 Map.get(@operations_to_opcodes, :push1) @push32 Map.get(@operations_to_opcodes, :push32) @push_operations @push1..@push32 @jump_operations [:jump, :jumpi] @stop Map.get(@operations_to_opcodes, :stop) def jump_operations(), do: @jump_operations @doc """ Returns the current operation at a given program counter address. ## Examples iex> EVM.Operation.get_operation_at(<<0x11, 0x01, 0x02>>, 0) 17 iex> EVM.Operation.get_operation_at(<<0x11, 0x01, 0x02>>, 1) 1 iex> EVM.Operation.get_operation_at(<<0x11, 0x01, 0x02>>, 2) 2 iex> EVM.Operation.get_operation_at(<<0x11, 0x01, 0x02>>, 3) 0 """ @spec get_operation_at(MachineCode.t(), MachineState.program_counter()) :: opcode def get_operation_at(machine_code, program_counter) when is_binary(machine_code) and is_integer(program_counter) do if program_counter < byte_size(machine_code) do :binary.at(machine_code, program_counter) else # Every other position is an implicit STOP code @stop end end @doc """ Returns the next operation position given a current position and the type of operation. This is to bypass push operands. ## Examples iex> EVM.Operation.next_instr_pos(10, :add) 11 iex> EVM.Operation.next_instr_pos(20, :mul) 21 iex> EVM.Operation.next_instr_pos(10, :push1) 12 iex> EVM.Operation.next_instr_pos(10, :push32) 43 """ @spec next_instr_pos(MachineState.program_counter(), operation) :: MachineState.program_counter() def next_instr_pos(pos, instr) do encoded_operation = instr |> encode pos + push_length(encoded_operation) + 1 end defp push_length(operation) when operation in @push_operations, do: operation - (@push1 - 1) defp push_length(_operation), do: 0 @doc """ Returns the given operation for a given opcode. ## Examples iex> EVM.Operation.decode(0x00) :stop iex> EVM.Operation.decode(0x01) :add iex> EVM.Operation.decode(0x02) :mul iex> EVM.Operation.decode(0xffff) nil """ @spec decode(opcode) :: operation | nil def decode(opcode) when is_integer(opcode) do Map.get(@opcodes_to_operations, opcode) end @doc """ Returns the given opcode for an operation. ## Examples iex> EVM.Operation.encode(:stop) 0x00 iex> EVM.Operation.encode(:add) 0x01 iex> EVM.Operation.encode(:mul) 0x02 iex> EVM.Operation.encode(:salmon) nil """ @spec encode(operation) :: opcode | nil def encode(operation) when is_atom(operation) do Map.get(@operations_to_opcodes, operation) end @doc """ Returns metadata about a given operation or opcode, or nil. ## Examples iex> EVM.Operation.metadata(:stop) %EVM.Operation.Metadata{id: 0x00, sym: :stop, input_count: 0, output_count: 0, description: "Halts execution", group: :stop_and_arithmetic} iex> EVM.Operation.metadata(0x00) %EVM.Operation.Metadata{id: 0x00, sym: :stop, input_count: 0, output_count: 0, description: "Halts execution", group: :stop_and_arithmetic} iex> EVM.Operation.metadata(:add) %EVM.Operation.Metadata{id: 0x01, sym: :add, input_count: 2, output_count: 1, description: "Addition operation", group: :stop_and_arithmetic} iex> EVM.Operation.metadata(:push1) %EVM.Operation.Metadata{id: 0x60, sym: :push1, fun: :push_n, args: [1], input_count: 0, output_count: 1, description: "Place 1-byte item on stack", group: :push, machine_code_offset: 1} iex> EVM.Operation.metadata(0xfe) nil iex> EVM.Operation.metadata(nil) nil """ @spec metadata(operation | opcode) :: EVM.Operation.Metadata.t() | nil def metadata(nil), do: nil def metadata(operation) when is_atom(operation) do operation |> encode |> metadata end def metadata(opcode) when is_integer(opcode) do Map.get(@opcodes_to_metadata, opcode) end @doc """ Executes a single operation. This simply does the effects of the operation itself, ignoring the rest of the actions of an operation cycle. This will effect, for instance, the stack, but will not effect the gas, etc. ## Examples # TODO: How to handle trie state in tests? # Add iex> EVM.Operation.run_operation(EVM.Operation.metadata(:add), %EVM.MachineState{stack: [1, 2]}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{stack: [3]}, %EVM.SubState{}, %EVM.ExecEnv{}} # Push iex> EVM.Operation.run_operation(EVM.Operation.metadata(:push1), %EVM.MachineState{stack: [1, 2]}, %EVM.SubState{}, %EVM.ExecEnv{machine_code: <<00, 01>>}) {%EVM.MachineState{stack: [1, 1, 2]}, %EVM.SubState{}, %EVM.ExecEnv{machine_code: <<0, 1>>}} # nil iex> EVM.Operation.run_operation(EVM.Operation.metadata(:stop), %EVM.MachineState{stack: [1, 2]}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{stack: [1, 2]}, %EVM.SubState{}, %EVM.ExecEnv{}} """ @spec run_operation(EVM.Operation.Metadata.t(), MachineState.t(), SubState.t(), ExecEnv.t()) :: {MachineState.t(), SubState.t(), ExecEnv.t()} def run_operation(operation, machine_state, sub_state, exec_env) do {args, updated_machine_state} = operation_args(operation, machine_state, sub_state, exec_env) apply_to_group_module(operation.sym, args) |> normalize_op_result(updated_machine_state.stack) |> merge_state( operation.sym, updated_machine_state, sub_state, exec_env ) end @spec apply_to_group_module(operation, list(EVM.val())) :: op_result() defp apply_to_group_module(operation, args) do %EVM.Operation.Metadata{fun: fun, group: group} = metadata(operation) method = fun || operation apply(group_to_module(group), method, args) end @spec group_to_module(atom()) :: atom() defp group_to_module(group), do: ("Elixir.EVM.Operation." <> Macro.camelize(Atom.to_string(group))) |> String.to_atom() @doc """ Normalizes op_results. If the result is an integer it encodes it and pushes it onto the stack. If it's a list pushes each element onto the stack. Otherwise it returns what's given to it. ## Examples # iex> EVM.Operation.normalize_op_result(1, []) %{stack: [1]} iex> EVM.Operation.normalize_op_result([1,2], []) %{stack: [1, 2]} """ @spec normalize_op_result(EVM.val() | list(EVM.val()) | op_result(), EVM.Stack.t()) :: op_result() def normalize_op_result(op_result, updated_stack) do if is_integer(op_result) || is_list(op_result) || is_binary(op_result) do %{stack: Stack.push(updated_stack, Helpers.encode_val(op_result))} else op_result end end @doc """ Returns an operation's inputs ## Examples # iex> EVM.Operation.inputs(EVM.Operation.metadata(:add), %{stack: [1, 2, 3]}) [1, 2] """ @spec inputs(EVM.Operation.Metadata.t(), MachineState.t()) :: list(EVM.val()) def inputs(_stack, nil), do: [] def inputs(operation, machine_state) do Stack.peek_n(machine_state.stack, operation.input_count) end defp operation_args(operation, machine_state, sub_state, exec_env) do {stack_args, updated_machine_state} = MachineState.pop_n(machine_state, operation.input_count) vm_map = %{ stack: updated_machine_state.stack, machine_state: updated_machine_state, sub_state: sub_state, exec_env: exec_env } args = operation.args ++ [stack_args, vm_map] {args, updated_machine_state} end @doc """ Merges the state from an opcode with the current environment ## Examples iex> EVM.Operation.merge_state(:noop, EVM.Operation.metadata(:add), %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}} iex> EVM.Operation.merge_state(%{stack: [1, 2, 3]}, :add, %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{stack: [1, 2, 3]}, %EVM.SubState{}, %EVM.ExecEnv{}} iex> EVM.Operation.merge_state(%{machine_state: %EVM.MachineState{stack: [1, 2, 3]}}, :add, %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{stack: [1, 2, 3]}, %EVM.SubState{}, %EVM.ExecEnv{}} iex> EVM.Operation.merge_state(%{machine_state: %EVM.MachineState{}, sub_state: %EVM.SubState{refund: 5}}, :add, %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{}, %EVM.SubState{refund: 5}, %EVM.ExecEnv{}} iex> EVM.Operation.merge_state(%{exec_env: %EVM.ExecEnv{stack_depth: 1}}, :add, %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{stack_depth: 1}} iex> EVM.Operation.merge_state(%{stack: [1, 2, 3], machine_state: %EVM.MachineState{program_counter: 5, stack: [4, 5]}}, :add, %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{program_counter: 5, stack: [1, 2, 3]}, %EVM.SubState{}, %EVM.ExecEnv{}} iex> EVM.Operation.merge_state(%EVM.MachineState{program_counter: 5, stack: [4, 5]}, :add, %EVM.MachineState{}, %EVM.SubState{}, %EVM.ExecEnv{}) {%EVM.MachineState{program_counter: 5, stack: [4, 5]}, %EVM.SubState{}, %EVM.ExecEnv{}} """ @spec merge_state( op_result(), operation, MachineState.t(), SubState.t(), ExecEnv.t() ) :: {MachineState.t(), SubState.t(), ExecEnv.t()} def merge_state(:noop, _operation, machine_state, sub_state, exec_env) do {machine_state, sub_state, exec_env} end def merge_state( updated_machine_state = %EVM.MachineState{}, _operation, _old_machine_state, sub_state, exec_env ) do {updated_machine_state, sub_state, exec_env} end def merge_state(op_result = %{}, _operation, machine_state, sub_state, exec_env) do # For machine state, we can update it by setting machine_state, or stack, or both. base_machine_state = op_result[:machine_state] || machine_state next_machine_state = if op_result[:stack], do: %{base_machine_state | stack: op_result[:stack]}, else: base_machine_state next_sub_state = op_result[:sub_state] || sub_state next_exec_env = op_result[:exec_env] || exec_env { next_machine_state, next_sub_state, next_exec_env } end end
34.830645
191
0.672146
036057ebea4b6c5d7a3793af354c3d9ae060e70c
449
ex
Elixir
lib/yatzy/scoring/four_of_a_kind.ex
idabmat/yatzy
fb1cc1f13670a19f3541a3b1df15e9897ffcfae3
[ "MIT" ]
3
2020-04-23T14:38:39.000Z
2020-05-03T17:20:32.000Z
lib/yatzy/scoring/four_of_a_kind.ex
idabmat/yatzy
fb1cc1f13670a19f3541a3b1df15e9897ffcfae3
[ "MIT" ]
null
null
null
lib/yatzy/scoring/four_of_a_kind.ex
idabmat/yatzy
fb1cc1f13670a19f3541a3b1df15e9897ffcfae3
[ "MIT" ]
null
null
null
defmodule Yatzy.Scoring.FourOfAKind do @moduledoc """ Four of a Kind: Four dice with the same number. Score: Sum of those four dice. """ alias Yatzy.Roll defstruct roll: %Roll{}, name: "Four of a Kind", description: "Four dice with the same number.", score: "Sum of those four dice." defimpl Yatzy.Scoring.Score do def execute(%{roll: roll}), do: Yatzy.Scoring.chunk_by(roll.dice, 4) end end
26.411765
80
0.641425
0360645e5fc17ec368697bccbab8e7d4739b884e
338
ex
Elixir
lib/aql/filter.ex
elbow-jason/durango
a31b5636789ef275f19963343eda03d10ebc3ca0
[ "MIT" ]
7
2018-03-04T14:33:46.000Z
2020-10-26T17:32:23.000Z
lib/aql/filter.ex
elbow-jason/durango
a31b5636789ef275f19963343eda03d10ebc3ca0
[ "MIT" ]
5
2018-08-01T07:29:02.000Z
2018-12-31T12:59:16.000Z
lib/aql/filter.ex
elbow-jason/durango
a31b5636789ef275f19963343eda03d10ebc3ca0
[ "MIT" ]
null
null
null
defmodule Durango.AQL.Filter do defmacro inject_parser() do quote do alias Durango.Query alias Durango.Dsl def parse_query(%Query{} = q, [{:filter, expr} | rest ]) do q |> Query.append_tokens("FILTER") |> Dsl.parse_expr(expr) |> Dsl.parse_query(rest) end end end end
18.777778
65
0.58284
03606d025c99090108d85ae93bae8437e4037e5d
2,527
ex
Elixir
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_response.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_response.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_response.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResponse do @moduledoc """ Response message for SearchCatalog. ## Attributes * `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The token that can be used to retrieve the next page of results. * `results` (*type:* `list(GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResult.t)`, *default:* `nil`) - Search results. * `unreachable` (*type:* `list(String.t)`, *default:* `nil`) - Unreachable locations. Search result does not include data from those locations. Users can get additional information on the error by repeating the search request with a more restrictive parameter -- setting the value for `SearchDataCatalogRequest.scope.include_locations`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :nextPageToken => String.t(), :results => list( GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResult.t() ), :unreachable => list(String.t()) } field(:nextPageToken) field(:results, as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResult, type: :list ) field(:unreachable, type: :list) end defimpl Poison.Decoder, for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResponse do def decode(value, options) do GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResponse.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.1
156
0.738029
03607177314d5f237386bd2bfa7b8d0bc68d4c35
17,125
ex
Elixir
lib/commanded/aggregates/aggregate.ex
ThisisGurwinder/commanded
ad7784ce3125022e188ea795771710c4e5e38e71
[ "MIT" ]
null
null
null
lib/commanded/aggregates/aggregate.ex
ThisisGurwinder/commanded
ad7784ce3125022e188ea795771710c4e5e38e71
[ "MIT" ]
null
null
null
lib/commanded/aggregates/aggregate.ex
ThisisGurwinder/commanded
ad7784ce3125022e188ea795771710c4e5e38e71
[ "MIT" ]
null
null
null
defmodule Commanded.Aggregates.Aggregate do @moduledoc """ Aggregate is a `GenServer` process used to provide access to an instance of an event sourced aggregate. It allows execution of commands against an aggregate instance, and handles persistence of created events to the configured event store. Concurrent commands sent to an aggregate instance are serialized and executed in the order received. The `Commanded.Commands.Router` module will locate, or start, an aggregate instance when a command is dispatched. By default, an aggregate process will run indefinitely once started. Its lifespan may be controlled by using the `Commanded.Aggregates.AggregateLifespan` behaviour. ## Snapshotting You can configure state snapshots for an aggregate in config. By default snapshots are *not* taken for an aggregate. The following options are available to enable snapshots: - `snapshot_every` - snapshot aggregate state every so many events. Use `nil` to disable snapshotting, or exclude the configuration entirely. - `snapshot_version` - a non-negative integer indicating the version of the aggregate state snapshot. Incrementing this version forces any earlier recorded snapshots to be ignored when rebuilding aggregate state. ### Example In `config/config.exs` enable snapshots for `ExampleAggregate` after every ten events: config :commanded, ExampleAggregate snapshot_every: 10, snapshot_version: 1 """ use GenServer use Commanded.Registration require Logger alias Commanded.Aggregates.{Aggregate, ExecutionContext} alias Commanded.Event.Mapper alias Commanded.EventStore alias Commanded.EventStore.{RecordedEvent, SnapshotData} @read_event_batch_size 100 defstruct aggregate_module: nil, aggregate_uuid: nil, aggregate_state: nil, aggregate_version: 0, lifespan_timeout: nil, snapshot_every: nil, snapshot_module_version: 1, snapshot_version: 0 def start_link(aggregate_module, aggregate_uuid, opts \\ []) do snapshot_options = snapshot_options(aggregate_module) aggregate = %Aggregate{ aggregate_module: aggregate_module, aggregate_uuid: aggregate_uuid, snapshot_every: Keyword.get(snapshot_options, :snapshot_every), snapshot_module_version: Keyword.get(snapshot_options, :snapshot_version, 1) } GenServer.start_link(__MODULE__, aggregate, opts) end @doc false def name(aggregate_module, aggregate_uuid), do: {aggregate_module, aggregate_uuid} def init(%Aggregate{} = state) do # initial aggregate state is populated by loading its state snapshot and/or # events from the event store :ok = GenServer.cast(self(), :populate_aggregate_state) # subscribe to aggregate's events to catch any events appended to its stream # by another process, such as directly appended to the event store. :ok = GenServer.cast(self(), :subscribe_to_events) {:ok, state} end @doc """ Execute the given command against the aggregate. - `aggregate_module` - the aggregate's module (e.g. `BankAccount`). - `aggregate_uuid` - uniquely identifies an instance of the aggregate. - `context` - includes command execution arguments (see `Commanded.Aggregates.ExecutionContext` for details). - `timeout` - an integer greater than zero which specifies how many milliseconds to wait for a reply, or the atom :infinity to wait indefinitely. The default value is five seconds (5,000ms). ## Return values Returns `{:ok, aggregate_version, events}` on success, or `{:error, reason}` on failure. - `aggregate_version` - the updated version of the aggregate after executing the command. - `events` - events produced by the command, can be an empty list. """ def execute(aggregate_module, aggregate_uuid, %ExecutionContext{} = context, timeout \\ 5_000) do GenServer.call( via_name(aggregate_module, aggregate_uuid), {:execute_command, context}, timeout ) end @doc false def aggregate_state(aggregate_module, aggregate_uuid, timeout \\ 5_000) def aggregate_state(aggregate_module, aggregate_uuid, timeout) do GenServer.call(via_name(aggregate_module, aggregate_uuid), :aggregate_state, timeout) end @doc false def aggregate_version(aggregate_module, aggregate_uuid) do GenServer.call(via_name(aggregate_module, aggregate_uuid), :aggregate_version) end @doc false def take_snapshot(aggregate_module, aggregate_uuid) do GenServer.cast(via_name(aggregate_module, aggregate_uuid), :take_snapshot) end @doc false def shutdown(aggregate_module, aggregate_uuid) do GenServer.stop(via_name(aggregate_module, aggregate_uuid)) end @doc false def handle_cast(:populate_aggregate_state, %Aggregate{} = state) do {:noreply, populate_aggregate_state(state)} end @doc false def handle_cast(:subscribe_to_events, %Aggregate{} = state) do %Aggregate{aggregate_uuid: aggregate_uuid} = state :ok = EventStore.subscribe(aggregate_uuid) {:noreply, state} end @doc false def handle_cast(:take_snapshot, %Aggregate{} = state) do %Aggregate{lifespan_timeout: lifespan_timeout} = state {:noreply, do_snapshot(state), lifespan_timeout} end @doc false def handle_call({:execute_command, %ExecutionContext{} = context}, _from, %Aggregate{} = state) do Logger.warn(fn -> "AGGREGATE:=> [[[[#{inspect context.command.__struct__}]]]] going to execute command" end) {reply, state} = execute_command(context, state) lifespan_timeout = case reply do {:ok, _stream_version, events} -> aggregate_lifespan_timeout(context, events) _ -> :infinity end case lifespan_timeout do :stop -> {:stop, :normal, reply, state} _ -> state = %Aggregate{state | lifespan_timeout: lifespan_timeout} if snapshotting_enabled?(state) && snapshot_required?(state) do :ok = GenServer.cast(self(), :take_snapshot) {:reply, reply, state} else {:reply, reply, state, lifespan_timeout} end end end @doc false def handle_call(:aggregate_state, _from, %Aggregate{} = state) do %Aggregate{aggregate_state: aggregate_state} = state {:reply, aggregate_state, state} end @doc false def handle_call(:aggregate_version, _from, %Aggregate{} = state) do %Aggregate{aggregate_version: aggregate_version} = state {:reply, aggregate_version, state} end @doc false def handle_info({:events, events}, %Aggregate{} = state) do %Aggregate{lifespan_timeout: lifespan_timeout} = state Logger.debug(fn -> describe(state) <> " received events: #{inspect(events)}" end) try do state = Enum.reduce(events, state, &handle_event/2) {:noreply, state, lifespan_timeout} catch {:error, reason} -> Logger.debug(fn -> describe(state) <> " stopping due to: #{inspect(reason)}" end) # stop after event handling returned an error {:stop, reason, state} end end @doc false def handle_info(:timeout, %Aggregate{} = state) do Logger.debug(fn -> describe(state) <> " stopping due to inactivity timeout" end) {:stop, :normal, state} end # Handle events appended to the aggregate's stream, received by its # event store subscription, by applying any missed events to its state. defp handle_event(%RecordedEvent{} = event, %Aggregate{} = state) do %RecordedEvent{data: data, stream_version: stream_version} = event %Aggregate{ aggregate_module: aggregate_module, aggregate_state: aggregate_state, aggregate_version: aggregate_version } = state expected_version = aggregate_version + 1 case stream_version do ^expected_version -> # apply event to aggregate's state %Aggregate{ state | aggregate_version: stream_version, aggregate_state: aggregate_module.apply(aggregate_state, data) } already_seen_version when already_seen_version <= aggregate_version -> # ignore events already applied to aggregate state state _unexpected_version -> Logger.debug(fn -> describe(state) <> " received an unexpected event: #{inspect(event)}" end) # throw an error when an unexpected event is received throw({:error, :unexpected_event_received}) end end # Populate the aggregate's state from a snapshot, if present, and it's events. # # Attempt to fetch a snapshot for the aggregate to use as its initial state. # If the snapshot exists, fetch any subsequent events to rebuild its state. # Otherwise start with the aggregate struct and stream all existing events for # the aggregate from the event store to rebuild its state from those events. defp populate_aggregate_state(%Aggregate{} = state) do %Aggregate{ aggregate_module: aggregate_module, aggregate_uuid: aggregate_uuid } = state aggregate = with true <- snapshotting_enabled?(state), {:ok, snapshot} <- EventStore.read_snapshot(aggregate_uuid), true <- snapshot_valid?(snapshot, state) do # populate initial state from snapshot %Aggregate{ state | aggregate_version: snapshot.source_version, aggregate_state: snapshot.data } else _ -> # no snapshot (or outdated), use intial empty state %Aggregate{state | aggregate_version: 0, aggregate_state: struct(aggregate_module)} end rebuild_from_events(aggregate) end # Load events from the event store, in batches, to rebuild the aggregate state defp rebuild_from_events(%Aggregate{} = state) do %Aggregate{ aggregate_uuid: aggregate_uuid, aggregate_version: aggregate_version } = state case EventStore.stream_forward(aggregate_uuid, aggregate_version + 1, @read_event_batch_size) do {:error, :stream_not_found} -> # aggregate does not exist, return initial state state event_stream -> rebuild_from_event_stream(event_stream, state) end end # Rebuild aggregate state from a `Stream` of its events defp rebuild_from_event_stream(event_stream, %Aggregate{} = state) do %Aggregate{aggregate_module: aggregate_module} = state event_stream |> Stream.map(fn event -> {event.data, event.stream_version} end) |> Stream.transform(state, fn {event, stream_version}, state -> case event do nil -> {:halt, state} event -> state = %Aggregate{ state | aggregate_version: stream_version, aggregate_state: aggregate_module.apply(state.aggregate_state, event) } {[state], state} end end) |> Stream.take(-1) |> Enum.at(0) |> case do nil -> state state -> state end end defp aggregate_lifespan_timeout(_context, []), do: :infinity defp aggregate_lifespan_timeout(%ExecutionContext{} = context, [event]) do %ExecutionContext{lifespan: lifespan} = context case lifespan.after_event(event) do timeout when timeout in [:infinity, :hibernate, :stop] -> timeout timeout when is_integer(timeout) and timeout >= 0 -> timeout invalid -> Logger.warn(fn -> "Invalid timeout for aggregate lifespan #{inspect(lifespan)}, expected a non-negative integer, `:infinity`, or `:hibernate` but got: #{ inspect(invalid) }" end) :infinity end end defp aggregate_lifespan_timeout(context, [_event | events]), do: aggregate_lifespan_timeout(context, events) # is snapshotting configured for the aggregate? defp snapshotting_enabled?(%Aggregate{snapshot_every: snapshot_every}), do: is_number(snapshot_every) && snapshot_every > 0 # was the snapshot taken at the current version? defp snapshot_valid?(%SnapshotData{metadata: metadata}, %Aggregate{ snapshot_module_version: expected_version }) do Map.get(metadata, "snapshot_version", 1) == expected_version end # take a snapshot now? defp snapshot_required?(%Aggregate{ aggregate_version: aggregate_version, snapshot_every: snapshot_every, snapshot_version: snapshot_version }) when aggregate_version - snapshot_version >= snapshot_every, do: true # not yet enough events to snapshot defp snapshot_required?(_state), do: false # snapshot aggregate state defp do_snapshot(%Aggregate{} = state) do %Aggregate{ aggregate_module: aggregate_module, aggregate_uuid: aggregate_uuid, aggregate_version: aggregate_version, aggregate_state: aggregate_state } = state Logger.debug(fn -> describe(state) <> " recording snapshot" end) snapshot = %SnapshotData{ source_uuid: aggregate_uuid, source_version: aggregate_version, source_type: Atom.to_string(aggregate_module), data: aggregate_state, metadata: %{"snapshot_version" => aggregate_version} } :ok = EventStore.record_snapshot(snapshot) %Aggregate{state | snapshot_version: aggregate_version} end defp execute_command(%ExecutionContext{retry_attempts: retry_attempts}, %Aggregate{} = state) when retry_attempts < 0, do: {{:error, :too_many_attempts}, state} defp execute_command(%ExecutionContext{} = context, %Aggregate{} = state) do %ExecutionContext{ command: command, handler: handler, function: function, retry_attempts: retry_attempts } = context %Aggregate{ aggregate_module: aggregate_module, aggregate_version: expected_version, aggregate_state: aggregate_state } = state Logger.debug(fn -> describe(state) <> " executing command: #{inspect(command)}" end) {reply, state} = case Kernel.apply(handler, function, [aggregate_state, command]) do {:error, _reason} = reply -> {reply, state} none when none in [nil, []] -> {{:ok, expected_version, []}, state} %Commanded.Aggregate.Multi{} = multi -> case Commanded.Aggregate.Multi.run(multi) do {:error, _reason} = reply -> {reply, state} {aggregate_state, pending_events} -> persist_events(pending_events, aggregate_state, context, state) end events -> pending_events = List.wrap(events) aggregate_state = apply_events(aggregate_module, aggregate_state, pending_events) persist_events(pending_events, aggregate_state, context, state) end case reply do {:error, :wrong_expected_version} -> Logger.debug(fn -> describe(state) <> " wrong expected version, retrying command" end) # fetch missing events from event store state = rebuild_from_events(state) # retry command, but decrement retry attempts (to prevent infinite retries) execute_command(%ExecutionContext{context | retry_attempts: retry_attempts - 1}, state) reply -> {reply, state} end end defp apply_events(aggregate_module, aggregate_state, events) do Enum.reduce(events, aggregate_state, &aggregate_module.apply(&2, &1)) end defp persist_events(pending_events, aggregate_state, context, %Aggregate{} = state) do %Aggregate{aggregate_uuid: aggregate_uuid, aggregate_version: expected_version} = state with {:ok, stream_version} <- append_to_stream(pending_events, aggregate_uuid, expected_version, context) do state = %Aggregate{ state | aggregate_state: aggregate_state, aggregate_version: stream_version } {{:ok, stream_version, pending_events}, state} else {:error, _reason} = reply -> {reply, state} end end defp append_to_stream([], _stream_uuid, expected_version, _context), do: {:ok, expected_version} defp append_to_stream(pending_events, stream_uuid, expected_version, context) do %ExecutionContext{ causation_id: causation_id, correlation_id: correlation_id, metadata: metadata } = context event_data = Mapper.map_to_event_data(pending_events, causation_id, correlation_id, metadata) EventStore.append_to_stream(stream_uuid, expected_version, event_data) end # get the snapshot options for the aggregate defined in environment config. defp snapshot_options(aggregate_module), do: Application.get_env(:commanded, aggregate_module, []) defp via_name(aggregate_module, aggregate_uuid), do: name(aggregate_module, aggregate_uuid) |> via_tuple() defp describe(%Aggregate{} = aggregate) do %Aggregate{ aggregate_module: aggregate_module, aggregate_uuid: aggregate_uuid, aggregate_version: aggregate_version } = aggregate "#{inspect(aggregate_module)}<#{aggregate_uuid}@#{aggregate_version}>" end end
32.18985
145
0.689635
03608cce4e581e8a63f0069817dbde95275c5b4f
644
ex
Elixir
lib/rasa_sdk/model/response_rejected.ex
r26D/rasa-sdk-elixir
65da9444add5da2e2c0989c36bcbdf902733c709
[ "Apache-2.0" ]
2
2020-09-24T09:58:52.000Z
2021-02-08T12:35:55.000Z
lib/rasa_sdk/model/response_rejected.ex
r26D/rasa-sdk-elixir
65da9444add5da2e2c0989c36bcbdf902733c709
[ "Apache-2.0" ]
null
null
null
lib/rasa_sdk/model/response_rejected.ex
r26D/rasa-sdk-elixir
65da9444add5da2e2c0989c36bcbdf902733c709
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule RasaSDK.Model.ResponseRejected do @moduledoc """ Action execution was rejected. This is the same as returning an &#x60;ActionExecutionRejected&#x60; event. """ @derive [Poison.Encoder] defstruct [ :action_name, :error ] @type t :: %__MODULE__{ action_name: String.t() | nil, error: String.t() | nil } end defimpl Poison.Decoder, for: RasaSDK.Model.ResponseRejected do def decode(value, _options) do value end end
23.851852
108
0.684783
0360a057f16c74e6b80007b425ca0c5c2049e42d
583
exs
Elixir
config/test.exs
rmartinsc/livrodealemao
337e2b7f5bd6de6b84d6ec44a37a839bee71319e
[ "MIT" ]
null
null
null
config/test.exs
rmartinsc/livrodealemao
337e2b7f5bd6de6b84d6ec44a37a839bee71319e
[ "MIT" ]
null
null
null
config/test.exs
rmartinsc/livrodealemao
337e2b7f5bd6de6b84d6ec44a37a839bee71319e
[ "MIT" ]
null
null
null
use Mix.Config # We don't run a server during test. If one is required, # you can enable the server option below. config :livrodealemao, LivrodealemaoWeb.Endpoint, http: [port: 4002], server: false # Print only warnings and errors during test config :logger, level: :warn # Configure your database config :livrodealemao, Livrodealemao.Repo, username: System.get_env("DB_USER") || "livrodealemao", password: System.get_env("DB_PASSWORD") || "password", database: "livrodealemao_test", hostname: System.get_env("DB_HOST") || "postgre", pool: Ecto.Adapters.SQL.Sandbox
30.684211
57
0.74271
0360b6026568aef4881eb6fd56057f1dc3d8fba3
944
ex
Elixir
lib/straw_hat_map/locations/location_entity.ex
straw-hat-team/straw_hat_map
df71340122852577b9df2ed2afcbcc4be879aba1
[ "MIT" ]
4
2018-03-07T04:12:36.000Z
2018-03-08T16:13:14.000Z
lib/straw_hat_map/locations/location_entity.ex
straw-hat-labs/straw_hat_map
df71340122852577b9df2ed2afcbcc4be879aba1
[ "MIT" ]
61
2018-03-07T04:50:42.000Z
2019-11-01T10:24:03.000Z
lib/straw_hat_map/locations/location_entity.ex
straw-hat-team/straw_hat_map
df71340122852577b9df2ed2afcbcc4be879aba1
[ "MIT" ]
2
2018-03-22T19:44:45.000Z
2019-08-02T03:45:47.000Z
defmodule StrawHat.Map.Location do @moduledoc """ A location entity. """ use StrawHat.Map.EctoSchema alias StrawHat.Map.Address @typedoc """ - `location`: a GeoJSON point using `Geo.Point.t/0`. """ @type t :: %__MODULE__{ id: String.t(), location: Geo.Point.t(), inserted_at: DateTime.t(), updated_at: DateTime.t(), address_id: String.t(), address: Schema.belongs_to(Address.t()) } @type location_attrs :: %{ location: Map.t(), address_id: String.t() } @optional_fields ~w(location address_id)a schema "locations" do field(:location, Geo.PostGIS.Geometry) belongs_to(:address, Address) timestamps() end @spec changeset(t, location_attrs) :: Ecto.Changeset.t() def changeset(location, location_attrs) do location |> cast(location_attrs, @optional_fields) |> cast_assoc(:address) end end
23.02439
58
0.615466
0360b8bb638644f68679e2de6dc45ab4dd368729
867
ex
Elixir
test/example/elixir/apps/subscribe/lib/subscribe.ex
davedoesdev/centro
1b1f693904dcb1ce955dced8fec03fd4c3a542f5
[ "MIT" ]
2
2017-12-05T13:06:22.000Z
2019-12-29T11:48:04.000Z
test/example/elixir/apps/subscribe/lib/subscribe.ex
davedoesdev/centro
1b1f693904dcb1ce955dced8fec03fd4c3a542f5
[ "MIT" ]
10
2019-11-02T09:55:14.000Z
2022-02-26T02:07:44.000Z
test/example/elixir/apps/subscribe/lib/subscribe.ex
davedoesdev/centro
1b1f693904dcb1ce955dced8fec03fd4c3a542f5
[ "MIT" ]
null
null
null
defmodule Subscribe do def main(topics) do {:ok, _} = EventsourceEx.new( "http://localhost:8802/centro/v2/subscribe?" <> URI.encode_query([{"authz_token", System.get_env("CENTRO_TOKEN")} | (for topic <- topics, do: {"topic", topic})]), headers: [], stream_to: self()) loop() end defmodule Start do defstruct [:id, :topic] end defmodule Data do defstruct [:id, :data] end def loop do receive do %EventsourceEx.Message{event: "start", data: data} -> start = Poison.decode!(data, as: %Start{}) :io.format("id: ~B topic: ~s~n", [start.id, start.topic]) %EventsourceEx.Message{event: "data", data: data} -> data = Poison.decode!(data, as: %Data{}) IO.write(:unicode.characters_to_binary(data.data, :utf8, :latin1)) end loop() end end
29.896552
74
0.584775
0360eb2aa14dc2ba8247c3a6508cac43c95b2b1f
4,935
exs
Elixir
test/attribute_repository_mnesia_test/write_test.exs
tanguilp/attribute_repository_mnesia
9e8d6284716bbbe8d24b6f551cd295fbaf5d7674
[ "Apache-2.0" ]
1
2022-01-27T11:48:58.000Z
2022-01-27T11:48:58.000Z
test/attribute_repository_mnesia_test/write_test.exs
tanguilp/attribute_repository_mnesia
9e8d6284716bbbe8d24b6f551cd295fbaf5d7674
[ "Apache-2.0" ]
null
null
null
test/attribute_repository_mnesia_test/write_test.exs
tanguilp/attribute_repository_mnesia
9e8d6284716bbbe8d24b6f551cd295fbaf5d7674
[ "Apache-2.0" ]
null
null
null
defmodule AttributeRepositoryMnesiaTest.Write do use ExUnit.Case @init_opts [instance: :test] @run_opts [instance: :test] setup_all do AttributeRepositoryMnesia.install(@run_opts, @init_opts) AttributeRepositoryMnesia.start(@init_opts) end setup do AttributeRepositoryMnesia.delete("test_write", @run_opts) AttributeRepositoryMnesia.put("test_write", %{ "key1" => "value 1", "key2" => 2, "key3" => true, "key4" => ["val1", "val2", "val3", "val4"] }, @run_opts) end # put test "put 1" do obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key1"] == "value 1" assert obj["key2"] == 2 assert obj["key3"] == true assert Enum.sort(obj["key4"]) == ["val1", "val2", "val3", "val4"] AttributeRepositoryMnesia.put("test_write", %{"key1" => "another value", "key4" => "value"}, @run_opts) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key1"] == "another value" assert obj["key2"] == nil assert obj["key3"] == nil assert obj["key4"] == "value" end test "modify add nonexistant value" do AttributeRepositoryMnesia.modify( "test_write", [ {:add, "key5", "value 5"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key5"] == "value 5" end test "modify add value to existant single attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:add, "key1", "value 2"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert Enum.sort(obj["key1"]) == ["value 1", "value 2"] end test "modify add value to existant multivalued attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:add, "key4", "val5"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert Enum.sort(obj["key4"]) == ["val1", "val2", "val3", "val4", "val5"] end test "modify replace value to nonexisting simple attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:replace, "key5", "some value"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key5"] == "some value" end test "modify replace value to existing simple attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:replace, "key2", "some value"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key2"] == "some value" end test "modify replace value to existing mutlivalued attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:replace, "key4", "some value"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key4"] == "some value" end test "modify replace one specific value to existing mutlivalued attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:replace, "key4", "val2", "val5"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert Enum.sort(obj["key4"]) == ["val1", "val3", "val4", "val5"] end test "modify delete value to existant simple attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:delete, "key1"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key1"] == nil end test "modify delete all values to existant mutlivalued attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:delete, "key4"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert obj["key4"] == nil end test "modify delete one value to existant mutlivalued attribute" do AttributeRepositoryMnesia.modify( "test_write", [ {:delete, "key4", "val3"} ], @run_opts ) obj = AttributeRepositoryMnesia.get!("test_write", :all, @run_opts) assert Enum.sort(obj["key4"]) == ["val1", "val2", "val4"] end test "delete" do AttributeRepositoryMnesia.put("test_delete", %{"key1" => "value", "key2" => "value"}, @run_opts) assert {:ok, _} = AttributeRepositoryMnesia.get("test_delete", :all, @run_opts) assert :ok == AttributeRepositoryMnesia.delete("test_delete", @run_opts) assert {:error, %AttributeRepository.Read.NotFoundError{}} = AttributeRepositoryMnesia.get("test_delete", :all, @run_opts) end end
24.798995
83
0.599189
03610ea65e8214e7cf6113da11cfc8820d9211d5
852
exs
Elixir
mix.exs
sldab/mix_apidoc
cd73a9bba630de2fcbd9ce8e980a8f95494edc84
[ "MIT" ]
8
2015-12-18T20:31:09.000Z
2019-01-07T20:20:41.000Z
mix.exs
techgaun/mix_apidoc
cd73a9bba630de2fcbd9ce8e980a8f95494edc84
[ "MIT" ]
6
2016-05-12T09:12:17.000Z
2018-03-22T20:32:23.000Z
mix.exs
sldab/mix_apidoc
cd73a9bba630de2fcbd9ce8e980a8f95494edc84
[ "MIT" ]
3
2016-02-02T06:53:29.000Z
2019-01-09T16:53:23.000Z
defmodule MixApidoc.Mixfile do use Mix.Project def project do [app: :mix_apidoc, version: "0.5.2", description: "A mix task that triggers apidoc to create documentation " <> "for RESTful web APIs from inline code annotations.", package: package(), elixir: "~> 1.0", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, docs: [extras: ["README.md"]], deps: deps()] end def package do [maintainers: ["Sławomir Dąbek", "Samar Dhwoj Acharya"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/sldab/mix_apidoc"}] end def application do [applications: []] end def deps do [ {:poison, "~> 1.5 or ~> 2.0 or ~> 3.0"}, {:earmark, "~> 0.1 or ~> 1.0", only: :dev}, {:ex_doc, "~> 0.11", only: :dev} ] end end
24.342857
79
0.56338
03611619e3b4b14834df6c55aaf93c051f99e640
4,489
exs
Elixir
apps/tai/test/tai/venue_adapters/okex/product_test.exs
chrism2671/tai-1
847827bd23908adfad4a82c83d5295bdbc022796
[ "MIT" ]
null
null
null
apps/tai/test/tai/venue_adapters/okex/product_test.exs
chrism2671/tai-1
847827bd23908adfad4a82c83d5295bdbc022796
[ "MIT" ]
null
null
null
apps/tai/test/tai/venue_adapters/okex/product_test.exs
chrism2671/tai-1
847827bd23908adfad4a82c83d5295bdbc022796
[ "MIT" ]
1
2020-05-03T23:32:11.000Z
2020-05-03T23:32:11.000Z
defmodule Tai.VenuesAdapters.OkEx.ProductTest do use ExUnit.Case, async: false setup do on_exit(fn -> :ok = Application.stop(:tzdata) end) {:ok, _} = Application.ensure_all_started(:tzdata) :ok end describe ".build/2" do test "returns a product struct from a venue futures instrument" do attrs = %{ instrument_id: "BTC-USDT-200327", trade_increment: "1", tick_size: "0.01", contract_val: "100", listing: "2019-12-13", delivery: "2020-03-27" } instrument = struct(ExOkex.Futures.Instrument, attrs) product = Tai.VenueAdapters.OkEx.Product.build(instrument, :venue_a) assert product.venue_id == :venue_a assert product.symbol == :btc_usdt_200327 assert product.venue_symbol == "BTC-USDT-200327" assert product.status == :trading assert product.price_increment == Decimal.new("0.01") assert product.min_price == Decimal.new("0.01") assert product.size_increment == Decimal.new("1") assert product.min_size == Decimal.new("1") assert product.value == Decimal.new("100") assert %DateTime{} = product.listing assert %DateTime{} = product.expiry assert product.is_inverse == false end test "returns a product struct from a venue swap instrument" do attrs = %{ instrument_id: "BTC-USDT-SWAP", size_increment: "1", tick_size: "0.01", contract_val: "100", listing: "2019-11-12T11:16:48.000Z", delivery: "2020-01-04T08:00:00.000Z", is_inverse: false } instrument = struct(ExOkex.Swap.Instrument, attrs) product = Tai.VenueAdapters.OkEx.Product.build(instrument, :venue_a) assert product.venue_id == :venue_a assert product.symbol == :btc_usdt_swap assert product.venue_symbol == "BTC-USDT-SWAP" assert product.status == :trading assert product.price_increment == Decimal.new("0.01") assert product.min_price == Decimal.new("0.01") assert product.size_increment == Decimal.new("1") assert product.min_size == Decimal.new("1") assert product.value == Decimal.new("100") assert %DateTime{} = product.listing assert product.expiry == nil assert product.is_inverse == false end test "returns a product struct from a venue spot instrument" do attrs = %{ instrument_id: "BTC-USDT", size_increment: "0.00000001", min_size: "0.001", tick_size: "0.1" } instrument = struct(ExOkex.Spot.Instrument, attrs) product = Tai.VenueAdapters.OkEx.Product.build(instrument, :venue_a) assert product.venue_id == :venue_a assert product.symbol == :btc_usdt assert product.venue_symbol == "BTC-USDT" assert product.status == :trading assert product.price_increment == Decimal.new("0.1") assert product.min_price == Decimal.new("0.1") assert product.size_increment == Decimal.new("0.00000001") assert product.min_size == Decimal.new("0.001") assert product.value == Decimal.new(1) assert product.listing == nil assert product.expiry == nil assert product.is_inverse == false end test "futures products can be inverse" do attrs = %{ instrument_id: "BTC-USD-200327", trade_increment: "1", tick_size: "0.01", contract_val: "100", listing: "2019-12-13", delivery: "2020-03-27", is_inverse: "true" } instrument = struct(ExOkex.Futures.Instrument, attrs) product = Tai.VenueAdapters.OkEx.Product.build(instrument, :venue_a) assert product.venue_id == :venue_a assert product.symbol == :btc_usd_200327 assert product.venue_symbol == "BTC-USD-200327" assert product.is_inverse == true end test "swap products can be inverse" do attrs = %{ instrument_id: "BTC-USD-SWAP", size_increment: "1", tick_size: "0.01", contract_val: "100", listing: "2019-11-12T11:16:48.000Z", delivery: "2020-01-04T08:00:00.000Z", is_inverse: true } instrument = struct(ExOkex.Swap.Instrument, attrs) product = Tai.VenueAdapters.OkEx.Product.build(instrument, :venue_a) assert product.venue_id == :venue_a assert product.symbol == :btc_usd_swap assert product.venue_symbol == "BTC-USD-SWAP" assert product.is_inverse == true end end end
33.251852
74
0.634217
0361845aad193153cd376f56b9859f48a2461ae8
1,164
ex
Elixir
apps/omg_watcher_rpc/lib/web/endpoint.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher_rpc/lib/web/endpoint.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
apps/omg_watcher_rpc/lib/web/endpoint.ex
boolafish/elixir-omg
46b568404972f6e4b4da3195d42d4fb622edb934
[ "Apache-2.0" ]
null
null
null
# Copyright 2019-2020 OmiseGO Pte Ltd # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. defmodule OMG.WatcherRPC.Web.Endpoint do use Phoenix.Endpoint, otp_app: :omg_watcher_rpc use Sentry.Phoenix.Endpoint plug(Plug.RequestId) plug(Plug.Logger, log: :debug) if code_reloading? do plug(Phoenix.CodeReloader) end plug( Plug.Parsers, parsers: [:json], pass: [], json_decoder: Jason ) plug(Plug.MethodOverride) plug(Plug.Head) if Application.get_env(:omg_watcher_rpc, OMG.WatcherRPC.Web.Endpoint)[:enable_cors], do: plug(CORSPlug) plug(OMG.WatcherRPC.Web.Plugs.MethodParamFilter) plug(OMG.WatcherRPC.Web.Router) end
27.714286
86
0.742268
0361b841c725833d29e406644a8ccde535abb695
3,287
ex
Elixir
lib/changelog_web/meta/image.ex
type1fool/changelog.com
fbec3528cc3f5adfdc75b008bb92b17efc4f248f
[ "MIT" ]
1
2020-05-20T16:58:17.000Z
2020-05-20T16:58:17.000Z
lib/changelog_web/meta/image.ex
type1fool/changelog.com
fbec3528cc3f5adfdc75b008bb92b17efc4f248f
[ "MIT" ]
null
null
null
lib/changelog_web/meta/image.ex
type1fool/changelog.com
fbec3528cc3f5adfdc75b008bb92b17efc4f248f
[ "MIT" ]
null
null
null
defmodule ChangelogWeb.Meta.Image do alias ChangelogWeb.Router.Helpers, as: Routes alias ChangelogWeb.{Endpoint, NewsItemView, NewsSourceView, PageView, PersonView, PodcastView, PostView, TopicView} def fb_image(assigns), do: assigns |> get_fb() def fb_image_width(assigns), do: assigns |> get_fb_width() def fb_image_height(assigns), do: assigns |> get_fb_height() def twitter_image(assigns), do: assigns |> get_twitter() defp get_fb(%{podcast: podcast}), do: podcast_image(podcast) defp get_fb(%{view_module: NewsItemView, item: item = %{image: img}}) when is_map(img), do: NewsItemView.image_url(item, :original) defp get_fb(%{view_module: PageView, view_template: "ten.html"}), do: static_image("/images/content/ten/ten-year-social.jpg") defp get_fb(%{view_module: PostView, post: post}) do cond do post.image -> post_image(post) true -> fb_summary_image() end end defp get_fb(_), do: fb_summary_image() defp get_fb_width(%{podcast: _podcast}), do: "3000" defp get_fb_width(%{view_module: NewsItemView, item: %{image: img}}) when is_map(img), do: nil defp get_fb_width(_), do: "1200" defp get_fb_height(%{podcast: _podcast}), do: "1688" defp get_fb_height(%{view_module: NewsItemView, item: %{image: img}}) when is_map(img), do: nil defp get_fb_height(_), do: "630" defp get_twitter(%{view_module: PageView, view_template: "ten.html"}), do: static_image("/images/content/ten/ten-year-social.jpg") defp get_twitter(%{view_module: PodcastView, view_template: "index.html"}), do: podcasts_image() defp get_twitter(%{podcast: podcast}), do: podcast_image(podcast) defp get_twitter(%{view_module: PostView, post: post}) do cond do post.image -> post_image(post) post.author -> person_image(post.author) true -> twitter_summary_image() end end defp get_twitter(%{view_module: NewsItemView, item: item}) do cond do item.author -> person_image(item.author) item.source && item.source.icon -> source_image(item.source) topic = Enum.find(item.topics, &(&1.icon)) -> topic_image(topic) true -> item_type_image(item) end end defp get_twitter(%{view_module: NewsSourceView, source: source}), do: source_image(source) defp get_twitter(%{view_module: PersonView, person: person}) when is_map(person), do: person_image(person) defp get_twitter(%{view_module: TopicView, topic: topic}), do: topic_image(topic) defp get_twitter(_), do: twitter_summary_image() defp item_type_image(item), do: static_image("/images/defaults/type-#{item.type}.png") defp person_image(person), do: PersonView.avatar_url(person, :large) defp podcast_image(podcast), do: static_image("/images/share/twitter-#{podcast.slug}.png") defp podcasts_image, do: static_image("/images/share/twitter-all-podcasts.png") defp post_image(post), do: PostView.image_url(post, :large) defp source_image(source), do: NewsSourceView.icon_url(source, :large) defp static_image(path), do: Routes.static_url(Endpoint, path) defp topic_image(topic), do: TopicView.icon_url(topic, :large) defp fb_summary_image, do: static_image("/images/share/fb-sitewide.png") defp twitter_summary_image, do: static_image("/images/share/twitter-sitewide-summary.png") end
47.637681
133
0.722239
0361dc5f2cc13837cc89a0333d26a3ad0299b8c1
1,473
ex
Elixir
clients/dns/lib/google_api/dns/v1/connection.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
null
null
null
clients/dns/lib/google_api/dns/v1/connection.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dns/lib/google_api/dns/v1/connection.ex
jechol/elixir-google-api
0290b683dfc6491ca2ef755a80bc329378738d03
[ "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.DNS.V1.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.DNS.V1. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # View and manage your data across Google Cloud Platform services "https://www.googleapis.com/auth/cloud-platform", # View your data across Google Cloud Platform services "https://www.googleapis.com/auth/cloud-platform.read-only", # View your DNS records hosted by Google Cloud DNS "https://www.googleapis.com/auth/ndev.clouddns.readonly", # View and manage your DNS records hosted by Google Cloud DNS "https://www.googleapis.com/auth/ndev.clouddns.readwrite" ], otp_app: :google_api_dns, base_url: "https://dns.googleapis.com/" end
35.071429
74
0.726409
0361dcba991cbace3b98a4ee50966e81ae46cb80
1,755
ex
Elixir
clients/firestore/lib/google_api/firestore/v1/model/precondition.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/firestore/lib/google_api/firestore/v1/model/precondition.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/firestore/lib/google_api/firestore/v1/model/precondition.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.Firestore.V1.Model.Precondition do @moduledoc """ A precondition on a document, used for conditional operations. ## Attributes * `exists` (*type:* `boolean()`, *default:* `nil`) - When set to `true`, the target document must exist. When set to `false`, the target document must not exist. * `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - When set, the target document must exist and have been last updated at that time. Timestamp must be microsecond aligned. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :exists => boolean() | nil, :updateTime => DateTime.t() | nil } field(:exists) field(:updateTime, as: DateTime) end defimpl Poison.Decoder, for: GoogleApi.Firestore.V1.Model.Precondition do def decode(value, options) do GoogleApi.Firestore.V1.Model.Precondition.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Firestore.V1.Model.Precondition do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.1
182
0.724786
0361edbe8e43769f225c038cb8cf22ad3690148b
39,087
ex
Elixir
lib/client.ex
ElinksFr/alchemy
4c64e5c619977a62a5674dbd2b1ef29f76f6f44e
[ "MIT" ]
null
null
null
lib/client.ex
ElinksFr/alchemy
4c64e5c619977a62a5674dbd2b1ef29f76f6f44e
[ "MIT" ]
null
null
null
lib/client.ex
ElinksFr/alchemy
4c64e5c619977a62a5674dbd2b1ef29f76f6f44e
[ "MIT" ]
null
null
null
defmodule Alchemy.Client do @moduledoc """ Represents a Client connection to the Discord API. This is the main public interface for the REST API. As you might have seen in other examples, this module is the main entry point for `Alchemy`. `start/2` will start up the necessary modules and caches necessary to hook into discord. You generally want to do this before you do any other work in your bot really. ## Blocking All the requests here will block the process using them. Since all the event handles and commands created with this framework run in concurrent processes, this isn't usually an issue. If you do want to "fire and forget", it's easy to wrap these requests in a task. ## Caching In general, you should try and use the functions provided by `Alchemy.Cache` over the requests in this module, because the cache functions will be much faster, and avoid excess API requests. """ use Supervisor require Logger alias Alchemy.Discord.{Users, Channels, Guilds, Invites, RateManager} alias Alchemy.Discord.Gateway.Manager, as: GatewayManager alias Alchemy.Discord.Gateway.RateLimiter.RateSupervisor, as: GatewayRates alias Alchemy.Discord.Gateway.RateLimiter, as: GatewayLimiter alias Alchemy.{Channel, Reaction.Emoji, Embed, Guild, Message, User, VoiceRegion} alias Alchemy.Cache.Supervisor, as: CacheSupervisor alias Alchemy.EventStage.StageSupervisor alias Alchemy.Voice.Supervisor, as: VoiceSupervisor import Alchemy.Discord.RateManager, only: [send_req: 2] use Alchemy.Discord.Types @doc """ Starts up a new Client with the given token. An optional `selfbot: id` can be passed, indiciating that you're using a user token instead of a normal bot token. SelfBots will only respond to themselves, and certain functionalities of the API may not work as well as for normal bots. """ @spec start(token, selfbot: snowflake) :: {:ok, pid} def start(token, options \\ []) do start_link(token, options) end @doc false def start_link(token, options) do # fails if the key isn't present if options[:selfbot] do Application.put_env(:alchemy, :self_bot, " ") end Supervisor.start_link(__MODULE__, {token, options}, name: Client) end # This creates a `RateManager`, under the name `API` that will be available # for managing requests. def init({token, options}) do base = [ worker(RateManager, [token]), worker(GatewayManager, [token, options]), supervisor(GatewayRates, []), supervisor(CacheSupervisor, []), supervisor(StageSupervisor, [options]) ] # don't even start the voice section if the path isn't set children = if Application.get_env(:alchemy, :ffmpeg_path) do [supervisor(VoiceSupervisor, []) | base] else base end supervise(children, strategy: :one_for_one) end ### Public ### @type unicode :: String.t() @type channel_id :: snowflake @type message_id :: snowflake @doc """ Gets a user by their client_id. `"@me"` can be passed to get the info relevant to the Client. ## Examples ```elixir iex> {:ok, user} = Client.get_user("client_id") {:ok, Alchemy.User%{.... ``` """ @spec get_user(snowflake) :: {:ok, User.t()} | {:error, term} def get_user(client_id) do {Users, :get_user, [client_id]} |> send_req("/users/#{client_id}") end @doc """ Edits the client's user_name and/or avatar. ## Options - `user_name` A string specifiying the new user_name for the client - `avatar` A link to an image for the client's avatar ## Examples ```elixir # Will edit "behind the scenes" Client.edit_profile(username: "NewGuy", avatar: "imgur.com/image.jpeg") ``` ```elixir iex> {:ok, user} = Client.edit_profile(username: "NewName") {:ok, Alchemy.User%{.... ``` """ @spec edit_profile( username: String.t(), avatar: url ) :: {:ok, User.t()} | {:error, term} def edit_profile(options) do {Users, :modify_user, [options]} |> send_req("/users/@me") end @doc """ Gets a list of guilds the client is currently a part of. ## Examples ```elixir {:ok, guilds} = Client.current_guilds ``` """ @spec get_current_guilds() :: {:ok, [User.user_guild()]} | {:error, term} def get_current_guilds do {Users, :get_current_guilds, []} |> send_req("/users/@me/guilds") end @doc """ Makes the client leave a guild. ## Examples ```elixir Client.leave_guild(guild_id) ``` """ @spec leave_guild(snowflake) :: {:ok, nil} | {:error, term} def leave_guild(guild_id) do {Users, :leave_guild, [guild_id]} |> send_req("/users/@me/guilds/#{guild_id}") end @doc """ Gets a list of private channels open with this user. ## Examples ```elixir Client.get_DMs() ``` """ @spec get_DMs :: [Channel.dm_channel()] def get_DMs do {Users, :get_DMs, []} |> send_req("/users/@me/channels") end @doc """ Opens a new private channel with a user. ## Examples ```elixir Cogs.def dm_me do Client.create_DM(message.author.id) end ``` """ @spec create_DM(snowflake) :: Channel.dm_channel() def create_DM(user_id) do {Users, :create_DM, [user_id]} |> send_req("/users/@me/channels") end @doc """ Gets a channel by its ID. Works on both private channels, and guild channels. ## Examples ```elixir {:ok, channel} = Client.get_channel("id") ``` """ @spec get_channel(snowflake) :: {:ok, Channel.t()} | {:error, term} def get_channel(channel_id) do {Channels, :get_channel, [channel_id]} |> send_req("/channels/#{channel_id}") end @doc """ Edits a channel in a guild, referenced by id. All the paramaters are optional. Some are mutually exclusive. I.E. you can't use voice only and text only parameters in the same request. ## Options - `name` the name for the channel - `position` the position in the left hand listing - `topic` ~ *text only* ~ the topic of the channel - `bitrate` ~ *voice only* ~ the bitrate, in bits, from `8000` to `96000`, for the voice channel to take - `user_limit` ~ *voice only* ~ the max amount of users allowed in this channel. From `1` to `99`, or `0` for no limit. - `nsfw` whether or not the channel is nsfw - `parent_id` the id of the new parent category for a channel ## Examples ```elixir Client.edit_channel(id, name: "the best channel", position: 1) ``` ```elixir {:ok, new_voice_channel} = Client.edit_channel(id, bitrate: 8000) ``` """ @spec edit_channel(snowflake, name: String.t(), position: Integer, topic: String.t(), bitrate: Integer, user_limit: Integer, nsfw: Boolean.t(), parent_id: snowflake ) :: {:ok, Channel.t()} | {:error, term} def edit_channel(channel_id, options) do {Channels, :modify_channel, [channel_id, options]} |> send_req("/channels/#{channel_id}") end @doc """ Deletes a channel from a guild. Here's an example of how to deal with the possible return types using pattern matching: ```elixir def my_delete(id) do {:ok, channel} = Client.delete_channel(id) case channel do %DMChannel{} -> "this is a private channel!" %TextChannel{} -> "this is a normal channel!" end end ``` """ @spec delete_channel(snowflake) :: {:ok, Channel.t()} | {:error, term} def delete_channel(channel_id) do {Channels, :delete_channel, [channel_id]} |> send_req("/channels/#{channel_id}") end @doc """ Gets up to `100` messages from a channel. `around`, `before`, `after` are all mutually exclusive. ## Options - `around` will search for messages around the time of a particular message - `before` will get messages before a certain message - `after` will get messages after a certain message - `limit` the number of messages to get. Defaults to `100` ## Examples ```elixir {:ok, messages} = Client.get_messages(around: id, limit: 40) ``` """ @spec get_messages(snowflake, around: snowflake, before: snowflake, after: snowflake, limit: Integer ) :: {:ok, [Message.t()]} | {:error, term} def get_messages(channel_id, options) do options = Keyword.put_new(options, :limit, 100) {Channels, :channel_messages, [channel_id, options]} |> send_req("/channels/#{channel_id}/messages") end @doc """ Gets a message by channel, and message_id Use `get_messages` for a bulk request instead. ## Examples ```elixir {:ok, message} = Client.get_message(channel, id) """ @spec get_message(snowflake, snowflake) :: {:ok, Message.t()} | {:error, term} def get_message(channel_id, message_id) do {Channels, :channel_message, [channel_id, message_id]} |> send_req("/channels/#{channel_id}/messages/#{message_id}") end @doc """ Sends a message to a particular channel ## Options - `tts` used to set whether or not a message should be text to speech - `embed` used to send an `Embed` object along with the message - `file` used to send a file along with the message ## Examples ```elixir {:ok, message} = Client.send_message(chan_id, "pong!") ``` Sending files along with messages is simple as well. ```elixir Client.send_message(chan_id, "here you go!", file: "foo.txt") ``` """ @spec send_message(String.t(), tts: Boolean, embed: Embed.t(), file: Path.t() ) :: {:ok, Message.t()} | {:error, term} def send_message(channel_id, content, options \\ []) do {_, options} = options |> Keyword.put(:content, "#{content}") |> Keyword.get_and_update(:embed, fn nil -> :pop some -> {some, Embed.build(some)} end) {Channels, :create_message, [channel_id, options]} |> send_req("/channels/#{channel_id}/messages") end @doc """ Edits a message's contents. ## Examples ```elixir {:ok, message} = Client.send_message(channel, "ping!") Process.sleep(1000) Client.edit_message(message, "not ping anymore!") ``` """ @spec edit_message( Message.t() | {channel_id, message_id}, String.t() ) :: {:ok, Message.t()} | {:error, term} def edit_message(message, content, opts \\ []) do {channel_id, message_id} = case message do %Message{channel_id: channel_id, id: id} -> {channel_id, id} tuple -> tuple end opts = Keyword.put(opts, :content, content) {Channels, :edit_message, [channel_id, message_id, opts]} |> send_req("/channels/#{channel_id}/messages") end @doc """ Edits a previously sent embed. Note that this can be accomplished via `edit_message/3` as well, but that requires editing the content as well. ```elixir Cogs.def embed do embed = %Embed{description: "the best embed"} |> color(0xc13261) {:ok, message} = Embed.send(embed) Process.sleep(2000) Client.edit_embed(message, embed |> color(0x5aa4d4)) end ``` """ @spec edit_embed(Message.t() | {channel_id, message_id}, Embed.t()) :: {:ok, Message.t()} | {:error, term} def edit_embed(message, embed) def edit_embed(%Message{channel_id: channel_id, id: id}, embed) do {Channels, :edit_message, [channel_id, id, [embed: Embed.build(embed)]]} |> send_req("/channels/#{channel_id}/messages") end def edit_embed({channel_id, id}, embed) do {Channels, :edit_message, [channel_id, id, [embed: Embed.build(embed)]]} |> send_req("/channels/#{channel_id}/messages") end @doc """ Deletes a message. Requires the `MANAGE_MESSAGES` permission for messages not sent by the user. ## Examples ```elixir content = "self destructing in 1s!!!" {:ok, message} = Client.send_message(channel_id, content) Process.sleep(1000) Client.delete_message(message) ``` """ @spec delete_message(Message.t() | {channel_id, message_id}) :: {:ok, nil} | {:error, term} def delete_message(message) def delete_message(%Message{channel_id: channel_id, id: id}) do {Channels, :delete_message, [channel_id, id]} |> send_req("del/channels/#{channel_id}/messages") end def delete_message({channel_id, message_id}) do {Channels, :delete_message, [channel_id, message_id]} |> send_req("del/channels/#{channel_id}/messages") end @doc """ Deletes a list of messages. Requires the `MANAGE_MESSAGES` permission for messages not posted by this user. Can only delete messages up to 2 weeks old. ```elixir Cogs.def countdown do {:ok, m1} = Cogs.say "3..." Process.sleep(1000) {:ok, m2} = Cogs.say "2..." Process.sleep(1000) {:ok, m3} = Cogs.say "1..." Process.sleep(1000) Client.delete_messages(message.channel, [m1, m2, m3]) end """ @spec delete_messages(snowflake, [Message.t() | snowflake]) :: {:ok, nil} | {:error, term} def delete_messages(channel_id, messages) do messages = Enum.map(messages, fn %{id: id} -> id id -> id end) {Channels, :delete_messages, [channel_id, messages]} |> send_req("del/channels/#{channel_id}/messages/bulk-delete") end @doc """ Adds a reaction to a message. This supports sending either a custom emoji object, or a unicode literal. While sending raw unicode is technically possible, you'll usually run into url encoding issues due to hidden characters if you try to send something like "❤️️"; use `\\u2764` instead. ## Examples ```elixir Cogs.def heart do Client.add_reaction(message, "️\\u2764") end ``` """ @spec add_reaction( Message.t() | {channel_id, message_id}, unicode | Emoji.t() ) :: {:ok, nil} | {:error, term} def add_reaction(message, emoji) def add_reaction(%Message{channel_id: channel_id, id: id}, emoji) do emoji = Emoji.resolve(emoji) {Channels, :create_reaction, [channel_id, id, emoji]} |> send_req("/channels/#{channel_id}/messages/reactions/@me") end def add_reaction({channel_id, message_id}, emoji) do emoji = Emoji.resolve(emoji) {Channels, :create_reaction, [channel_id, message_id, emoji]} |> send_req("/channels/#{channel_id}/messages/reactions/@me") end @doc """ Removes a reaction on a message, posted by this user. This doesn't require the `MANAGE_MESSAGES` permission, unlike `delete_reaction`. ## Example ```elixir Cogs.def indecisive do Client.add_reaction(message, "\u2764") Process.sleep(3000) Client.remove_reaction(message, "\u2764") end ``` """ @spec remove_reaction( Message.t() | {channel_id, message_id}, unicode | Emoji.t() ) :: {:ok, nil} | {:error, term} def remove_reaction(message, emoji) def remove_reaction(%Message{channel_id: channel_id, id: id}, emoji) do emoji = Emoji.resolve(emoji) {Channels, :delete_own_reaction, [channel_id, id, emoji]} |> send_req("/channels/#{channel_id}/messages/reactions/@me") end def remove_reaction({channel_id, message_id}, emoji) do emoji = Emoji.resolve(emoji) {Channels, :delete_own_reaction, [channel_id, message_id, emoji]} |> send_req("/channels/#{channel_id}/messages/reactions/@me") end @doc """ Deletes a reaction added by another user. Requires the `MANAGE_MESSAGES` permission. """ @spec delete_reaction( Message.t() | {channel_id, message_id}, unicode | Emoji.t(), snowflake | User.t() ) :: {:ok, nil} | {:error, term} def delete_reaction(message, emoji, user) def delete_reaction(%Message{channel_id: channel_id, id: id}, emoji, user) do emoji = Emoji.resolve(emoji) user = case user do %User{id: id} -> id id -> id end {Channels, :delete_reaction, [channel_id, id, emoji, user]} |> send_req("/channels/#{channel_id}/messages/reactions") end def delete_reaction({channel_id, message_id}, emoji, user) do emoji = Emoji.resolve(emoji) user = case user do %User{id: id} -> id id -> id end {Channels, :delete_reaction, [channel_id, message_id, emoji, user]} |> send_req("/channels/#{channel_id}/messages/reactions") end @doc """ Gets a list of users who reacted to message with a particular emoji. ## Examples Cogs.def react do {:ok, message} = Cogs.say("react to this!") Process.sleep(10000) {:ok, users} = Client.get_reactions(message, "\u2764") Cogs.say("#\{length(users)\} users reacted with a \u2764!") end """ @spec get_reactions( Message.t() | {channel_id, message_id}, unicode | Emoji.t() ) :: {:ok, [User.t()]} | {:error, term} def get_reactions(%Message{channel_id: channel_id, id: id}, emoji) do emoji = Emoji.resolve(emoji) {Channels, :get_reactions, [channel_id, id, emoji]} |> send_req("/channels/#{channel_id}/messages/reactions") end def get_reactions({channel_id, message_id}, emoji) do emoji = Emoji.resolve(emoji) {Channels, :get_reactions, [channel_id, message_id, emoji]} |> send_req("/channels/#{channel_id}/messages/reactions") end @doc """ Removes all reactions from a message. Requires the `MANAGE_MESSAGES` permission. ## Examples ```elixir Cogs.def psyche do {:ok, message} = Cogs.say("react to this") Process.sleep(10000) Client.delete_reactions(message) end ``` """ @spec remove_reactions(Message.t() | {channel_id, message_id}) :: {:ok, nil} | {:error, term} def remove_reactions(message) def remove_reactions(%Message{channel_id: channel_id, id: id}) do {Channels, :delete_reactions, [channel_id, id]} |> send_req("/channels/#{channel_id}/messages/reactions") end def remove_reactions({channel_id, message_id}) do {Channels, :delete_reactions, [channel_id, message_id]} |> send_req("/channels/#{channel_id}/messages/reactions") end @doc """ Gets a list of invites for a channel. Only usable for guild channels. ## Examples ```elixir Cogs.def count_invites do {:ok, invites} = Client.get_channel_invites(message.channel_id) Cogs.say("there are #\{length(invites)\} invites active in this channel") end """ @spec get_channel_invites(snowflake) :: {:ok, [Channel.invite()]} | {:error, term} def get_channel_invites(channel_id) do {Channels, :get_channel_invites, [channel_id]} |> send_req("/channels/#{channel_id}/invites") end @doc """ Creates a new invite for a channel. Requires the `CREATE_INSTANT_INVITE` permission. ## Options - `max_age` The duration (seconds) of the invite. `0` for never. - `max_uses` The max number of uses. `0` for unlimited. - `temporary` Whether this invite grants temporary membership. - `unique` When set, a similar invite won't try to be used. Useful for creating unique one time use invites. ## Examples ```elixir Cogs.def invite do {:ok, invite} = Client.create_invite(message.channel_id, max_age: 0) Cogs.say("Here you go:\\nhttps://discord.gg/#\{invite.code\}") end ``` """ @spec create_invite(snowflake, max_age: Integer, max_uses: Integer, temporary: Boolean, unique: True ) :: {:ok, Channel.invite()} | {:error, term} def create_invite(channel_id, options \\ []) do {Channels, :create_channel_invite, [channel_id, options]} |> send_req("/channels/#{channel_id}/invites") end @doc """ Triggers the typing indicator. This **shouldn't** be used by bots usually. ## Examples ```elixir Cogs.def hard_math do Client.trigger_typing(message.channel_id) Process.sleep(3000) Cogs.say("done!") end ``` """ @spec trigger_typing(snowflake) :: {:ok, nil} | {:error, term} def trigger_typing(channel_id) do {Channels, :trigger_typing, [channel_id]} |> send_req("/channels/#{channel_id}/typing") end @doc """ Gets a list of pinned messages in a channel. ## Examples ```elixir Cogs.def pins do {:ok, pinned} = Client.get_pins(message.channel_id) Cogs.say("there are #\{length(pinned)\} pins in this channel.") end ``` """ @spec get_pins(snowflake) :: {:ok, [Message.t()]} | {:error, term} def get_pins(channel_id) do {Channels, :get_pinned_messages, [channel_id]} |> send_req("/channels/#{channel_id}/pins") end @doc """ Pins a message to its channel. ## Examples ```elixir Cogs.def pin_this do Client.pin(message) end ``` """ @spec pin(Message.t() | {channel_id, message_id}) :: {:ok, nil} | {:error, term} def pin(%Message{channel_id: channel_id, id: id}) do {Channels, :add_pinned_message, [channel_id, id]} |> send_req("/channels/#{channel_id}/pins") end def pin({channel_id, message_id}) do {Channels, :add_pinned_message, [channel_id, message_id]} |> send_req("/channels/#{channel_id}/pins") end @doc """ Removes a pinned message from a channel. ## Examples ```elixir Cogs.def unpin do {:ok, [first|_]} = Client.get_pins(message.channel_id) Client.unpin(first) end ``` """ @spec unpin(Message.t() | {channel_id, message_id}) :: {:ok, nil} | {:error, term} def unpin(%Message{channel_id: channel_id, id: id}) do {Channels, :delete_pinned_message, [channel_id, id]} |> send_req("/channels/#{channel_id}/pins") end def unpin({channel_id, message_id}) do {Channels, :delete_pinned_message, [channel_id, message_id]} |> send_req("/channels/#{channel_id}/pins") end # CACHESTUB @doc """ Gets info about a certain guild. The info returned here doesn't contain as much info as contained in the cache. For guilds the user is a part of, the cache should be preferred over this method. ```examples Client.get_guild(id) ``` """ @spec get_guild(snowflake) :: {:ok, Guild.t()} | {:error, term} def get_guild(guild_id) do {Guilds, :get_guild, [guild_id]} |> send_req("/guilds/#{guild_id}") end @doc """ Modifies a guild's settings. ## Options - `name` The name of the guild. - `region` The id of the voice region. - `verification_level` The level of verification of the guild. - `default_message_notifications` The default message notification settings. - `afk_channel_id` The id of the afk channel. - `afk_timeout` The afk timeout in seconds. - `icon` A url to the new icon. Must be a 128x128 jpeg image. - `splash` A url to the new splash screen. This is only available for partnered guilds. ## Examples ```elixir Client.edit_guild(guild_id, name: "new name") ``` """ @spec edit_guild(snowflake, name: String.t(), region: snowflake, verification_level: Integer, default_message_notifications: Integer, afk_channel_id: snowflake, afk_timeout: snowflake, icon: url, splash: url ) :: {:ok, Guild.t()} | {:error, term} def edit_guild(guild_id, options) do {Guilds, :modify_guild, [guild_id, options]} |> send_req("/guilds/#{guild_id}") end # CACHESTUB @doc """ Returns a list of channel objects for a guild. As with most guild methods, the cache should be preferred over the api if possible. ## Examples ```elixir Client.get_channels(guild_id) ``` """ @spec get_channels(snowflake) :: {:ok, [Channel.t()]} | {:error, term} def get_channels(guild_id) do {Guilds, :get_channels, [guild_id]} |> send_req("/guilds/#{guild_id}/channels") end @doc """ Creates a new channel in a guild. Requires the `MANAGE_CHANNELS` permission. ## Options - `voice` Setting this creates a new voice channel. - `bitrate` Sets the bitrate (bits) for a voice channel. - `user_limit` Sets the max amount of users for a voice channel. - `permission_overwrites` An overwrite for permissions in that channel ## Examples ```elixir Client.create_channel(guild_id) ``` """ @spec create_channel(snowflake, String.t(), voice: Boolean, bitrate: Integer, user_limit: Integer ) :: {:ok, Channel.t()} | {:error, term} def create_channel(guild_id, name, options \\ []) do {Guilds, :create_channel, [guild_id, name, options]} |> send_req("/guilds/#{guild_id}/channels") end @doc """ Swaps the position of channels in a guild. ## Examples ```elixir # alphabetizes a guild channel list with {:ok, channels} <- Client.get_channels(guild_id) do channels |> Enum.sort_by(& &1.name) |> Stream.map(& &1.id) |> Enum.with_index |> (&Client.move_channels(guild_id, &1)).() end """ @spec move_channels(snowflake, [{snowflake, Integer}]) :: {:ok, nil} | {:error, term} def move_channels(guild_id, pairs) do {Guilds, :move_channels, [guild_id, pairs]} |> send_req("/guilds/#{guild_id}/channels") end # CACHESTUB @doc """ Gets info for a member of a guild. For guilds the bot is in, use the corresponding cache method instead. ## Examples ```elixir Client.get_member(guild_id, user_id) ``` """ @spec get_member(snowflake, snowflake) :: {:ok, Guild.member()} | {:error, term} def get_member(guild_id, user_id) do {Guilds, :get_member, [guild_id, user_id]} |> send_req("/guilds/#{guild_id}/members") end # CACHESTUB @doc """ Gets a list of members from a guild. ## Options - `limit` The number of members to fetch (max 1000). - `after` Setting this to a user id will only fetch members that joined after that person. ## Examples ```elixir Client.get_member_list(guild_id, limit: 10) ``` """ @spec get_member_list(snowflake, limit: Integer, after: snowflake) :: {:ok, [Guild.member()]} | {:error, term} def get_member_list(guild_id, options \\ []) do {Guilds, :get_member_list, [guild_id, options]} |> send_req("/guilds/#{guild_id}/members") end # SUGARSTUB @doc """ Modifies a member in a guild. Each option requires different permissions. ## Options - `nick` The nickname of the user. Requires `:manage_nicknames` - `roles` A list of roles (ids) the user should have after the change. Requires `:manage_roles` - `mute` Whether or not the user should be muted. Requires `:mute_members` - `deaf` Whether or not the user should be deafened. Requires `:deafen_members` - `channel_id` Voice channel to move the user too (if they are connected). Requires `:move_members`, and permission to connect to that channel. ## Examples ```elixir Client.edit_member(guild_id, user_id, nick: "cool guy") ``` """ @spec edit_member(snowflake, snowflake, nick: String.t(), roles: [snowflake], mute: Boolean, deaf: Boolean, channel_id: snowflake ) :: {:ok, nil} | {:error, term} def edit_member(guild_id, user_id, options) do {Guilds, :modify_member, [guild_id, user_id, options]} |> send_req("/guilds/#{guild_id}/members") end @doc """ Modifies the nickname of the current user. ## Examples ```elixir Client.change_nickname(guild_id, "best bot") ``` """ @spec change_nickname(snowflake, String.t()) :: {:ok, nil} | {:error, term} def change_nickname(guild_id, name) do {Guilds, :modify_nick, [guild_id, name]} |> send_req("/guilds/#{guild_id}/members/@me/nick") end # SUGARSTUB @doc """ Adds a role to a member of a guild. Requires the `:manage_roles` permission. ## Examples ```elixir Client.add_role(guild_id, user_id, role_id) ``` """ @spec add_role(snowflake, snowflake, snowflake) :: {:ok, nil} | {:error, term} def add_role(guild_id, user_id, role_id) do {Guilds, :add_role, [guild_id, user_id, role_id]} |> send_req("/guilds/#{guild_id}/members/roles") end # SUGARSTUB @doc """ Removes a role of a guild member. Requires the `:manage_roles` permission. ## Examples ```elixir Client.remove_role(guild_id, user_id, role_id) ``` """ @spec remove_role(snowflake, snowflake, snowflake) :: {:ok, nil} | {:error, term} def remove_role(guild_id, user_id, role_id) do {Guilds, :remove_role, [guild_id, user_id, role_id]} |> send_req("/guilds/#{guild_id}/members/roles") end # SUGARSTUB @doc """ Kicks a member from a guild. Not to be confused with `ban_member/3`. ## Examples ```elixir Client.kick_member(guild_id, user_id) ``` """ @spec kick_member(snowflake, snowflake) :: {:ok, nil} | {:error, term} def kick_member(guild_id, user_id) do {Guilds, :remove_member, [guild_id, user_id]} |> send_req("/guilds/#{guild_id}/members") end # SUGARSTUB @doc """ Gets a list of users banned from this guild. Requires the `:ban_members` permission. ## Examples ```elixir {:ok, bans} = Client.get_bans(guild_id) ``` """ @spec get_bans(snowflake) :: {:ok, [User.t()]} | {:error, term} def get_bans(guild_id) do {Guilds, :get_bans, [guild_id]} |> send_req("/guilds/#{guild_id}/bans") end # SUGARSTUB @doc """ Bans a member from a guild. This prevents a user from rejoining for as long as the ban persists, as opposed to `kick_member/2` which will just make them leave the server. A `days` paramater can be set to delete x days of messages; limited to 7. ## Examples ```elixir Client.ban_member(guild_id, user_id, 1) ``` """ @spec ban_member(snowflake, snowflake) :: {:ok, nil} | {:error, term} def ban_member(guild_id, user_id, days \\ 0) do {Guilds, :create_ban, [guild_id, user_id, days]} |> send_req("/guilds/#{guild_id}/bans") end # SUGARSTUB @doc """ Unbans a user from the server. ## Examples ```elixir Client.unban_member(guild_id, user_id) ``` """ @spec unban_member(snowflake, snowflake) :: {:ok, nil} | {:error, term} def unban_member(guild_id, user_id) do {Guilds, :remove_ban, [guild_id, user_id]} |> send_req("/guilds/#{guild_id}/bans") end @doc """ Gets a list of roles available in a guild. Requires the `:manage_roles` permission. ## Examples ```elixir Client.get_roles(guild_id) ``` """ @spec get_roles(snowflake) :: {:ok, [Guild.role()]} | {:error, term} def get_roles(guild_id) do {Guilds, :get_roles, [guild_id]} |> send_req("/guilds/#{guild_id}/roles") end @doc """ Creates a new role in the guild. Requires the `:manage_roles` permission. ## Options - `name` The name of the new role. Defaults to "new role" - `permissions` The set of permissions for that role. Defaults to the `@everyone` permissions in that guild. - `color` The color of the role. Defaults to `0x000000` - `hoist` When set to `true`, the role will be displayed seperately in the sidebar. - `mentionable` When set to `true`, allows the role to be mentioned. ## Examples ```elixir Client.create_role(guild_id, name: "the best role", color: 0x4bd1be) ``` """ @spec create_role(snowflake, name: String.t(), permissions: Integer, color: Integer, hoist: Booean, mentionable: Boolean ) :: {:ok, Guild.role()} | {:error, term} def create_role(guild_id, options) do {Guilds, :create_role, [guild_id, options]} |> send_req("/guilds/#{guild_id}/roles") end @doc """ Edits a preexisting role in a guild. The same as `create_role/2` except that this operates on a role that has already been created. See that function for discussion. """ @spec edit_role(snowflake, snowflake, name: String.t(), permissions: Integer, color: Integer, hoist: Booean, mentionable: Boolean ) :: {:ok, Guild.role()} | {:error, term} def edit_role(guild_id, role_id, options) do {Guilds, :modify_role, [guild_id, role_id, options]} |> send_req("/guilds/#{guild_id}/roles") end @doc """ Removes a role from a guild. Requires the `:manage_roles` permission. """ @spec delete_role(snowflake, snowflake) :: {:ok, nil} | {:error, term} def delete_role(guild_id, role_id) do {Guilds, :delete_role, [guild_id, role_id]} |> send_req("/guilds/#{guild_id}/roles") end @doc """ Modifies the position of roles in a guild. Takes a list of `{id, position}` where `position` is an integer starting at 0, and `id` is the id of the role. Returns a list of all the roles in the guild. Requires the `:manage_roles` permission. """ @spec move_roles(snowflake, [{snowflake, Integer}]) :: {:ok, [Guild.role()]} | {:error, term} def move_roles(guild_id, pairs) do {Guilds, :move_roles, [guild_id, pairs]} |> send_req("/guilds/#{guild_id}/roles") end @doc """ Returns a count of members who would be kicked in a prune operation. Days specifies the amount of days of inactivity to check for. See `prune_guild/2` for a discussion of this operation. """ @spec get_prune_count(snowflake, Integer) :: {:ok, nil} | {:error, term} def get_prune_count(guild_id, days) do {Guilds, :get_prune_count, [guild_id, days]} |> send_req("/guilds/#{guild_id}/prune") end @doc """ Removes inactive members of a guild. Days allows you to specify the amount of days of inactivity necessary to be kicked from the guild. Requires the `:manage_roles` permission ## Examples ```elixir Client.prune_guild(guild_id, ) ``` """ @spec prune_guild(snowflake, Integer) :: {:ok, nil} | {:error, term} def prune_guild(guild_id, days) do {Guilds, :prune_guild, [guild_id, days]} |> send_req("/guilds/#{guild_id}/prune") end @doc """ Returns a list of voice regions in a guild. """ @spec get_regions(snowflake) :: {:ok, [VoiceRegion.t()]} | {:error, term} def get_regions(guild_id) do {Guilds, :get_regions, [guild_id]} |> send_req("/guilds/#{guild_id}/regions") end @doc """ Returns a list of invites for a guild. Requires the `:manage_guild` permission. """ @spec get_invites(snowflake) :: {:ok, [Channel.invite()]} | {:error, term} def get_invites(guild_id) do {Guilds, :get_invites, [guild_id]} |> send_req("/guilds/#{guild_id}/invites") end @doc """ Gets a list of integration objects for a guild. Requires the `:manage_guild` permission. """ @spec get_integrations(snowflake) :: {:ok, %{}} | {:error, term} def get_integrations(guild_id) do {Guilds, :get_integrations, [guild_id]} |> send_req("/guilds/#{guild_id}/integrations") end @doc """ Edits an integration of a guild. Requires the `:manage_guild` permission. ## Options - `expire_behaviour` The behaviour when an integration subscription lapses. - `expire_grace_period` Period (seconds) where the integration ignores lapsed subscriptions. - `enable_emoticons` Whether or not emoticons should be synced for this integration. """ @spec edit_integration(snowflake, snowflake, expire_behaviour: Integer, expire_grace_period: Integer, enable_emoticons: Boolean ) :: {:ok, nil} | {:error, term} def edit_integration(guild_id, integration_id, options) do {Guilds, :edit_integration, [guild_id, integration_id, options]} |> send_req("/guilds/#{guild_id}/integrations") end @doc """ Removes an integration from a guild. Requires the `:manage_guild` permission. """ @spec delete_integration(snowflake, snowflake) :: {:ok, nil} | {:error, term} def delete_integration(guild_id, integration_id) do {Guilds, :delete_integration, [guild_id, integration_id]} |> send_req("/guilds/#{guild_id}/integrations") end @doc """ Syncs a guild integration. Requires the `:manage_guild` permission. """ @spec sync_integration(snowflake, snowflake) :: {:ok, nil} | {:error, term} def sync_integration(guild_id, integration_id) do {Guilds, :sync_integration, [guild_id, integration_id]} |> send_req("/guilds/#{guild_id}/integrations/sync") end @doc """ Returns a list of all possible voice regions. """ @spec list_voice_regions :: {:ok, [VoiceRegion.t()]} | {:error, term} def list_voice_regions do {Guilds, :get_all_regions, []} |> send_req("voice/regions") end @doc """ Gets the information for a single invite. Not to be confused with `get_invites/1`, which lists out the invites in a guild. This merely gets the information relating to a single invite, accessed by its code. """ @spec get_invite(String.t()) :: {:ok, Channel.invite()} | {:error, term} def get_invite(invite_code) do {Invites, :get_invite, [invite_code]} |> send_req("/invites") end @doc """ Deletes an invite. After deletion the invite can no longer be used, as you might expect. """ @spec delete_invite(String.t()) :: {:ok, nil} | {:error, term} def delete_invite(invite_code) do {Invites, :delete_invite, [invite_code]} |> send_req("/invites") end @doc """ Updates the status of the client. The status displays either "playing Game", or a "streaming Game" message under the client, as well setting an inactivity based on idleness. `playing: game` specifies that you're playing, but not streaming a game. `streaming: {game, twitch}` acts in a similar way, except that it will also have a link to that twitch stream. You should only pass in the handle, and not the full stream link, i.e. "foobar" instead of "twitch.tv/foobar". `idle_since` can be specified, using unix time, in milliseconds, to indicate for how long the client has been idle. ## Note on ratelimiting This functionality is *heavily* ratelimited, at a rate of 1 req / 12s. Because of this, this function will automatically error after 24s of waiting. Because of how long this may take, you might want to run this in a new task. ## Examples ```elixir Client.update_status("Alchemy") ``` """ @spec update_status(Integer, playing: String.t(), streaming: {String.t(), String.t()}) :: :ok | {:error, String.t()} def update_status(idle_since \\ nil, game_info) def update_status(idle_since, playing: game) do do_update_status(idle_since, {:playing, game}) end def update_status(idle_since, streaming: {game, twitch_handle}) do do_update_status(idle_since, {:streaming, game, twitch_handle}) end defp do_update_status(idle_since, info) do pids = Supervisor.which_children(GatewayRates) |> Stream.map(fn {_, pid, _, _} -> pid end) try do Enum.map(pids, fn pid -> GatewayLimiter.status_update(pid, idle_since, info) |> Task.await(24_000) end) :ok catch :exit, _ -> {:error, "Took longer than 24s to update statuses. " <> "You might be using the function too often; " <> "it has a ratelimit of 1 req / 12s."} end end end
28.282923
91
0.646762
036206af6bdea651df836d9d2d07b75b19ba1958
460
ex
Elixir
lib/errors/cast_error.ex
ZennerIoT/casconf
949ecef6bc52f381a952c16b17fd876f3ba51975
[ "MIT" ]
2
2019-03-27T12:02:05.000Z
2019-05-22T03:08:57.000Z
lib/errors/cast_error.ex
ZennerIoT/casconf
949ecef6bc52f381a952c16b17fd876f3ba51975
[ "MIT" ]
null
null
null
lib/errors/cast_error.ex
ZennerIoT/casconf
949ecef6bc52f381a952c16b17fd876f3ba51975
[ "MIT" ]
null
null
null
defmodule Casconf.CastError do defexception [ loader: nil, loader_opts: nil, value: nil, type: nil ] def exception(value) do struct(__MODULE__, Keyword.take(value, ~w[loader loader_opts value type]a)) end def message(%__MODULE__{} = error) do load_description = error.loader.describe_load(error.loader_opts) "Value #{inspect(error.value)} (#{load_description}) could not be converted to #{inspect error.type}" end end
25.555556
105
0.702174
0362325ed30a576b3cb63e9687ec792e279074c6
1,973
ex
Elixir
clients/reseller/lib/google_api/reseller/v1/model/subscription_plan_commitment_interval.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/reseller/lib/google_api/reseller/v1/model/subscription_plan_commitment_interval.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/reseller/lib/google_api/reseller/v1/model/subscription_plan_commitment_interval.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.Reseller.V1.Model.SubscriptionPlanCommitmentInterval do @moduledoc """ In this version of the API, annual commitment plan's interval is one year. *Note: *When billingMethod value is OFFLINE, the subscription property object plan.commitmentInterval is omitted in all API responses. ## Attributes * `endTime` (*type:* `String.t`, *default:* `nil`) - An annual commitment plan's interval's endTime in milliseconds using the UNIX Epoch format. See an example Epoch converter. * `startTime` (*type:* `String.t`, *default:* `nil`) - An annual commitment plan's interval's startTime in milliseconds using UNIX Epoch format. See an example Epoch converter. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :endTime => String.t(), :startTime => String.t() } field(:endTime) field(:startTime) end defimpl Poison.Decoder, for: GoogleApi.Reseller.V1.Model.SubscriptionPlanCommitmentInterval do def decode(value, options) do GoogleApi.Reseller.V1.Model.SubscriptionPlanCommitmentInterval.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Reseller.V1.Model.SubscriptionPlanCommitmentInterval do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.46
212
0.749113
0362494b279b0759b438fc37295414ecc3bb155d
12,693
exs
Elixir
test/unit/hologram/compiler/transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
40
2022-01-19T20:27:36.000Z
2022-03-31T18:17:41.000Z
test/unit/hologram/compiler/transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
42
2022-02-03T22:52:43.000Z
2022-03-26T20:57:32.000Z
test/unit/hologram/compiler/transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
3
2022-02-10T04:00:37.000Z
2022-03-08T22:07:45.000Z
defmodule Hologram.Compiler.TransformerTest do use Hologram.Test.UnitCase, async: true alias Hologram.Compiler.{Context, Transformer} alias Hologram.Compiler.IR.{ AccessOperator, AdditionOperator, AliasDirective, AnonymousFunctionCall, AnonymousFunctionType, AtomType, BinaryType, Block, BooleanType, CaseExpression, ConsOperator, DivisionOperator, DotOperator, EqualToOperator, FloatType, FunctionDefinition, FunctionCall, IfExpression, ImportDirective, IntegerType, LessThanOperator, ListConcatenationOperator, ListSubtractionOperator, ListType, MacroDefinition, MapType, MatchOperator, MembershipOperator, ModuleDefinition, ModuleAttributeDefinition, ModuleAttributeOperator, ModulePseudoVariable, ModuleType, MultiplicationOperator, NilType, NotEqualToOperator, ProtocolDefinition, Quote, RelaxedBooleanAndOperator, RelaxedBooleanNotOperator, RelaxedBooleanOrOperator, RequireDirective, StrictBooleanAndOperator, StringType, StructType, SubtractionOperator, TupleType, TypeOperator, Typespec, UnaryNegativeOperator, UnaryPositiveOperator, Unquote, UseDirective, Variable } describe "operators" do test "access" do code = "a[:b]" ast = ast(code) assert %AccessOperator{} = Transformer.transform(ast, %Context{}) end test "addition" do code = "1 + 2" ast = ast(code) assert %AdditionOperator{} = Transformer.transform(ast, %Context{}) end test "cons" do code = "[h | t]" ast = ast(code) assert %ConsOperator{} = Transformer.transform(ast, %Context{}) end test "division" do code = "1 / 2" ast = ast(code) assert %DivisionOperator{} = Transformer.transform(ast, %Context{}) end test "dot" do code = "a.b" ast = ast(code) assert %DotOperator{} = Transformer.transform(ast, %Context{}) end test "equal to" do code = "1 == 2" ast = ast(code) assert %EqualToOperator{} = Transformer.transform(ast, %Context{}) end test "less than" do code = "1 < 2" ast = ast(code) assert %LessThanOperator{} = Transformer.transform(ast, %Context{}) end test "list concatenation" do code = "[1, 2] ++ [3, 4]" ast = ast(code) assert %ListConcatenationOperator{} = Transformer.transform(ast, %Context{}) end test "list subtraction" do code = "[1, 2] -- [3, 2]" ast = ast(code) assert %ListSubtractionOperator{} = Transformer.transform(ast, %Context{}) end test "match" do code = "a = 1" ast = ast(code) assert %MatchOperator{} = Transformer.transform(ast, %Context{}) end test "membership" do code = "1 in [1, 2]" ast = ast(code) assert %MembershipOperator{} = Transformer.transform(ast, %Context{}) end test "module attribute" do code = "@a" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %ModuleAttributeOperator{name: :a} end test "multiplication" do code = "1 * 2" ast = ast(code) assert %MultiplicationOperator{} = Transformer.transform(ast, %Context{}) end test "not equal to" do code = "1 != 2" ast = ast(code) assert %NotEqualToOperator{} = Transformer.transform(ast, %Context{}) end test "pipe" do code = "100 |> div(2)" ast = ast(code) assert %FunctionCall{} = Transformer.transform(ast, %Context{}) end test "relaxed boolean and" do code = "true && false" ast = ast(code) assert %RelaxedBooleanAndOperator{} = Transformer.transform(ast, %Context{}) end test "relaxed boolean not, block AST" do code = "!false" ast = ast(code) assert %RelaxedBooleanNotOperator{} = Transformer.transform(ast, %Context{}) end test "relaxed boolean not, non-block AST" do code = "true && !false" ast = ast(code) assert %RelaxedBooleanAndOperator{right: %RelaxedBooleanNotOperator{}} = Transformer.transform(ast, %Context{}) end test "relaxed boolean or" do code = "true || false" ast = ast(code) assert %RelaxedBooleanOrOperator{} = Transformer.transform(ast, %Context{}) end test "strict boolean and" do code = "true and false" ast = ast(code) assert %StrictBooleanAndOperator{} = Transformer.transform(ast, %Context{}) end test "subtraction" do code = "1 - 2" ast = ast(code) assert %SubtractionOperator{} = Transformer.transform(ast, %Context{}) end test "type" do code = "str::binary" ast = ast(code) assert %TypeOperator{} = Transformer.transform(ast, %Context{}) end test "unary negative" do code = "-2" ast = ast(code) assert %UnaryNegativeOperator{} = Transformer.transform(ast, %Context{}) end test "unary positive" do code = "+2" ast = ast(code) assert %UnaryPositiveOperator{} = Transformer.transform(ast, %Context{}) end end describe "types" do test "anonymous function" do code = "fn -> 1 end" ast = ast(code) assert %AnonymousFunctionType{} = Transformer.transform(ast, %Context{}) end test "atom" do code = ":test" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %AtomType{value: :test} end test "binary" do code = "<<1, 2>>" ast = ast(code) assert %BinaryType{} = Transformer.transform(ast, %Context{}) end test "boolean" do code = "true" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %BooleanType{value: true} end test "float" do code = "1.0" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %FloatType{value: 1.0} end test "integer" do code = "1" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %IntegerType{value: 1} end test "list" do code = "[1, 2]" ast = ast(code) assert %ListType{} = Transformer.transform(ast, %Context{}) end test "map" do code = "%{a: 1, b: 2}" ast = ast(code) assert %MapType{} = Transformer.transform(ast, %Context{}) end test "module from module segments" do code = "Hologram.Compiler.TransformerTest" ast = ast(code) assert %ModuleType{} = Transformer.transform(ast, %Context{}) end test "module from atom" do module = Hologram.Compiler.TransformerTest assert %ModuleType{} = Transformer.transform(module, %Context{}) end test "nil" do code = "nil" ast = ast(code) assert %NilType{} = Transformer.transform(ast, %Context{}) end test "string" do code = "\"test\"" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %StringType{value: "test"} end test "struct" do code = "%Hologram.Test.Fixtures.Compiler.Transformer.Module2{a: 1}" ast = ast(code) assert %StructType{} = Transformer.transform(ast, %Context{}) end test "tuple, 2 elements" do code = "{1, 2}" ast = ast(code) assert %TupleType{} = Transformer.transform(ast, %Context{}) end test "tuple, non-2 elements" do code = "{1, 2, 3}" ast = ast(code) assert %TupleType{} = Transformer.transform(ast, %Context{}) end test "nested" do code = "[1, {2, 3, 4}]" ast = ast(code) result = Transformer.transform(ast, %Context{}) expected = %ListType{ data: [ %IntegerType{value: 1}, %TupleType{ data: [ %IntegerType{value: 2}, %IntegerType{value: 3}, %IntegerType{value: 4} ] } ] } assert result == expected end end describe "definitions" do test "public function" do code = "def test, do: :ok" ast = ast(code) assert %FunctionDefinition{} = Transformer.transform(ast, %Context{}) end test "private function" do code = "defp test, do: :ok" ast = ast(code) assert %FunctionDefinition{} = Transformer.transform(ast, %Context{}) end test "macro" do code = """ defmacro test_macro(a, b) do quote do 1 end end """ ast = ast(code) assert %MacroDefinition{} = Transformer.transform(ast, %Context{}) end test "module" do code = "defmodule Hologram.Test.Fixtures.Compiler.Transformer.Module1 do end" ast = ast(code) assert %ModuleDefinition{} = Transformer.transform(ast, %Context{}) end test "module attribute" do code = "@a 1" ast = ast(code) assert %ModuleAttributeDefinition{} = Transformer.transform(ast, %Context{}) end test "protocol" do code = """ defprotocol Hologram.Test.Fixtures.PlaceholderModule1 do def test_fun(a, b) end """ ast = ast(code) assert %ProtocolDefinition{} = Transformer.transform(ast, %Context{}) end end describe "directives" do test "alias" do code = "alias Hologram.Test.Fixtures.Compiler.Transformer.Module1" ast = ast(code) assert %AliasDirective{} = Transformer.transform(ast, %Context{}) end test "import" do code = "import Hologram.Test.Fixtures.Compiler.Transformer.Module1" ast = ast(code) assert %ImportDirective{} = Transformer.transform(ast, %Context{}) end test "require" do code = "require Hologram.Test.Fixtures.Compiler.Transformer.Module1" ast = ast(code) assert %RequireDirective{} = Transformer.transform(ast, %Context{}) end test "use" do code = "use Hologram.Compiler.TransformerTest" ast = ast(code) assert %UseDirective{} = Transformer.transform(ast, %Context{}) end end describe "control flow" do test "anonymous function call" do code = "test.(123)" ast = ast(code) assert %AnonymousFunctionCall{} = Transformer.transform(ast, %Context{}) end test "case expression" do code = """ case x do %{a: a} -> :ok 2 -> :error end """ ast = ast(code) assert %CaseExpression{} = Transformer.transform(ast, %Context{}) end test "for expression" do code = "for n <- [1, 2], do: n * n" ast = ast(code) assert %FunctionCall{module: Enum, function: :reduce} = Transformer.transform(ast, %Context{}) end test "function called without a module" do code = "test(123)" ast = ast(code) assert %FunctionCall{} = Transformer.transform(ast, %Context{}) end test "function called on module" do code = "Hologram.Compiler.TransformerTest.test(123)" ast = ast(code) assert %FunctionCall{} = Transformer.transform(ast, %Context{}) end test "if expression" do code = "if true, do: 1, else: 2" ast = ast(code) assert %IfExpression{} = Transformer.transform(ast, %Context{}) end end describe "other" do test "block" do ast = {:__block__, [], [1, 2]} assert %Block{} = Transformer.transform(ast, %Context{}) end test "quote" do code = "quote do 1 end" ast = ast(code) assert %Quote{} = Transformer.transform(ast, %Context{}) end test "typespec" do code = "@spec test_fun(atom()) :: list(integer())" ast = ast(code) assert %Typespec{} = Transformer.transform(ast, %Context{}) end test "unquote" do code = "unquote(abc)" ast = ast(code) assert %Unquote{} = Transformer.transform(ast, %Context{}) end test "__MODULE__ macro" do code = "__MODULE__" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %ModulePseudoVariable{} end test "variable, last AST tuple elem is nil" do code = "a" ast = ast(code) result = Transformer.transform(ast, %Context{}) assert result == %Variable{name: :a} end test "variable, last AST tuple elem is module" do ast = {:a, [line: 1], Hologram.Compiler.TransformerTest} result = Transformer.transform(ast, %Context{}) assert result == %Variable{name: :a} end end end
22.952984
100
0.595368
03625a9c50293fbfdfd983fe90a8d2db9bf349d9
1,847
exs
Elixir
mix.exs
walkr/rox
c2ac16299728fa59a9d0871b8b4634f09e113bc8
[ "MIT" ]
2
2018-10-23T21:33:42.000Z
2019-03-30T00:22:19.000Z
mix.exs
walkr/rox
c2ac16299728fa59a9d0871b8b4634f09e113bc8
[ "MIT" ]
null
null
null
mix.exs
walkr/rox
c2ac16299728fa59a9d0871b8b4634f09e113bc8
[ "MIT" ]
1
2018-10-23T01:44:48.000Z
2018-10-23T01:44:48.000Z
defmodule Rox.Mixfile do use Mix.Project def project do [ app: :rox, version: "2.3.0", elixir: "~> 1.4", build_embedded: Mix.env() == :prod, start_permanent: Mix.env() == :prod, compilers: [:rustler] ++ Mix.compilers(), rustler_crates: rustler_crates(), package: package(), description: description(), deps: deps() ] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [extra_applications: [:logger]] end # Type "mix help deps" for more examples and options defp deps do [ # Rust NIFs {:rustler, git: "https://github.com/rusterlium/rustler", sparse: "rustler_mix"}, # Doc generation {:ex_doc, "~> 0.18", only: :dev}, # Benchmarking {:benchfella, "~> 0.3.0", only: :dev}, # Generate fake data {:faker, "~> 0.7", only: :dev}, # Computational flows {:flow, "~> 0.14", only: :dev}, # Producers and consumers {:gen_stage, "~> 0.14", only: :dev}, # Dialyzer support {:dialyxir, "~> 1.0.0-rc.1", only: :dev, runtime: false} ] end defp rustler_crates do [ rox_nif: [ path: "native/rox_nif", cargo: :system, default_features: false, features: [], mode: :release ] ] end defp description do """ Rust powered NIF bindings to Facebook's RocksDB """ end defp package do [ name: :rox, files: [ "lib", "native/rox_nif/Cargo.*", "native/rox_nif/src", "mix.exs", "README.md", "History.md", "LICENSE" ], maintainers: ["Griffin Smith"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/urbint/rox"} ] end end
20.988636
86
0.536546
03626e7b39bfdf2337c92186da6c9bf24559377b
3,456
exs
Elixir
samples/elixir/animals.exs
MateoCerquetella/dark-plus-syntax
c5afd61a0b7a0081b6e4c070a49cde71abfd3dce
[ "MIT" ]
44
2018-06-17T03:37:04.000Z
2022-01-31T06:28:02.000Z
samples/elixir/animals.exs
MateoCerquetella/dark-plus-syntax
c5afd61a0b7a0081b6e4c070a49cde71abfd3dce
[ "MIT" ]
18
2018-04-01T10:25:20.000Z
2021-06-24T09:38:06.000Z
samples/elixir/animals.exs
MateoCerquetella/dark-plus-syntax
c5afd61a0b7a0081b6e4c070a49cde71abfd3dce
[ "MIT" ]
18
2018-07-27T17:08:54.000Z
2022-01-20T09:08:53.000Z
defmodule Animals do @moduledoc """ Red fish, Blue fish, ``` def fish do :fish end ``` """ @doc """ > Returns a list of zoo animals. ## Examples iex> Animals.create_zoo ["lion", "tiger", "gorilla", "elephant", "monkey", "giraffe"] """ def create_zoo() do ["lion", "tiger", "gorilla", "elephant", "monkey", "giraffe"] end @doc """ > Takes a list of zoo animals and returns a new randomised list with the same elements as the first. ## Examples iex> zoo = Animals.create_zoo iex> Animals.randomise(zoo) ["monkey", "tiger", "elephant", "gorilla", "giraffe", "lion"] """ def randomise(zoo) do Enum.shuffle(zoo) end @doc """ > Takes a list of zoo animals and a single animal and returns a boolean as to whether or not the list contains the given animal. ## Examples iex> zoo = Animals.create_zoo iex> Animals.contains?(zoo, "gorilla") true """ def contains?(zoo, animal) do Enum.member?(zoo, animal) end @doc """ > Takes a list of zoo animals and the number of animals that you want to see and then returns a list. ## Examples iex> zoo = Animals.create_zoo iex> Animals.see_animals(zoo, 2) ["monkey", "giraffe"] """ def see_animals(zoo, count) do # Enum.split returns a tuple so we have to pattern match on the result # to get the value we want out {_seen, to_see} = Enum.split(zoo, -count) # Enum.split(zoo, -count) = {_seen, to_see} to_see end @doc """ > Takes a list of zoo animals and a filename and saves the list to that file. ## Examples iex> zoo = Animals.create_zoo iex> Animals.save(zoo, "my_animals") :ok """ def save(zoo, filename) do # erlang is converting the zoo list to something that can be written to the # file system binary = :erlang.term_to_binary(zoo) File.write(filename, binary) end @doc """ > Takes filename and returns a list of animals if the file exists. ## Examples iex> Animals.load("my_animals") ["lion", "tiger", "gorilla", "elephant", "monkey", "giraffe"] iex> Animals.load("aglkjhdfg") "File does not exist" """ def load(filename) do # here we are running a case expression on the result of File.read(filename) # if we receive an :ok then we want to return the list # if we receive an error then we want to give the user an error-friendly message case File.read(filename) do {:ok, binary} -> :erlang.binary_to_term(binary) {:error, _reason} -> "File does not exist" end end @doc """ > Takes a number, creates a zoo, randomises it and then returns a list of animals of length selected. ## Examples iex> Animals.selection(2) ["gorilla", "giraffe"] """ def selection(number_of_animals) do # We are using the pipe operator here. It takes the value returned from # the expression and passes it down as the first argument in the expression # below. `see_animals` takes two arguments but only one needs to be specified # as the first is provided by the pipe operator Animals.create_zoo() |> Animals.randomise() |> Animals.see_animals(number_of_animals) end @doc """ > Writes a list of animals to a file. ## Examples iex> Animals.create_zoo(noice) """ def create_zoo(file_name) do Animals.create_zoo() |> Animals.save(file_name) end end
23.834483
84
0.639178
03627225cfae7940068121ae4bd1ccd83c033ff6
1,115
exs
Elixir
config/config.exs
robot-overlord/up_run
5656b9e584d9ce839372c6a6a367f2181ff8c09c
[ "MIT" ]
3
2017-05-24T21:06:48.000Z
2019-03-25T19:15:06.000Z
config/config.exs
robot-overlord/up_run
5656b9e584d9ce839372c6a6a367f2181ff8c09c
[ "MIT" ]
null
null
null
config/config.exs
robot-overlord/up_run
5656b9e584d9ce839372c6a6a367f2181ff8c09c
[ "MIT" ]
null
null
null
# This file is responsible for configuring your application # and its dependencies with the aid of the Mix.Config module. use Mix.Config # This configuration is loaded before any dependency and is restricted # to this project. If another project depends on this project, this # file won't be loaded nor affect the parent project. For this reason, # if you want to provide default values for your application for # 3rd-party users, it should be done in your "mix.exs" file. # You can configure for your application as: # # config :up_run, key: :value # # And access this configuration in your application as: # # Application.get_env(:up_run, :key) # # Or configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs"
35.967742
73
0.750673
03628a4153711a4a8482ac30e2e28f167df456cd
1,307
exs
Elixir
test/service_test.exs
icanmakeitbetter/decipher_api
3e2152f8fd87f4a92489d08e0bd4f53d18e3c0d2
[ "MIT" ]
null
null
null
test/service_test.exs
icanmakeitbetter/decipher_api
3e2152f8fd87f4a92489d08e0bd4f53d18e3c0d2
[ "MIT" ]
null
null
null
test/service_test.exs
icanmakeitbetter/decipher_api
3e2152f8fd87f4a92489d08e0bd4f53d18e3c0d2
[ "MIT" ]
null
null
null
defmodule DecipherAPITest.ServiceTest do alias DecipherAPI.Service alias DecipherAPITest.Support.FakeData use ExUnit.Case, async: true defp assert_error(response) do assert Service.parse_response(response) |> elem(0) == :error end test "that 400 error returns an :error atom" do FakeData.response_status_code(400) |> assert_error end test "that 401 error returns an :error atom" do FakeData.response_status_code(401) |> assert_error end test "that 402 error returns an :error atom" do FakeData.response_status_code(402) |> assert_error end test "that 403 error returns an :error atom" do FakeData.response_status_code(403) |> assert_error end test "that 404 error returns an :error atom" do FakeData.response_status_code(404) |> assert_error end test "that 405 error returns an :error atom" do FakeData.response_status_code(405) |> assert_error end test "that 429 error returns an :error atom" do FakeData.response_status_code(429) |> assert_error end test "that 501 error returns an :error atom" do FakeData.response_status_code(501) |> assert_error end test "that an undocumneted error returns an :error atom" do FakeData.response_status_code(502) |> assert_error end end
23.339286
64
0.7215
036297687173f24575d59c2fadc7da04313f0dc6
868
ex
Elixir
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/packet_capture_query_status_result.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/packet_capture_query_status_result.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.Network/lib/microsoft/azure/management/network/model/packet_capture_query_status_result.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule Microsoft.Azure.Management.Network.Model.PacketCaptureQueryStatusResult do @moduledoc """ Status of packet capture session. """ @derive [Poison.Encoder] defstruct [ :"name", :"id", :"captureStartTime", :"packetCaptureStatus", :"stopReason", :"packetCaptureError" ] @type t :: %__MODULE__{ :"name" => String.t, :"id" => String.t, :"captureStartTime" => DateTime.t, :"packetCaptureStatus" => String.t, :"stopReason" => String.t, :"packetCaptureError" => [String.t] } end defimpl Poison.Decoder, for: Microsoft.Azure.Management.Network.Model.PacketCaptureQueryStatusResult do def decode(value, _options) do value end end
24.111111
103
0.684332
0362b2bccc2f9f7ad01d1eda2122134dc5999c5e
2,050
ex
Elixir
test/support/test_suite.ex
pukkamustard/rdf-ex
c459d8e7fa548fdfad82643338b68decf380a296
[ "MIT" ]
null
null
null
test/support/test_suite.ex
pukkamustard/rdf-ex
c459d8e7fa548fdfad82643338b68decf380a296
[ "MIT" ]
null
null
null
test/support/test_suite.ex
pukkamustard/rdf-ex
c459d8e7fa548fdfad82643338b68decf380a296
[ "MIT" ]
null
null
null
defmodule RDF.TestSuite do defmodule NS do use RDF.Vocabulary.Namespace defvocab MF, base_iri: "http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#", terms: [], strict: false defvocab RDFT, base_iri: "http://www.w3.org/ns/rdftest#", terms: ~w[ TestTurtleEval TestTurtlePositiveSyntax TestTurtleNegativeSyntax TestTurtleNegativeEval ], strict: false end @compile {:no_warn_undefined, RDF.TestSuite.NS.MF} @compile {:no_warn_undefined, RDF.TestSuite.NS.RDFT} alias NS.MF alias RDF.{Turtle, Graph, Description, IRI} def dir(format), do: Path.join(RDF.TestData.dir, String.upcase(format) <> "-TESTS") def file(filename, format), do: format |> dir |> Path.join(filename) def manifest_path(format), do: file("manifest.ttl", format) def manifest_graph(format, opts \\ []) do format |> manifest_path |> Turtle.read_file!(opts) end def test_cases(format, test_type, opts) do format |> manifest_graph(opts) |> Graph.descriptions |> Enum.filter(fn description -> RDF.iri(test_type) in Description.get(description, RDF.type, []) end) end def test_name(test_case), do: value(test_case, MF.name) def test_title(test_case), # Unfortunately OTP < 20 doesn't support unicode characters in atoms, # so we can't put the description in the test name # do: test_name(test_case) <> ": " <> value(test_case, RDFS.comment) do: test_name(test_case) def test_input_file(test_case), do: test_case |> Description.first(MF.action) |> IRI.parse def test_output_file(test_case), do: test_case |> Description.first(MF.result) |> IRI.parse def test_input_file_path(test_case, format), do: test_input_file(test_case).path |> Path.basename |> file(format) def test_result_file_path(test_case, format), do: test_output_file(test_case).path |> Path.basename |> file(format) defp value(description, property), do: Description.first(description, property) |> to_string end
28.082192
85
0.686341
0362e211b5a689a035820dbb5a6313e5de355e6a
1,796
ex
Elixir
clients/vault/lib/google_api/vault/v1/model/add_held_accounts_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/vault/lib/google_api/vault/v1/model/add_held_accounts_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/vault/lib/google_api/vault/v1/model/add_held_accounts_request.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &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.Vault.V1.Model.AddHeldAccountsRequest do @moduledoc """ Add a list of accounts to a hold. ## Attributes * `accountIds` (*type:* `list(String.t)`, *default:* `nil`) - Account ids to identify which accounts to add. Only account_ids or only emails should be specified, but not both. * `emails` (*type:* `list(String.t)`, *default:* `nil`) - Emails to identify which accounts to add. Only emails or only account_ids should be specified, but not both. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accountIds => list(String.t()), :emails => list(String.t()) } field(:accountIds, type: :list) field(:emails, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Vault.V1.Model.AddHeldAccountsRequest do def decode(value, options) do GoogleApi.Vault.V1.Model.AddHeldAccountsRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Vault.V1.Model.AddHeldAccountsRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.538462
137
0.722717
03630fa0b93b80599bed9502db36fc6d07ff4daa
346
ex
Elixir
lib/nebulex_redis_adapter/client_cluster/keyslot.ex
bjyoungblood/nebulex_redis_adapter
8ecf19f91d1d332c39e3507831fbfabc800fcf2b
[ "MIT" ]
20
2018-09-02T15:14:44.000Z
2021-12-10T16:40:56.000Z
lib/nebulex_redis_adapter/client_cluster/keyslot.ex
bjyoungblood/nebulex_redis_adapter
8ecf19f91d1d332c39e3507831fbfabc800fcf2b
[ "MIT" ]
23
2018-10-26T19:49:11.000Z
2022-03-23T22:37:25.000Z
lib/nebulex_redis_adapter/client_cluster/keyslot.ex
bjyoungblood/nebulex_redis_adapter
8ecf19f91d1d332c39e3507831fbfabc800fcf2b
[ "MIT" ]
17
2018-11-06T00:19:03.000Z
2021-11-19T09:46:06.000Z
defmodule NebulexRedisAdapter.ClientCluster.Keyslot do @moduledoc """ Default Keyslot implementation when `:jchash` module is loaded. """ use Nebulex.Adapter.Keyslot if Code.ensure_loaded?(:jchash) do @impl true def hash_slot(key, range) do key |> :erlang.phash2() |> :jchash.compute(range) end end end
21.625
65
0.676301
036312fd8455d2f5fa27990c070132573f590b54
16,304
ex
Elixir
lib/plug/router.ex
codeadict/plug
c5e5cc04fe890054b0a03fbb9baeb2fcc49679a6
[ "Apache-2.0" ]
null
null
null
lib/plug/router.ex
codeadict/plug
c5e5cc04fe890054b0a03fbb9baeb2fcc49679a6
[ "Apache-2.0" ]
null
null
null
lib/plug/router.ex
codeadict/plug
c5e5cc04fe890054b0a03fbb9baeb2fcc49679a6
[ "Apache-2.0" ]
null
null
null
defmodule Plug.Router do @moduledoc ~S""" A DSL to define a routing algorithm that works with Plug. It provides a set of macros to generate routes. For example: defmodule AppRouter do use Plug.Router plug :match plug :dispatch get "/hello" do send_resp(conn, 200, "world") end match _ do send_resp(conn, 404, "oops") end end Each route needs to return a connection, as per the Plug spec. A catch-all `match` is recommended to be defined as in the example above, otherwise routing fails with a function clause error. The router is itself a plug, which means it can be invoked as: AppRouter.call(conn, AppRouter.init([])) Notice the router contains a plug pipeline and by default it requires two plugs: `match` and `dispatch`. `match` is responsible for finding a matching route which is then forwarded to `dispatch`. This means users can easily hook into the router mechanism and add behaviour before match, before dispatch or after both. To specify private options on `match` that can be used by plugs before `dispatch` pass an option with key `:private` containing a map. Example: get "/hello", private: %{an_option: :a_value} do send_resp(conn, 200, "world") end These options are assigned to `:private` in the call's `Plug.Conn`. ## Routes get "/hello" do send_resp(conn, 200, "world") end In the example above, a request will only match if it is a `GET` request and the route is "/hello". The supported HTTP methods are `get`, `post`, `put`, `patch`, `delete` and `options`. A route can also specify parameters which will then be available in the function body: get "/hello/:name" do send_resp(conn, 200, "hello #{name}") end The `:name` parameter will also be available in the function body as `conn.params["name"]` and `conn.path_params["name"]`. Routes allow for globbing which will match the remaining parts of a route and can be available as a parameter in the function body. Also note that a glob can't be followed by other segments: get "/hello/*_rest" do send_resp(conn, 200, "matches all routes starting with /hello") end get "/hello/*glob" do send_resp(conn, 200, "route after /hello: #{inspect glob}") end Finally, a general `match` function is also supported: match "/hello" do send_resp(conn, 200, "world") end A `match` will match any route regardless of the HTTP method. Check `match/3` for more information on how route compilation works and a list of supported options. ## Parameter Parsing Handling request data can be done through the [`Plug.Parsers`](https://hexdocs.pm/plug/Plug.Parsers.html#content) plug. It provides support for parsing URL-encoded, form-data, and JSON data as well as providing a behaviour that others parsers can adopt. Here is an example of `Plug.Parsers` can be used in a `Plug.Router` router to parse the JSON-encoded body of a POST request: defmodule AppRouter do use Plug.Router plug :match plug Plug.Parsers, parsers: [:json], pass: ["application/json"], json_decoder: Jason plug :dispatch post "/hello" do IO.inspect conn.body_params # Prints JSON POST body send_resp(conn, 200, "Success!") end end It is important that `Plug.Parsers` is placed before the `:dispatch` plug in the pipeline, otherwise the matched clause route will not receive the parsed body in its `Plug.Conn` argument when dispatched. `Plug.Parsers` can also be plugged between `:match` and `:dispatch` (like in the example above): this means that `Plug.Parsers` will run only if there is a matching route. This can be useful to perform actions such as authentication *before* parsing the body, which should only be parsed if a route matches afterwards. ## Error handling In case something goes wrong in a request, the router by default will crash, without returning any response to the client. This behaviour can be configured in two ways, by using two different modules: * `Plug.ErrorHandler` - allows the developer to customize exactly which page is sent to the client via the `handle_errors/2` function; * `Plug.Debugger` - automatically shows debugging and request information about the failure. This module is recommended to be used only in a development environment. Here is an example of how both modules could be used in an application: defmodule AppRouter do use Plug.Router if Mix.env == :dev do use Plug.Debugger end use Plug.ErrorHandler plug :match plug :dispatch get "/hello" do send_resp(conn, 200, "world") end defp handle_errors(conn, %{kind: _kind, reason: _reason, stack: _stack}) do send_resp(conn, conn.status, "Something went wrong") end end ## Routes compilation All routes are compiled to a match function that receives three arguments: the method, the request path split on `/` and the connection. Consider this example: match "/foo/bar", via: :get do send_resp(conn, 200, "hello world") end It is compiled to: defp match("GET", ["foo", "bar"], conn) do send_resp(conn, 200, "hello world") end This means guards can be given to `match`: match "/foo/bar/:baz" when size(baz) <= 3, via: :get do send_resp(conn, 200, "hello world") end After a match is found, the block given as `do/end` is stored as a function in the connection. This function is then retrieved and invoked in the `dispatch` plug. ## Options When used, the following options are accepted by `Plug.Router`: * `:log_on_halt` - accepts the level to log whenever the request is halted """ @doc false defmacro __using__(opts) do quote location: :keep do import Plug.Router @before_compile Plug.Router use Plug.Builder, unquote(opts) @doc false def match(conn, _opts) do do_match(conn, conn.method, Enum.map(conn.path_info, &URI.decode/1), conn.host) end @doc false def dispatch(%Plug.Conn{assigns: assigns} = conn, _opts) do {_path, fun} = Map.fetch!(conn.private, :plug_route) fun.(conn) end defoverridable match: 2, dispatch: 2 end end @doc false defmacro __before_compile__(env) do unless Module.defines?(env.module, {:do_match, 4}) do raise "no routes defined in module #{inspect(env.module)} using Plug.Router" end quote do import Plug.Router, only: [] end end @doc """ Returns the path of the route that the request was matched to. """ @spec match_path(Plug.Conn.t()) :: String.t() def match_path(%Plug.Conn{} = conn) do {path, _fun} = Map.fetch!(conn.private, :plug_route) path end ## Match @doc """ Main API to define routes. It accepts an expression representing the path and many options allowing the match to be configured. The route can dispatch either to a function body or a Plug module. ## Examples match "/foo/bar", via: :get do send_resp(conn, 200, "hello world") end match "/baz", to: MyPlug, init_opts: [an_option: :a_value] ## Options `match/3` and the other route macros accept the following options: * `:host` - the host which the route should match. Defaults to `nil`, meaning no host match, but can be a string like "example.com" or a string ending with ".", like "subdomain." for a subdomain match. * `:private` - assigns values to `conn.private` for use in the match * `:assigns` - assigns values to `conn.assigns` for use in the match * `:via` - matches the route against some specific HTTP method (specified as an atom, like `:get` or `:put`. * `:do` - contains the implementation to be invoked in case the route matches. * `:to` - a Plug that will be called in case the route matches. * `:init_opts` - the options for the target Plug given by `:to`. A route should specify only one of `:do` or `:to` options. """ defmacro match(path, options, contents \\ []) do compile(nil, path, options, contents) end @doc """ Dispatches to the path only if the request is a GET request. See `match/3` for more examples. """ defmacro get(path, options, contents \\ []) do compile(:get, path, options, contents) end @doc """ Dispatches to the path only if the request is a POST request. See `match/3` for more examples. """ defmacro post(path, options, contents \\ []) do compile(:post, path, options, contents) end @doc """ Dispatches to the path only if the request is a PUT request. See `match/3` for more examples. """ defmacro put(path, options, contents \\ []) do compile(:put, path, options, contents) end @doc """ Dispatches to the path only if the request is a PATCH request. See `match/3` for more examples. """ defmacro patch(path, options, contents \\ []) do compile(:patch, path, options, contents) end @doc """ Dispatches to the path only if the request is a DELETE request. See `match/3` for more examples. """ defmacro delete(path, options, contents \\ []) do compile(:delete, path, options, contents) end @doc """ Dispatches to the path only if the request is an OPTIONS request. See `match/3` for more examples. """ defmacro options(path, options, contents \\ []) do compile(:options, path, options, contents) end @doc """ Forwards requests to another Plug. The `path_info` of the forwarded connection will exclude the portion of the path specified in the call to `forward`. If the path contains any parameters, those will be available in the target Plug in `conn.params` and `conn.path_params`. ## Options `forward` accepts the following options: * `:to` - a Plug the requests will be forwarded to. * `:init_opts` - the options for the target Plug. * `:host` - a string representing the host or subdomain, exactly like in `match/3`. * `:private` - values for `conn.private`, exactly like in `match/3`. * `:assigns` - values for `conn.assigns`, exactly like in `match/3`. If `:init_opts` is undefined, then all remaining options are passed to the target plug. ## Examples forward "/users", to: UserRouter Assuming the above code, a request to `/users/sign_in` will be forwarded to the `UserRouter` plug, which will receive what it will see as a request to `/sign_in`. forward "/foo/:bar/qux", to: FooPlug Here, a request to `/foo/BAZ/qux` will be forwarded to the `FooPlug` plug, which will receive what it will see as a request to `/`, and `conn.params["bar"]` will be set to `"BAZ"`. Some other examples: forward "/foo/bar", to: :foo_bar_plug, host: "foobar." forward "/baz", to: BazPlug, init_opts: [plug_specific_option: true] """ defmacro forward(path, options) when is_binary(path) do quote bind_quoted: [path: path, options: options] do {target, options} = Keyword.pop(options, :to) {options, plug_options} = Keyword.split(options, [:host, :private, :assigns]) plug_options = Keyword.get(plug_options, :init_opts, plug_options) if is_nil(target) or !is_atom(target) do raise ArgumentError, message: "expected :to to be an alias or an atom" end {target, target_opts} = case Atom.to_string(target) do "Elixir." <> _ -> {target, target.init(plug_options)} _ -> {{__MODULE__, target}, plug_options} end @plug_forward_target target @plug_forward_opts target_opts # Delegate the matching to the match/3 macro along with the options # specified by Keyword.split/2. match path <> "/*glob", options do Plug.Router.Utils.forward( var!(conn), var!(glob), @plug_forward_target, @plug_forward_opts ) end end end ## Match Helpers @doc false def __route__(method, path, guards, options) do {method, guards} = build_methods(List.wrap(method || options[:via]), guards) {vars, match} = Plug.Router.Utils.build_path_match(path) params_match = Plug.Router.Utils.build_path_params_match(vars) private = extract_merger(options, :private) assigns = extract_merger(options, :assigns) host_match = Plug.Router.Utils.build_host_match(options[:host]) {quote(do: conn), method, match, params_match, host_match, guards, private, assigns} end @doc false def __put_route__(conn, path, fun) do Plug.Conn.put_private(conn, :plug_route, {append_match_path(conn, path), fun}) end defp append_match_path(%Plug.Conn{private: %{plug_route: {base_path, _}}}, path) do base_path <> path end defp append_match_path(%Plug.Conn{}, path) do path end # Entry point for both forward and match that is actually # responsible to compile the route. defp compile(method, expr, options, contents) do {body, options} = cond do Keyword.has_key?(contents, :do) -> {contents[:do], options} Keyword.has_key?(options, :do) -> Keyword.pop(options, :do) options[:to] -> {to, options} = Keyword.pop(options, :to) {init_opts, options} = Keyword.pop(options, :init_opts, []) body = quote do @plug_router_to.call(var!(conn), @plug_router_init) end options = quote do to = unquote(to) @plug_router_to to @plug_router_init to.init(unquote(init_opts)) unquote(options) end {body, options} true -> raise ArgumentError, message: "expected one of :to or :do to be given as option" end {path, guards} = extract_path_and_guards(expr) quote bind_quoted: [ method: method, path: path, options: options, guards: Macro.escape(guards, unquote: true), body: Macro.escape(body, unquote: true) ] do route = Plug.Router.__route__(method, path, guards, options) {conn, method, match, params, host, guards, private, assigns} = route defp do_match(unquote(conn), unquote(method), unquote(match), unquote(host)) when unquote(guards) do unquote(private) unquote(assigns) merge_params = fn %Plug.Conn.Unfetched{} -> unquote({:%{}, [], params}) fetched -> Map.merge(fetched, unquote({:%{}, [], params})) end conn = update_in(unquote(conn).params, merge_params) conn = update_in(conn.path_params, merge_params) Plug.Router.__put_route__(conn, unquote(path), fn var!(conn) -> unquote(body) end) end end end defp extract_merger(options, key) when is_list(options) do if option = Keyword.get(options, key) do quote do conn = update_in(conn.unquote(key), &Map.merge(&1, unquote(Macro.escape(option)))) end end end # Convert the verbs given with `:via` into a variable and guard set that can # be added to the dispatch clause. defp build_methods([], guards) do {quote(do: _), guards} end defp build_methods([method], guards) do {Plug.Router.Utils.normalize_method(method), guards} end defp build_methods(methods, guards) do methods = Enum.map(methods, &Plug.Router.Utils.normalize_method(&1)) var = quote do: method guards = join_guards(quote(do: unquote(var) in unquote(methods)), guards) {var, guards} end defp join_guards(fst, true), do: fst defp join_guards(fst, snd), do: quote(do: unquote(fst) and unquote(snd)) # Extract the path and guards from the path. defp extract_path_and_guards({:when, _, [path, guards]}), do: {extract_path(path), guards} defp extract_path_and_guards(path), do: {extract_path(path), true} defp extract_path({:_, _, var}) when is_atom(var), do: "/*_path" defp extract_path(path), do: path end
30.937381
92
0.652969
0363490e1f5d6d837e19eaf5ef1f1b41af58bcfb
5,639
ex
Elixir
clients/drive/lib/google_api/drive/v3/model/drive_capabilities.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/drive/lib/google_api/drive/v3/model/drive_capabilities.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
clients/drive/lib/google_api/drive/v3/model/drive_capabilities.ex
yoshi-code-bot/elixir-google-api
cdb6032f01fac5ab704803113c39f2207e9e019d
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Drive.V3.Model.DriveCapabilities do @moduledoc """ Capabilities the current user has on this shared drive. ## Attributes * `canAddChildren` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can add children to folders in this shared drive. * `canChangeCopyRequiresWriterPermissionRestriction` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can change the copyRequiresWriterPermission restriction of this shared drive. * `canChangeDomainUsersOnlyRestriction` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can change the domainUsersOnly restriction of this shared drive. * `canChangeDriveBackground` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can change the background of this shared drive. * `canChangeDriveMembersOnlyRestriction` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can change the driveMembersOnly restriction of this shared drive. * `canComment` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can comment on files in this shared drive. * `canCopy` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can copy files in this shared drive. * `canDeleteChildren` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can delete children from folders in this shared drive. * `canDeleteDrive` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can delete this shared drive. Attempting to delete the shared drive may still fail if there are untrashed items inside the shared drive. * `canDownload` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can download files in this shared drive. * `canEdit` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can edit files in this shared drive * `canListChildren` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can list the children of folders in this shared drive. * `canManageMembers` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can add members to this shared drive or remove them or change their role. * `canReadRevisions` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can read the revisions resource of files in this shared drive. * `canRename` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can rename files or folders in this shared drive. * `canRenameDrive` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can rename this shared drive. * `canResetDriveRestrictions` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can reset the shared drive restrictions to defaults. * `canShare` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can share files or folders in this shared drive. * `canTrashChildren` (*type:* `boolean()`, *default:* `nil`) - Whether the current user can trash children from folders in this shared drive. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :canAddChildren => boolean() | nil, :canChangeCopyRequiresWriterPermissionRestriction => boolean() | nil, :canChangeDomainUsersOnlyRestriction => boolean() | nil, :canChangeDriveBackground => boolean() | nil, :canChangeDriveMembersOnlyRestriction => boolean() | nil, :canComment => boolean() | nil, :canCopy => boolean() | nil, :canDeleteChildren => boolean() | nil, :canDeleteDrive => boolean() | nil, :canDownload => boolean() | nil, :canEdit => boolean() | nil, :canListChildren => boolean() | nil, :canManageMembers => boolean() | nil, :canReadRevisions => boolean() | nil, :canRename => boolean() | nil, :canRenameDrive => boolean() | nil, :canResetDriveRestrictions => boolean() | nil, :canShare => boolean() | nil, :canTrashChildren => boolean() | nil } field(:canAddChildren) field(:canChangeCopyRequiresWriterPermissionRestriction) field(:canChangeDomainUsersOnlyRestriction) field(:canChangeDriveBackground) field(:canChangeDriveMembersOnlyRestriction) field(:canComment) field(:canCopy) field(:canDeleteChildren) field(:canDeleteDrive) field(:canDownload) field(:canEdit) field(:canListChildren) field(:canManageMembers) field(:canReadRevisions) field(:canRename) field(:canRenameDrive) field(:canResetDriveRestrictions) field(:canShare) field(:canTrashChildren) end defimpl Poison.Decoder, for: GoogleApi.Drive.V3.Model.DriveCapabilities do def decode(value, options) do GoogleApi.Drive.V3.Model.DriveCapabilities.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Drive.V3.Model.DriveCapabilities do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
55.831683
226
0.700479
03634d9803c51f423324ebfd9db0e438c3d1b5f2
882
exs
Elixir
priv/repo/migrations/20180523013618_create_cms_jobs.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
priv/repo/migrations/20180523013618_create_cms_jobs.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
priv/repo/migrations/20180523013618_create_cms_jobs.exs
mydearxym/mastani_server
f24034a4a5449200165cf4a547964a0961793eab
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Repo.Migrations.CreateCmsJobs do use Ecto.Migration def change do create table(:cms_jobs) do add(:title, :string) add(:company, :string) add(:bonus, :string) add(:company_logo, :string) add(:location, :string) add(:desc, :text) add(:body, :text) add(:author_id, references(:cms_authors, on_delete: :delete_all), null: false) add(:views, :integer, default: 0) add(:link_addr, :string) add(:link_source, :string) add(:min_salary, :integer, default: 0) add(:max_salary, :integer, default: 10_000_000) add(:min_experience, :integer, default: 1) add(:max_experience, :integer, default: 3) add(:min_education, :string) add(:digest, :string) add(:length, :integer) timestamps() end create(index(:cms_jobs, [:author_id])) end end
28.451613
84
0.629252
0363b99f7369e0e4726d9252757d52d051b97d51
1,934
ex
Elixir
lib/teslamate_web/plugs/locale_plug.ex
DP19/teslamate
7218286f39d2689566dd7188264ebdb7aea62663
[ "MIT" ]
null
null
null
lib/teslamate_web/plugs/locale_plug.ex
DP19/teslamate
7218286f39d2689566dd7188264ebdb7aea62663
[ "MIT" ]
null
null
null
lib/teslamate_web/plugs/locale_plug.ex
DP19/teslamate
7218286f39d2689566dd7188264ebdb7aea62663
[ "MIT" ]
null
null
null
defmodule TeslaMateWeb.LocalePlug do import Plug.Conn @max_age 365 * 24 * 60 * 60 def init(opts) do [backend: Keyword.fetch!(opts, :backend)] end def call(conn, backend: backend) do case fetch_locale(conn, backend) do nil -> conn |> put_session(:locale, Gettext.get_locale(backend)) locale when is_binary(locale) -> Gettext.put_locale(backend, locale) conn |> put_session("locale", locale) |> put_resp_header("content-language", locale_to_language(locale)) |> put_resp_cookie("locale", locale, max_age: @max_age) end end defp fetch_locale(conn, backend) do fetch_locale_from_params(conn, backend) || fetch_locale_from_cookies(conn, backend) || fetch_locale_from_headers(conn, backend) end defp fetch_locale_from_params(conn, backend) do conn.params["locale"] |> validate_locale(backend) end defp fetch_locale_from_cookies(conn, backend) do conn.cookies["locale"] |> validate_locale(backend) end defp fetch_locale_from_headers(conn, backend) do conn |> locales_from_accept_language() |> Enum.find(&validate_locale(&1, backend)) end defp locales_from_accept_language(conn) do case get_req_header(conn, "accept-language") do [value | _] -> values = String.split(value, ",") Enum.map(values, &resolve_locale_from_accept_language/1) _ -> [] end end defp resolve_locale_from_accept_language(language) do language |> String.split(";") |> List.first() |> language_to_locale() end defp language_to_locale(language), do: String.replace(language, "-", "_", global: false) defp locale_to_language(locale), do: String.replace(locale, "_", "-", global: false) defp validate_locale(nil, _), do: nil defp validate_locale(locale, backend) do if locale in Gettext.known_locales(backend) do locale end end end
26.493151
90
0.676836
0363baa632e85a3a6dc3cde7e6f44e27a98a8008
317
ex
Elixir
apps/rtc/lib/rtc/upgrade_buffer.ex
michaeljguarino/forge
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
[ "Apache-2.0" ]
59
2021-09-16T19:29:39.000Z
2022-03-31T20:44:24.000Z
apps/rtc/lib/rtc/upgrade_buffer.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
111
2021-08-15T09:56:37.000Z
2022-03-31T23:59:32.000Z
apps/rtc/lib/rtc/upgrade_buffer.ex
svilenkov/plural
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
[ "Apache-2.0" ]
4
2021-12-13T09:43:01.000Z
2022-03-29T18:08:44.000Z
defmodule Rtc.UpgradeBuffer do defstruct [:last] def new(), do: %__MODULE__{last: nil} def append(%__MODULE__{last: nil} = buf, %{id: id}), do: %{buf | last: id} def append(%__MODULE__{last: last} = buf, %{id: id}) when id > last, do: %{buf | last: id} def append(%__MODULE__{} = buf, _), do: buf end
28.818182
76
0.615142
0363d8288f2ec4414962ad8fc2c4007e2c410cc2
788
ex
Elixir
lib/gatehouse_web/auth/current_session.ex
trutvo/gatehouse
027d4dd35703d84e15b9b2297347350b9a8f5a6b
[ "Apache-2.0" ]
1
2019-07-21T03:48:31.000Z
2019-07-21T03:48:31.000Z
lib/gatehouse_web/auth/current_session.ex
trutvo/gatehouse
027d4dd35703d84e15b9b2297347350b9a8f5a6b
[ "Apache-2.0" ]
1
2021-03-07T17:54:41.000Z
2021-03-07T17:54:41.000Z
lib/gatehouse_web/auth/current_session.ex
trutvo/gatehouse
027d4dd35703d84e15b9b2297347350b9a8f5a6b
[ "Apache-2.0" ]
2
2019-06-14T06:25:25.000Z
2019-07-21T03:48:33.000Z
defmodule Gatehouse.CurrentSession do import Plug.Conn import Guardian.Plug def init(opts), do: opts def call(conn, _opts) do principal = current_resource(conn) {:ok, token, _claims} = Gatehouse.Guardian.encode_and_sign(principal) conn |> assign(:session, %{ principal: principal, token: token }) end def token(conn) do principal = current_resource(conn) {:ok, token, _claims} = Gatehouse.Guardian.encode_and_sign(principal) token end def current_user(conn) do Gatehouse.Guardian.Plug.current_resource(conn) end def is_admin?(conn) do if logged_in?(conn) do principal = current_resource(conn) Gatehouse.AdministrationManager.is_admin(principal) end end def logged_in?(conn), do: !!current_user(conn) end
24.625
73
0.706853
0363dd3d71d14942535ae226ca132099a119e068
1,931
ex
Elixir
lib/manager.ex
easink/heos_ex
7a897d253548528e7ab2dcadfdcb6c1cbb27179f
[ "Apache-2.0" ]
null
null
null
lib/manager.ex
easink/heos_ex
7a897d253548528e7ab2dcadfdcb6c1cbb27179f
[ "Apache-2.0" ]
null
null
null
lib/manager.ex
easink/heos_ex
7a897d253548528e7ab2dcadfdcb6c1cbb27179f
[ "Apache-2.0" ]
null
null
null
defmodule Heos.Manager do @moduledoc """ Heos Manages handle connection to main device. """ # @compile if Mix.env() == :test, do: :export_all # require Logger # alias Heos.Connection # @port 1255 # def start_link(args) do # GenServer.start_link(__MODULE__, args, name: __MODULE__) # end # @impl true # def init(args) do # host = Keyword.get(args, :host) # port = Keyword.get(args, :port, @port) # # start discover task # # Task.start(Discover, :discover, []) # send(self(), :connect) # # minimize race condition, or use handle_continue # {:ok, # %{ # players: %{}, # conn: %Connection{host: host, port: port} # }} # end ############################################################################# ## ## API ## ## @spec add_player(player :: %Player{}) :: {:ok, any} ## def add_player(player) do ## GenServer.call(__MODULE__, {:add_player, player}) ## end ############################################################################# ## ## Callbacks ## # @impl true # def handle_info(:connect, state) do # # players = state.players # # updated_players = update_players(players, player) # # {:reply, updated_players, %{state | players: updated_players}} # {:noreply, state} # end ############################################################################# ## ## Private ## ## @doc """ ## update_players(players, player) ## iex> player1 = %{id: "111", name: "test name"} ## iex> players = %{"111" => %{id: "111", name: "test name"}} ## iex> update_players(players, player1) ## iex> %{"111" => %{id: "111", name: "test name"}} ## """ ## defp update_players(players, player) do ## Map.update(players, player.id, player, & &1) ## # case Map.get(players, player.id) do ## # nil -> %{players | player.id => player} ## # _ -> players ## # end ## end end
23.26506
79
0.499223
0364144cabe8162b3e3c01edd735e8e03e503b7b
1,546
ex
Elixir
clients/gke_hub/lib/google_api/gke_hub/v1/model/policy_controller_template_library_config.ex
mopp/elixir-google-api
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
[ "Apache-2.0" ]
null
null
null
clients/gke_hub/lib/google_api/gke_hub/v1/model/policy_controller_template_library_config.ex
mopp/elixir-google-api
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
[ "Apache-2.0" ]
null
null
null
clients/gke_hub/lib/google_api/gke_hub/v1/model/policy_controller_template_library_config.ex
mopp/elixir-google-api
d496227d17600bccbdf8f6be9ad1b7e7219d7ec6
[ "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.GKEHub.V1.Model.PolicyControllerTemplateLibraryConfig do @moduledoc """ The config specifying which default library templates to install. ## Attributes * `included` (*type:* `boolean()`, *default:* `nil`) - Whether the standard template library should be installed or not. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :included => boolean() | nil } field(:included) end defimpl Poison.Decoder, for: GoogleApi.GKEHub.V1.Model.PolicyControllerTemplateLibraryConfig do def decode(value, options) do GoogleApi.GKEHub.V1.Model.PolicyControllerTemplateLibraryConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.GKEHub.V1.Model.PolicyControllerTemplateLibraryConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.893617
124
0.753558
03643682134d657c2f4e98b17c2a0894f6bb411f
10,367
exs
Elixir
test/support/keys_fixture.exs
ybod/joken
4e7d34f4020ee1346f4c437e0c555589e1173132
[ "Apache-2.0" ]
null
null
null
test/support/keys_fixture.exs
ybod/joken
4e7d34f4020ee1346f4c437e0c555589e1173132
[ "Apache-2.0" ]
null
null
null
test/support/keys_fixture.exs
ybod/joken
4e7d34f4020ee1346f4c437e0c555589e1173132
[ "Apache-2.0" ]
null
null
null
defmodule Joken.Fixtures do import Joken def payload do %{ name: "John Doe" } end def token_config do payload |> token |> with_validation("name", &(&1 == "John Doe")) end # key taken from Appendix A.2.3 of JWE (Json Web Encryption) RFC # http://tools.ietf.org/html/rfc7516#appendix-A.2.3 def rsa_key2 do %{"kty" => "RSA", "n" => "sXchDaQebHnPiGvyDOAT4saGEUetSyo9MKLOoWFsueri23bOdgWp4Dy1WlUzewbgBHod5pcM9H95GQRV3JDXboIRROSBigeC5yjU1hGzHHyXss8UDprecbAYxknTcQkhslANGRUZmdTOQ5qTRsLAt6BTYuyvVRdhS8exSZEy_c4gs_7svlJJQ4H9_NxsiIoLwAEk7-Q3UXERGYw_75IDrGA84-lA_-Ct4eTlXHBIY2EaV7t7LjJaynVJCpkv4LKjTTAumiGUIuQhrNhZLuF_RJLqHpM2kgWFLU7-VTdL1VbC2tejvcI2BlMkEpk1BzBZI0KQB0GaDWFLN-aEAw3vRw", "e" => "AQAB", "d" => "VFCWOqXr8nvZNyaaJLXdnNPXZKRaWCjkU5Q2egQQpTBMwhprMzWzpR8Sxq1OPThh_J6MUD8Z35wky9b8eEO0pwNS8xlh1lOFRRBoNqDIKVOku0aZb-rynq8cxjDTLZQ6Fz7jSjR1Klop-YKaUHc9GsEofQqYruPhzSA-QgajZGPbE_0ZaVDJHfyd7UUBUKunFMScbflYAAOYJqVIVwaYR5zWEEceUjNnTNo_CVSj-VvXLO5VZfCUAVLgW4dpf1SrtZjSt34YLsRarSb127reG_DUwg9Ch-KyvjT1SkHgUWRVGcyly7uvVGRSDwsXypdrNinPA4jlhoNdizK2zF2CWQ", "p" => "9gY2w6I6S6L0juEKsbeDAwpd9WMfgqFoeA9vEyEUuk4kLwBKcoe1x4HG68ik918hdDSE9vDQSccA3xXHOAFOPJ8R9EeIAbTi1VwBYnbTp87X-xcPWlEPkrdoUKW60tgs1aNd_Nnc9LEVVPMS390zbFxt8TN_biaBgelNgbC95sM", "q" => "uKlCKvKv_ZJMVcdIs5vVSU_6cPtYI1ljWytExV_skstvRSNi9r66jdd9-yBhVfuG4shsp2j7rGnIio901RBeHo6TPKWVVykPu1iYhQXw1jIABfw-MVsN-3bQ76WLdt2SDxsHs7q7zPyUyHXmps7ycZ5c72wGkUwNOjYelmkiNS0", "dp" => "w0kZbV63cVRvVX6yk3C8cMxo2qCM4Y8nsq1lmMSYhG4EcL6FWbX5h9yuvngs4iLEFk6eALoUS4vIWEwcL4txw9LsWH_zKI-hwoReoP77cOdSL4AVcraHawlkpyd2TWjE5evgbhWtOxnZee3cXJBkAi64Ik6jZxbvk-RR3pEhnCs", "dq" => "o_8V14SezckO6CNLKs_btPdFiO9_kC1DsuUTd2LAfIIVeMZ7jn1Gus_Ff7B7IVx3p5KuBGOVF8L-qifLb6nQnLysgHDh132NDioZkhH7mI7hPG-PYE_odApKdnqECHWw0J-F0JWnUd6D2B_1TvF9mXA2Qx-iGYn8OVV1Bsmp6qU", "qi" => "eNho5yRBEBxhGBtQRww9QirZsB66TrfFReG_CcteI1aCneT0ELGhYlRlCtUkTRclIfuEPmNsNDPbLoLqqCVznFbvdB7x-Tl-m0l_eFTj2KiqwGqE9PZB9nNTwMVvH3VRRSLWACvPnSiwP8N5Usy-WRXS-V7TbpxIhvepTfE0NNo" } end def rsa_key do %{"d" => "A2gHIUmJOzRGvklIA2S8wWayCXnF8NYAhOhu7woSwjioO3HRzvd3ptegSKDpPfABJuzhy7y08ug5ZcyFbN1hJBVY8NwNzpLSUK9wmXekrbTG9MT76NAiQTxV6fYK5DXPF4Cp0qghBt-tq0kQNKx4q9QEzLb9XonmXE2a10U8EWJIs972SFGhxKzf6aq6Ri7UDK607ngQyEhVmGxr3gDJLAGQ5wOap5NYIL2ufI5FYqH-Sby_Qk7299b-w4B0fl6u8isR8OlpwMLVnD-oqOBPH-65tE82hxPV0QbSmyzmg9hlVVinJ82YRBkbcu-XG9XXOhUqJJ7kafQrYkQx6BiFKQ", "dp" => "Useg361ca8Aem1TToW8AfjOLAAEqkkR48UPMSS2Le9D4YFtAb_ud5CK2IevYl0R-4afXUzIoeiNRg4bOTAWmTwKKlmAp4B5GzlbPzAPhwQRCxzs5MiW0K-Nw30blBLWlJYDAnVEr3T3rqtgzXFLMhR5AHqM4VhWQK7QaxgaW7TE", "dq" => "yueW-DmyJULJlJckFXfkivSO_X1sjQurDwDfyFLAnrvgy2EqJ-iq0gBVySMGw2CgeSQegTmuKinF4anL0wy85BK8tgxDULVOpjls4ej8ZQnJ2RVEjdxZLjKh-2yw-v6mbn7goko98nkRCBYMdDUBHNVcaY9bA8kdBWi-K6DgW2E", "e" => "AQAB", "kty" => "RSA", "n" => "xnAUUvtW3ftv25jCB-hePVCnhROqH2PACVGoCybdtMYTl8qVABAR0d6T-BRzVhJzz0-UvBNFUQyVvKAFxtbQUZN2JgAm08UJrDQszqz5tTzodWexODdPuoCaWaWge_MZGhz5PwWd7Jc4bPAu0QzSVFpBP3CovSjv48Z2Eq0_LHXVjjX_Az-WaUh94mXFyAxFI_oCygtT-il1-japS3cXJJh0WddT3VKEBRYHmxDJd_LYE-KXQt3aTDhq0vI9sG2ivtFj0dc3w_YBdr4hlcr42ujSP3wLTPpTjituwHQhYP4j-zqu7J3FYaIxU4lkK9Y_DP27RxffFI9YDPJdwFkNJw", "p" => "5cMQg_4MrOnHI44xEs6Jyt_22DCvw3K-GY046Ls50vIf2KlRALHI65SPKfVFo5hUuHkBuWnQV46tHJU0dlmfg4svPMm_581r59yXeI8W6G4FlsSiVyhFO3P5Q5ubVs7MNaqhvaqqPqR14cVvHSqjwX5jGuGAVuLhnOhZGbtb7_U", "q" => "3RlGNrCRU-yV7TTikKJVJCIpe8vgLBkHQ61iuICd8AyHa4sXICgf2YBFgW8CAJOHKIp8g_Nl94VYpqWvN1YVDB7sFUlRpJL2yXvTKxDzUwtM5pf_D1O6lGEMQBRY-buhZHmPf5qG93LnsSqm5YOZGpZ6t6gHtYM9A6JOIgwsYys", "qi" => "kG5Stetls18_1fvQx8rxhX2Ais0Xg0gLDUjpE_9TYcb-utq79HVKOQ_2PJGz09hQ_teqnhXhgGMubqaktl6UOSJr6B4JgcAY7yU-34EuSxp8uKLix9BVsF2cpiC4ADhjLKP9c7IQ7X7zfs336_Reb8fh9G_zRdwEfmqFy7m28Lg"} end def ec_p256_key do %{"crv" => "P-256", "d" => "aJhYDBNS-5yrH97PAExzWNLlJGqJwFGZmv7iJvdG4p0", "kty" => "EC", "x" => "LksdLpZN3ijcn_TBfRK-_tgmvws0c5_V5k0bg14RLhU", "y" => "ukc-JOEAWhW664SY5Q29xHlAVEDlrQwYF3-vQ_cdi1s"} end def ec_p384_key do %{"crv" => "P-384", "d" => "-iM1VuECCos2kAvvSXSsEGL-_A9-DIc4l8Z297xfSMSxiHJMYdyVMNRxHBmoJ__0", "kty" => "EC", "x" => "HgI0kaSfi-MJLcO5eP3OvLwO6pHYxiP4q-qnzqk5-TwR8MO9FweSRMpxWb-1buPZ", "y" => "EdONZTBTmoT_c0R7_kSW6y_VaCgB_k2iNMlARR2xqFzVS5ADkyFtCEMgOS5JmZuA"} end def ec_p521_key do %{"crv" => "P-521", "d" => "ADa5GfibXsE1DcceEmsTB99lVG2cakh247L77aa1_K9OZrlYzCIhx-HVVzwJ-KDYPOIU9q2Up8D8H-EXM_6EOYzJ", "kty" => "EC", "x" => "ANrII7yaoz0vcvYKSXg404CebQYn0-GXIBvtc3hJFh-ubu8_mdIR6_B3pa3FC_CbHZnYcSxYeRaWmDjZmWqnWsgg", "y" => "AH0EUWVaoVROX3_OzzQIZLuKG5546exe5-0cQ-E7thMaH6-k5cqcyIedCuX1c9lOWcXgo2NLlj4JOwSetCpOspEM"} end def ed25519_key do %{"crv" => "Ed25519", "d" => "VoU6Pm8SOjz8ummuRPsvoJQOPI3cjsdMfUhf2AAEc7s", "kty" => "OKP", "x" => "l11mBSuP-XxI0KoSG7YEWRp4GWm7dKMOPkItJy2tlMM"} end def ed25519ph_key do %{"crv" => "Ed25519ph", "d" => "D8PU55JCryvSLK44AaCcAYj99P2MDQdxmNJhTUhFqTA", "kty" => "OKP", "x" => "JnLdiNg-GBTQjukBZUPinl56Au_kF58adtqtzrXnZTs"} end def ed448_key do %{"crv" => "Ed448", "d" => "-ox5cBHY-QLR0hRdE2gd97LkQ8oRZCT89ALXm-FqhINLdVEd_PtfHuetZoKeHALqwu-NfuADYDBL", "kty" => "OKP", "x" => "BnJNZy1_JXpGRlrNLYsz_9I5NCM-Py39P1kEOyrLRXJj38rnOJe7cJaVsOnPj2NkL_jVtG_qkjOA"} end def ed448ph_key do %{"crv" => "Ed448ph", "d" => "1AlVWjtG0cTvUSQrqgXHqYTBP07FljGGvO5SZhAgtt92NTBcuTs_HedSqvikyHhhcsE4PsTHXBx0", "kty" => "OKP", "x" => "pqCS-juwmDl_-uZhliMmaZNssMukorRdQcqC8Nu44uYyBDgpkc_i-Ir1rYjPzLOlNHEGyb0dIN-A"} end def ed25519_token do "eyJhbGciOiJFZDI1NTE5IiwidHlwIjoiSldUIn0.eyJuYW1lIjoiSm9obiBEb2UifQ.9a7z_qCuHwBMVSOG9sDzc2Ccbk49tY2GLddqViz0nuB4zG9pQS-jhhGpkYwQ9LE33742__nujzWLaSJ93tYhAw" end def ed25519ph_token do "eyJhbGciOiJFZDI1NTE5cGgiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiSm9obiBEb2UifQ.VRTZ7LyOmmPTn382rK6vP4VMYYBiQGz6i-Hpf8IB5flmcBavDmLqed8Q-h9uRlSRCTkemIBDpqKE-7zj9RlgBw" end def ed448_token do "eyJhbGciOiJFZDQ0OCIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.8eVjWUndsxWOzJMRQn5BqFJDMrcIj950zmKdSkXH2NBSCRETJD0YFA3HocSiWOgswHKZXIcYeT0AFc1JjH3LGl_oREiotTuU20b8USt3Z81VzqmMG2fvx5QlwKlZwwk4A2V5F2X-d1Ky0z1VV1PovjcA" end def ed448ph_token do "eyJhbGciOiJFZDQ0OHBoIiwidHlwIjoiSldUIn0.eyJuYW1lIjoiSm9obiBEb2UifQ.T4PiW8b_l0XqEI3NLXHFvHUifD0SpNNLpMwLbT-QuLE03FZ105Voyeh7uB87WxbSwWuZOyZfPQ6Az4N41A2oRsoTS7v9jeqizIP240vve3VB7sLs6zl9Vgb4nH6k0jvQUMKPBw7Mf6KbPN1a_rumIj0A" end def es256_token do "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.ozw2CHDqSE1t5CXXP50x52tr07Nj7HGSBWGytDj93gcHxS65TJ6Tv0RrOei-WtauDN3beXF5e7lZ8c5MPwx0-w" end def es384_token do "eyJhbGciOiJFUzM4NCIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.H1Y9Z3hhYff4kIWt6b1F-S1hNP74DRqYH9Jg41sJTitKC4wmYEAfKkQk6O7Z5nReL-4bhL2TZwl-rutG2tadVSUePeGlYR0AIiBCgJGf9dZPfYYF-toJ37wefKz0Cq78" end def es512_token do "eyJhbGciOiJFUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.ASkU80v3zU8Qa0Xdz3fJTkwRn5yEoYIUpEp4R7IH8iEEq1AJqhJv7VLSrACfiC8TdooBsa2qitA7qCOF12XgpHQzAJCvs1ryhEwmgnB3a5_aNW-5_s3REmAvmaA587Au0C-vBlRFvymrYRAITUN0Vb9z0giBAu82GcEaRuTvXblYeQXz" end def hs256_token do "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.3fazvmF342WiHp5uhY-wkWArn-YJxq1IO7Msrtfk-OQ" end def hs384_token do "eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.YOH6U5Ggk5_o5B7Dg3pacaKcPkrbFEX-30-trLV6C6wjTHJ_975PXLSEzebOSP8k" end def hs512_token do "eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.zi1zohSNwRdHftnWKE16vE3VmbGFtG27LxbYDXAodVlX7T3ATgmJJPjluwf2SPKJND2-O7alOq8NWv6EAnWWyg" end def ps256_token do "eyJhbGciOiJQUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.ku7tPc7imjD49cf2iL2KKOWd9pWSM8MYIa3lIkx8FV0uZEgukCx5yzWl20tpozLkvp_jeW_-9n2jy-Htm8Acj2Gj4zc-DhHajS01RD5Q341cQ4TS5UFZqO6BkACPXlPAPIlFCRliU2IZkSCVUsr73BaiXZ0kGpa6RZ0EWmIa0zOA6eMODDujtifoBntpxjEceFZZZux3Z7tts0-GZw4Qob952IjFdtVHqpmBGXz3v0paJ5fqCWjO7_tMqfdg7LDGXYsgkUxKyuPMjuctCtgNpKQsQZx0K4sTq7aVitQFpVUH2byyidX33xw2FvVqGFPccHCiq52sVZjUqjeKADcJhQ" end def ps384_token do "eyJhbGciOiJQUzM4NCIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.QhUlNiQ1oRFqVcgr36Tp7O3PzvZ6P0quyE9DWMFmMR2lmwW6Qh07tlS4Lre_V2zA9EsWb4Z4UPNLlugizgZyDbomW7DEZGsmMs39XP7kS0WPOPkK_JGZmRCJEvA6K038KSwWhgdgfTn_ZzwnEQutkF3OkgyMR6vbhSx60eJgh9EqVVoXQzZ9amiYszKpJYQqGgs_MNtzAS6UkurLeaL_w1CYEJGtPuepKg2mDX9DKFMrEJCeNI7Zj6f8b3_CSw7VdoMZRxAbcGMa7imRrf1b-ONCaEpO8UWGkUURtmEr4PllHpBPRn8eg7TaHK1WwM7VrPWDjiDOr7gIi3XJpik4BA" end def ps512_token do "eyJhbGciOiJQUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.sb3d4pgZD8-LxVwgTo-rS1PQmjzQhfrXyRg6FWMKWGGltKlpnuySVDPHywZCmYFEOyT4KSk17Xx7E1L6256Q4KO320zMB6Uh7HpFhCbsvSsI0Xlybypbx0oJO7H4g5MypyF4WkEmbxGA64vltZobVCL2bxg7uLfNtngwmyUA8yzeXZwNhpdfB6ajhpY1JIp5D6bv8630QANCSI2mabvsaMW2pjvAQOYPZZTzN5Z8JZVvzTxyr0yheApB6KkW58zDyGbYf7wH0aeaL16tnDpdC5ZX3ddwMDYtUDEp_5nFy1bFIKa0jFWTnoyL0AYwtsO8ag2l9L4Q7fs0OdjAD1qgrg" end def rs256_token do "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.e3hyn_oaaA2lxMlqH1UPo8STN-a_sszl8B2_s6tY9aT_YBAmfd7BXJOPsOMl7x2wXeKMQaNBVjna2tA0UiO_m3SpwiYgoTcU65D6OgkzugmLD_DhjDK1YCOKlm7So1uhbkb_QCuo4Ij5scsQqwv7hkxo4IximGBeH9LAvPhPTaGmYJMI7_tWIld2TlY6tNUQP4n0qctXsI3hjvGzdvuQW-tRnzAQCC4TYe-mJgFa033NSHeiX-sZB-SuYlWi7DJqDTiwlb_beVdqWpxxtFDA005Iw6FZTpH9Rs1LVwJU5t3RN5iWB-z4ZI-kKsGUGLNrAZ7btV6Ow2FMAdj9TXmNpQ" end def rs384_token do "eyJhbGciOiJSUzM4NCIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.XpXgnjgYH-SIQMPg8xnNXXG5RV6CQhWajHoJbf44_fT70ZbpVDSeQopNXjQg3ClFDdbTbyGeR-cCfgr1xMqdWWpbmuCn13CS9-918WD0fENkrDMb_ErFyft0XiWTLeQlW_BaLP0-sqAfY8-XsiDMbClP2hgAdyV9iA-aFJ2S5HVKI_j68WmjcvwNGPNJcfhTEpx0mMroBj1qNBRNS5p94L-QRieZgtbs5ikrn7OAo5NME6DGtrDLd1deeN84r3nGTqQODiK22o-LSjnpWHKw0iXjQymFrnnd7B_IgYiWu7X4ZPmUy_wMSYT9O8k00sfE_VRVV5Uq2qlNpCYWv9LlLA" end def rs512_token do "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiSm9obiBEb2UifQ.aw9j2S7aqohX_dGWJYrA1btgQE46Dtiy-7S9J70-k_Tm2ElepqgAj25gBDqLWkGuhKKncHWlablS2fLpmzmh-FqPbamBms6Wb9oL73H-BN4RbaCV_GGtqRFJGGHiMcKMTkbAqFps0P9xyAlr77mjplC8yXvS-gnRw3Y1z3vpgmju9G7DSyKYNUea0-_7VkT-dq0DQTiAxpaBNz4bV4Ycuduu4J24opTAGnZKR3QMdLJnoM1NRhCtpAo8twXi5He4yIFiCoz5Cjy6uWkY8mtJchC5BEES-EnbqsTBY8ScOH3tQuR9gFxunHGrfwOvT6OgX2Y5D-ZjVC6WuFGy9tPb7w" end end
66.031847
412
0.864956
036441046fed3091e2aa81f9aa59caad893cc5c4
69
ex
Elixir
lib/ymn_link_web_web/views/layout_view.ex
t-yamanashi/ymn_link_web
d883a14a10235230c6dbc935860de995004493b7
[ "Apache-2.0" ]
null
null
null
lib/ymn_link_web_web/views/layout_view.ex
t-yamanashi/ymn_link_web
d883a14a10235230c6dbc935860de995004493b7
[ "Apache-2.0" ]
null
null
null
lib/ymn_link_web_web/views/layout_view.ex
t-yamanashi/ymn_link_web
d883a14a10235230c6dbc935860de995004493b7
[ "Apache-2.0" ]
null
null
null
defmodule YmnLinkWebWeb.LayoutView do use YmnLinkWebWeb, :view end
17.25
37
0.826087
0364467852ccdb1b06def5dfe4d4fc8999e5870d
730
ex
Elixir
lib/ex_pool/state/config.ex
jcabotc/ex_pool
ec5acab0e16aa7b7d5c58abba8aa1ebcf8c5c6e4
[ "Apache-2.0" ]
6
2015-11-29T10:43:02.000Z
2016-04-07T17:32:17.000Z
lib/ex_pool/state/config.ex
jcabotc/ex_pool
ec5acab0e16aa7b7d5c58abba8aa1ebcf8c5c6e4
[ "Apache-2.0" ]
null
null
null
lib/ex_pool/state/config.ex
jcabotc/ex_pool
ec5acab0e16aa7b7d5c58abba8aa1ebcf8c5c6e4
[ "Apache-2.0" ]
null
null
null
defmodule ExPool.State.Config do @moduledoc """ The configuration of the pool. This module defines a `ExPool.State.Config` struct that keeps the configuration given by the user. ## Fields * `size` - number of workers of the pool """ @type size :: non_neg_integer @type t :: %__MODULE__{ size: size } defstruct size: nil alias ExPool.State.Config @default_size 5 @doc """ Creates a new Config from the given keyword configuration. ## Configuration options * `:size` - (Optional) size of the pool (default #{@default_size}) """ @spec new(config :: [Keyword]) :: t def new(config) do size = Keyword.get(config, :size, @default_size) %Config{size: size} end end
17.804878
70
0.657534
03646b0d8df5b5373eb861ab74da3109d4aed76c
27,048
exs
Elixir
lib/mix/test/mix/tasks/compile.elixir_test.exs
felipelincoln/elixir
6724c1d1819f2926dac561980b4beab281bbd3c2
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/compile.elixir_test.exs
felipelincoln/elixir
6724c1d1819f2926dac561980b4beab281bbd3c2
[ "Apache-2.0" ]
1
2021-07-01T17:58:37.000Z
2021-07-01T19:05:37.000Z
lib/mix/test/mix/tasks/compile.elixir_test.exs
felipelincoln/elixir
6724c1d1819f2926dac561980b4beab281bbd3c2
[ "Apache-2.0" ]
null
null
null
Code.require_file("../../test_helper.exs", __DIR__) defmodule Mix.Tasks.Compile.ElixirTest do import ExUnit.CaptureIO alias Mix.Task.Compiler.Diagnostic use MixTest.Case setup do Mix.Project.push(MixTest.Case.Sample) :ok end def trace(event, _e) do send(__MODULE__, event) :ok end @elixir_otp_version {System.version(), :erlang.system_info(:otp_release)} test "compiles a project without per environment build" do Mix.Project.pop() Mix.ProjectStack.post_config(build_per_environment: false) Mix.Project.push(MixTest.Case.Sample) in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert File.regular?("_build/shared/lib/sample/ebin/Elixir.A.beam") assert File.regular?("_build/shared/lib/sample/ebin/Elixir.B.beam") assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) end test "compiles a project with per environment build" do in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam") assert File.regular?("_build/dev/lib/sample/ebin/Elixir.B.beam") assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) end test "compiles a project with custom tracer" do Process.register(self(), __MODULE__) in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.Elixir.run(["--tracer", "Mix.Tasks.Compile.ElixirTest"]) assert_received {:alias_reference, _meta, A} assert_received {:alias_reference, _meta, B} end) after Code.put_compiler_option(:tracers, []) end test "compiles a project with a previously set custom tracer" do Process.register(self(), __MODULE__) Code.put_compiler_option(:tracers, [__MODULE__]) in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.Elixir.run([]) assert_received {:alias_reference, _meta, A} assert_received {:alias_reference, _meta, B} end) after Code.put_compiler_option(:tracers, []) end test "warns when Logger is used but not depended on" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do require Logger def info, do: Logger.info("hello") end """) message = "Logger.info/1 defined in application :logger is used by the current application but the current application does not depend on :logger" assert capture_io(:stderr, fn -> Mix.Task.run("compile", []) end) =~ message Mix.Task.clear() assert capture_io(:stderr, fn -> assert catch_exit(Mix.Task.run("compile", ["--warnings-as-errors", "--force"])) end) =~ message end) end test "does not warn when __info__ is used but not depended on" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do require Logger def info, do: Logger.__impl__("hello") end """) assert capture_io(:stderr, fn -> Mix.Task.run("compile", []) end) == "" end) end test "recompiles module-application manifest if manifest is outdated" do in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.Elixir.run(["--force"]) purge([A, B]) mtime = {{1970, 1, 1}, {0, 0, 0}} File.touch!("_build/dev/lib/sample/.mix/compile.app_tracer", mtime) Mix.Tasks.Compile.Elixir.run(["--force"]) assert File.stat!("_build/dev/lib/sample/.mix/compile.app_tracer").mtime > mtime end) end test "recompiles project if Elixir version changed" do in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.run([]) purge([A, B]) assert File.exists?("_build/dev/lib/sample") assert File.exists?("_build/dev/lib/sample/consolidated") assert Mix.Dep.ElixirSCM.read() == {:ok, @elixir_otp_version, Mix.SCM.Path} Mix.Task.clear() File.write!("_build/dev/lib/sample/consolidated/.to_be_removed", "") manifest_data = :erlang.term_to_binary({:v1, "0.0.0", nil}) File.write!("_build/dev/lib/sample/.mix/compile.elixir_scm", manifest_data) File.touch!("_build/dev/lib/sample/.mix/compile.elixir_scm", {{2010, 1, 1}, {0, 0, 0}}) Mix.Tasks.Compile.run([]) assert Mix.Dep.ElixirSCM.read() == {:ok, @elixir_otp_version, Mix.SCM.Path} assert File.stat!("_build/dev/lib/sample/.mix/compile.elixir_scm").mtime > {{2010, 1, 1}, {0, 0, 0}} refute File.exists?("_build/dev/lib/sample/consolidated/.to_be_removed") end) end test "recompiles project if scm changed" do in_fixture("no_mixfile", fn -> Mix.Tasks.Compile.run(["--verbose"]) purge([A, B]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert Mix.Dep.ElixirSCM.read() == {:ok, @elixir_otp_version, Mix.SCM.Path} Mix.Task.clear() manifest_data = :erlang.term_to_binary({1, @elixir_otp_version, :another}) File.write!("_build/dev/lib/sample/.mix/compile.elixir_scm", manifest_data) File.touch!("_build/dev/lib/sample/.mix/compile.elixir_scm", {{2010, 1, 1}, {0, 0, 0}}) Mix.Tasks.Compile.run([]) assert Mix.Dep.ElixirSCM.read() == {:ok, @elixir_otp_version, Mix.SCM.Path} assert File.stat!("_build/dev/lib/sample/.mix/compile.elixir_scm").mtime > {{2010, 1, 1}, {0, 0, 0}} end) end test "does not write BEAM files down on failures" do in_tmp("blank", fn -> File.mkdir_p!("lib") File.write!("lib/a.ex", "raise ~s(oops)") capture_io(fn -> assert {:error, [_]} = Mix.Tasks.Compile.Elixir.run([]) end) refute File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam") end) end test "removes, purges and deletes old artifacts" do in_fixture("no_mixfile", fn -> assert Mix.Tasks.Compile.Elixir.run([]) == {:ok, []} assert File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam") assert Code.ensure_loaded?(A) File.rm!("lib/a.ex") assert Mix.Tasks.Compile.Elixir.run([]) == {:ok, []} refute File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam") refute Code.ensure_loaded?(A) refute String.contains?(File.read!("_build/dev/lib/sample/.mix/compile.elixir"), "Elixir.A") end) end test "compiles mtime changed files if content changed but not length" do in_fixture("no_mixfile", fn -> assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} Mix.shell().flush purge([A, B]) same_length_content = "lib/a.ex" |> File.read!() |> String.replace("A", "Z") File.write!("lib/a.ex", same_length_content) future = {{2038, 1, 1}, {0, 0, 0}} File.touch!("lib/a.ex", future) Mix.Tasks.Compile.Elixir.run(["--verbose"]) message = "warning: mtime (modified time) for \"lib/a.ex\" was set to the future, resetting to now" assert_received {:mix_shell, :error, [^message]} message = "warning: mtime (modified time) for \"lib/b.ex\" was set to the future, resetting to now" refute_received {:mix_shell, :error, [^message]} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} File.touch!("_build/dev/lib/sample/.mix/compile.elixir", future) assert Mix.Tasks.Compile.Elixir.run([]) == {:noop, []} end) end test "does not recompile mtime changed but identical files" do in_fixture("no_mixfile", fn -> assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} Mix.shell().flush purge([A, B]) future = {{2038, 1, 1}, {0, 0, 0}} File.touch!("lib/a.ex", future) Mix.Tasks.Compile.Elixir.run(["--verbose"]) message = "warning: mtime (modified time) for \"lib/a.ex\" was set to the future, resetting to now" assert_received {:mix_shell, :error, [^message]} message = "warning: mtime (modified time) for \"lib/b.ex\" was set to the future, resetting to now" refute_received {:mix_shell, :error, [^message]} refute_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} File.touch!("_build/dev/lib/sample/.mix/compile.elixir", future) assert Mix.Tasks.Compile.Elixir.run([]) == {:noop, []} end) end test "compiles size changed files" do in_fixture("no_mixfile", fn -> past = {{2010, 1, 1}, {0, 0, 0}} File.touch!("lib/a.ex", past) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} Mix.shell().flush purge([A, B]) File.write!("lib/a.ex", File.read!("lib/a.ex") <> "\n") File.touch!("lib/a.ex", past) Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) end test "compiles dependent changed modules" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", "defmodule A, do: B.module_info()") assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} Mix.shell().flush purge([A, B]) force_recompilation("lib/b.ex") Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) end test "compiles dependent changed modules without beam files" do in_fixture("no_mixfile", fn -> File.write!("lib/b.ex", """ defmodule B do def a, do: A.__info__(:module) end """) Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} assert File.regular?("_build/dev/lib/sample/ebin/Elixir.A.beam") assert File.regular?("_build/dev/lib/sample/ebin/Elixir.B.beam") Code.put_compiler_option(:ignore_module_conflict, true) Code.compile_file("lib/b.ex") force_recompilation("lib/a.ex") Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} end) after Code.put_compiler_option(:ignore_module_conflict, false) end test "compiles dependent changed modules even on removal" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", "defmodule A, do: B.module_info()") assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} Mix.shell().flush purge([A, B]) File.rm("lib/b.ex") File.write!("lib/a.ex", "defmodule A, do: nil") Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) end test "compiles dependent changed files" do in_fixture("no_mixfile", fn -> tmp = tmp_path("c.eex") File.touch!("lib/a.eex") File.write!("lib/a.ex", """ defmodule A do @external_resource "lib/a.eex" @external_resource #{inspect(tmp)} def a, do: :ok end """) # Compiles with missing external resources assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:noop, []} Mix.shell().flush purge([A, B]) # Update local existing resource File.touch!("lib/a.eex", {{2038, 1, 1}, {0, 0, 0}}) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} # Does not update on old existing resource File.touch!("lib/a.eex", {{2000, 1, 1}, {0, 0, 0}}) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:noop, []} Mix.shell().flush purge([A, B]) # Update external existing resource File.touch!(tmp, {{2038, 1, 1}, {0, 0, 0}}) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) after File.rm(tmp_path("c.eex")) end test "recompiles modules with exports tracking" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do defstruct [:foo] end """) File.write!("lib/b.ex", """ defmodule B do def fun do %A{foo: 1} end end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) File.write!("lib/a.ex", """ defmodule A do # Some comments defstruct [:foo] end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) File.write!("lib/a.ex", """ defmodule A do defstruct [:foo, :bar] end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) File.write!("lib/a.ex", """ defmodule A do @enforce_keys [:foo] defstruct [:foo, :bar] end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) File.write!("lib/a.ex", """ defmodule A do @enforce_keys [:foo] defstruct [:foo, :bar] def some_fun, do: :ok end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) # Remove all code, we should now get a compilation error File.write!("lib/a.ex", """ """) assert capture_io(fn -> {:error, _} = Mix.Tasks.Compile.Elixir.run(["--verbose"]) end) =~ "A.__struct__/1 is undefined, cannot expand struct A" # At the code back and it should work again File.write!("lib/a.ex", """ defmodule A do defstruct [:foo, :bar] end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) # Removing the file should have the same effect as removing all code File.rm!("lib/a.ex") assert capture_io(fn -> {:error, _} = Mix.Tasks.Compile.Elixir.run(["--verbose"]) end) =~ "A.__struct__/1 is undefined, cannot expand struct A" end) end test "recompiles modules with async tracking" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ Kernel.ParallelCompiler.async(fn -> defmodule A do def fun, do: :ok end end) |> Task.await() """) File.write!("lib/b.ex", """ defmodule B do A.fun() end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) force_recompilation("lib/a.ex") assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} purge([A, B]) end) end test "recompiles modules with multiple sources" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def one, do: 1 end defmodule B do def two, do: 2 end """) File.write!("lib/b.ex", """ B.two() defmodule A do end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose", "--ignore-module-conflict"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} refute function_exported?(A, :one, 0) Mix.shell().flush purge([A]) File.rm("lib/b.ex") Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} assert function_exported?(A, :one, 0) end) end test "recompiles with --force" do in_fixture("no_mixfile", fn -> assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} purge([A, B]) # Now we have a noop assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:noop, []} # --force assert Mix.Tasks.Compile.Elixir.run(["--force", "--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} end) end test "compiles files with autoload disabled" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do @compile {:autoload, false} end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} purge([A, B]) end) end test "does not recompile files that are empty or has no code" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", "") File.write!("lib/b.ex", "# Just a comment") File.write!("lib/c.ex", "\n\n") assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/c.ex"]} assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:noop, []} refute_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/c.ex"]} end) end test "recompiles modules with __mix_recompile__ check" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def __mix_recompile__?(), do: true end """) File.write!("lib/b.ex", """ defmodule B do def __mix_recompile__?(), do: false end """) File.write!("lib/c.ex", """ defmodule C do @compile {:autoload, false} def __mix_recompile__?(), do: true end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiling 3 files (.ex)"]} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/c.ex"]} assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiling 1 file (.ex)"]} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} File.rm!("lib/a.ex") assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} refute_received _ end) end test "does not treat remote typespecs as compile time dependencies" do in_fixture("no_mixfile", fn -> File.write!("lib/b.ex", """ defmodule B do @type t :: A.t end """) assert Mix.Tasks.Compile.Elixir.run(["--verbose"]) == {:ok, []} assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} Mix.shell().flush purge([A, B]) force_recompilation("lib/a.ex") Mix.Tasks.Compile.Elixir.run(["--verbose"]) assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} end) end test "prints warnings from non-stale files with --all-warnings" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def my_fn(unused), do: :ok end """) # First compilation should print unused variable warning assert capture_io(:stderr, fn -> Mix.Tasks.Compile.Elixir.run([]) == :ok end) =~ "variable \"unused\" is unused" assert capture_io(:stderr, fn -> Mix.Tasks.Compile.Elixir.run(["--all-warnings"]) end) =~ "variable \"unused\" is unused" # Should not print warning once fixed File.write!("lib/a.ex", """ defmodule A do def my_fn(_unused), do: :ok end """) assert capture_io(:stderr, fn -> Mix.Tasks.Compile.Elixir.run(["--all-warnings"]) end) == "" end) end test "returns warning diagnostics" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def my_fn(unused), do: :ok end """) diagnostic = %Diagnostic{ file: Path.absname("lib/a.ex"), severity: :warning, position: 2, compiler_name: "Elixir", message: "variable \"unused\" is unused (if the variable is not meant to be used, prefix it with an underscore)" } capture_io(:stderr, fn -> assert {:ok, [^diagnostic]} = Mix.Tasks.Compile.Elixir.run([]) end) # Recompiling should return :noop status because nothing is stale, # but also include previous warning diagnostics assert {:noop, [^diagnostic]} = Mix.Tasks.Compile.Elixir.run([]) end) end test "returns warning diagnostics for external files" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ IO.warn "warning", [{nil, nil, 0, file: 'lib/foo.txt', line: 3}] """) diagnostic = %Diagnostic{ file: Path.absname("lib/foo.txt"), severity: :warning, position: 3, compiler_name: "Elixir", message: "warning" } capture_io(:stderr, fn -> assert {:ok, [^diagnostic]} = Mix.Tasks.Compile.Elixir.run([]) end) end) end test "returns warning diagnostics for unused imports" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do import B end """) File.write!("lib/b.ex", """ defmodule B do def foo, do: :ok end """) diagnostic = %Diagnostic{ file: Path.absname("lib/a.ex"), severity: :warning, position: 2, compiler_name: "Elixir", message: "unused import B" } capture_io(:stderr, fn -> assert {:ok, [^diagnostic]} = Mix.Tasks.Compile.Elixir.run([]) end) end) end test "returns error diagnostics", context do in_tmp(context.test, fn -> File.mkdir_p!("lib") File.write!("lib/a.ex", """ defmodule A do def my_fn(), do: $$$ end """) file = Path.absname("lib/a.ex") capture_io(fn -> assert {:error, [diagnostic]} = Mix.Tasks.Compile.Elixir.run([]) assert %Diagnostic{ file: ^file, severity: :error, position: 2, message: "** (SyntaxError) lib/a.ex:2:" <> _, compiler_name: "Elixir" } = diagnostic end) end) end test "returns error diagnostics when deadlocked" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do B.__info__(:module) end """) File.write!("lib/b.ex", """ defmodule B do A.__info__(:module) end """) capture_io(fn -> assert {:error, errors} = Mix.Tasks.Compile.Elixir.run([]) errors = Enum.sort_by(errors, &Map.get(&1, :file)) file_a = Path.absname("lib/a.ex") file_b = Path.absname("lib/b.ex") assert [ %Diagnostic{file: ^file_a, message: "deadlocked waiting on module B"}, %Diagnostic{file: ^file_b, message: "deadlocked waiting on module A"} ] = errors end) end) end test "verify runtime dependent modules that haven't been compiled" do Mix.Project.pop() Mix.Project.push(MixTest.Case.Sample) in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def foo(), do: :ok end """) File.write!("lib/b.ex", """ defmodule B do def foo(), do: A.foo() end """) File.write!("lib/c.ex", """ defmodule C do def foo(), do: B.foo() def bar(), do: B.bar() end """) output = capture_io(:stderr, fn -> Mix.Tasks.Compile.Elixir.run(["--verbose"]) end) refute output =~ "A.foo/0 is undefined or private" assert output =~ "B.bar/0 is undefined or private" assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/b.ex"]} assert_received {:mix_shell, :info, ["Compiled lib/c.ex"]} File.write!("lib/a.ex", """ defmodule A do end """) output = capture_io(:stderr, fn -> Mix.Tasks.Compile.Elixir.run(["--verbose"]) end) # Check B due to direct dependency on A # Check C due to transient dependency on A assert output =~ "A.foo/0 is undefined or private" assert output =~ "B.bar/0 is undefined or private" # Ensure only A was recompiled assert_received {:mix_shell, :info, ["Compiled lib/a.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/b.ex"]} refute_received {:mix_shell, :info, ["Compiled lib/c.ex"]} end) end end
30.947368
144
0.584516
03647c1e60f2e2dae6a213e871bfeb443828fef7
2,062
ex
Elixir
clients/display_video/lib/google_api/display_video/v1/model/advertiser_ad_server_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/display_video/lib/google_api/display_video/v1/model/advertiser_ad_server_config.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/display_video/lib/google_api/display_video/v1/model/advertiser_ad_server_config.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.DisplayVideo.V1.Model.AdvertiserAdServerConfig do @moduledoc """ Ad server related settings of an advertiser. ## Attributes * `cmHybridConfig` (*type:* `GoogleApi.DisplayVideo.V1.Model.CmHybridConfig.t`, *default:* `nil`) - The configuration for advertisers that use both Campaign Manager 360 (CM360) and third-party ad servers. * `thirdPartyOnlyConfig` (*type:* `GoogleApi.DisplayVideo.V1.Model.ThirdPartyOnlyConfig.t`, *default:* `nil`) - The configuration for advertisers that use third-party ad servers only. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :cmHybridConfig => GoogleApi.DisplayVideo.V1.Model.CmHybridConfig.t() | nil, :thirdPartyOnlyConfig => GoogleApi.DisplayVideo.V1.Model.ThirdPartyOnlyConfig.t() | nil } field(:cmHybridConfig, as: GoogleApi.DisplayVideo.V1.Model.CmHybridConfig) field(:thirdPartyOnlyConfig, as: GoogleApi.DisplayVideo.V1.Model.ThirdPartyOnlyConfig) end defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.AdvertiserAdServerConfig do def decode(value, options) do GoogleApi.DisplayVideo.V1.Model.AdvertiserAdServerConfig.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.AdvertiserAdServerConfig do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.24
208
0.762852
036483788ef40b0342e102b82c7b2261ba768b43
920
ex
Elixir
lib/elasticsearch.ex
kentork/kensakukun
188e1d931fa525ccf0ace9f13fccbefc19406eea
[ "MIT" ]
null
null
null
lib/elasticsearch.ex
kentork/kensakukun
188e1d931fa525ccf0ace9f13fccbefc19406eea
[ "MIT" ]
null
null
null
lib/elasticsearch.ex
kentork/kensakukun
188e1d931fa525ccf0ace9f13fccbefc19406eea
[ "MIT" ]
null
null
null
defmodule Kensakukun.Elasticsearch do def get_indices() do host = Application.fetch_env!(:kensakukun, :es_host) port = Application.fetch_env!(:kensakukun, :es_port) HTTPotion.get("http://" <> host <> ":" <> port <> "/_cat/indices?format=json") |> Map.get(:body) |> Poison.decode!() end def search_path(index, query) do host = Application.fetch_env!(:kensakukun, :es_host) port = Application.fetch_env!(:kensakukun, :es_port) HTTPotion.get( "http://" <> host <> ":" <> port <> "/" <> index <> "/pathes/_search", headers: ["Content-Type": "application/json"], body: "{\"from\":0,\"size\":1000,\"query\": {\"term\": {\"path\": \"" <> query <> "\"}}}" ) |> Map.get(:body) |> Poison.decode!() |> entities |> Enum.map(& &1["_source"]) end defp entities(%{"hits" => %{"hits" => result}}), do: result # defp ok({:ok, result}), do: result end
31.724138
95
0.572826
036489845a47001efa2c437599b9b71aef7ee3e9
161
ex
Elixir
examples/Authentication_lookup.ex
ipfinder-io/ip-finder-elixir
281402fc91f90291a46e0fc4e93620a4390e5c17
[ "Apache-2.0" ]
null
null
null
examples/Authentication_lookup.ex
ipfinder-io/ip-finder-elixir
281402fc91f90291a46e0fc4e93620a4390e5c17
[ "Apache-2.0" ]
1
2019-08-29T23:23:08.000Z
2019-08-29T23:23:08.000Z
examples/Authentication_lookup.ex
ipfinder-io/ip-finder-elixir
281402fc91f90291a46e0fc4e93620a4390e5c17
[ "Apache-2.0" ]
2
2019-08-29T23:19:07.000Z
2022-02-02T03:00:16.000Z
defmodule AuthenticationLookup do use Ipfinder def auth do conf = Ipfinder.new("YOUR_TOKEN_GOES_HERE") {:ok, auth} = Ipfinder.authentication(conf) end end
23
45
0.770186
0364df4cc6bfea5aa80bd8c274f45463333b51af
884
exs
Elixir
test/conditioners/function_call_test.exs
bcardarella/elixir-fixtures
2c49e0af3713bd912dc7bb639324da423d155299
[ "MIT" ]
139
2016-02-07T12:28:18.000Z
2022-02-15T11:39:58.000Z
test/conditioners/function_call_test.exs
bcardarella/elixir-fixtures
2c49e0af3713bd912dc7bb639324da423d155299
[ "MIT" ]
17
2016-05-16T18:59:26.000Z
2020-09-11T16:53:53.000Z
test/conditioners/function_call_test.exs
bcardarella/elixir-fixtures
2c49e0af3713bd912dc7bb639324da423d155299
[ "MIT" ]
10
2016-02-23T09:25:09.000Z
2020-02-29T14:21:21.000Z
defmodule EctoFixtures.Conditioners.FunctionCallTest do use ExUnit.Case test "can evaluate functions to generate values" do source = "test/fixtures/function_call.exs" data = EctoFixtures.read(source) |> EctoFixtures.parse |> EctoFixtures.condition source = String.to_atom(source) assert data[source][:owners][:rows][:brian][:data][:password_hash] == :crypto.hash(:sha, "password") end test "can evaluate Elixir types to generate values" do source = "test/fixtures/types.exs" data = EctoFixtures.read(source) |> EctoFixtures.parse |> EctoFixtures.condition source = String.to_atom(source) assert data[source][:owners][:rows][:brian][:data][:map] == %{foo: :bar} assert data[source][:owners][:rows][:brian][:data][:list] == [1, 2, 3] assert data[source][:owners][:rows][:brian][:data][:tuple] == {1, 2, 3} end end
31.571429
104
0.673077
0364e18c64e99870c11e867df78663713b6bf177
79
ex
Elixir
lib/dapp_demo.ex
arpnetwork/dapp_demo
ff87809625ae6053378ddffd63e27c6225d93370
[ "Apache-2.0" ]
null
null
null
lib/dapp_demo.ex
arpnetwork/dapp_demo
ff87809625ae6053378ddffd63e27c6225d93370
[ "Apache-2.0" ]
null
null
null
lib/dapp_demo.ex
arpnetwork/dapp_demo
ff87809625ae6053378ddffd63e27c6225d93370
[ "Apache-2.0" ]
null
null
null
defmodule DappDemo do @moduledoc """ Documentation for DappDemo. """ end
13.166667
29
0.696203
0364f3a72dcc04ddaf12c1788a883652a6ef402e
681
ex
Elixir
lib/workbench_web/auth_error_handler.ex
GunnarPDX/workbench
11bcd762fd1b3bbfa5fefa1aac55c89cd7b2a7c7
[ "MIT" ]
null
null
null
lib/workbench_web/auth_error_handler.ex
GunnarPDX/workbench
11bcd762fd1b3bbfa5fefa1aac55c89cd7b2a7c7
[ "MIT" ]
null
null
null
lib/workbench_web/auth_error_handler.ex
GunnarPDX/workbench
11bcd762fd1b3bbfa5fefa1aac55c89cd7b2a7c7
[ "MIT" ]
null
null
null
defmodule WorkbenchWeb.AuthErrorHandler do import Plug.Conn @behaviour Guardian.Plug.ErrorHandler @impl Guardian.Plug.ErrorHandler def auth_error(conn, {:no_resource_found, :resource_not_found}, _opts) do conn |> Phoenix.Controller.redirect(to: "/auth/google") end def auth_error(conn, {:already_authenticated, _reason}, _opts) do conn |> Phoenix.Controller.redirect(to: "/balances/all") end def auth_error(conn, {:unauthenticated, _reason}, _opts) do conn |> Phoenix.Controller.redirect(to: "/") end def auth_error(conn, {type, _reason}, _opts) do body = Jason.encode!(%{message: to_string(type)}) send_resp(conn, 401, body) end end
28.375
75
0.71953
0364fd5709182604a8ed51bad03991550addef36
248
exs
Elixir
priv/repo/migrations/20190809095307_create_todos.exs
westrik/todo-ex
6ab0c61b91d3e76239e77e988e51aa0b06f30408
[ "MIT" ]
1
2020-11-12T08:26:51.000Z
2020-11-12T08:26:51.000Z
priv/repo/migrations/20190809095307_create_todos.exs
westrik/todo-ex
6ab0c61b91d3e76239e77e988e51aa0b06f30408
[ "MIT" ]
null
null
null
priv/repo/migrations/20190809095307_create_todos.exs
westrik/todo-ex
6ab0c61b91d3e76239e77e988e51aa0b06f30408
[ "MIT" ]
null
null
null
defmodule TodoApi.Repo.Migrations.CreateTodos do use Ecto.Migration def change do create table(:todos) do add :description, :string add :is_complete, :boolean, default: false, null: false timestamps() end end end
17.714286
61
0.681452
03653042ed479783a2b8047713dceac061082db3
2,236
ex
Elixir
clients/content/lib/google_api/content/v2/model/transit_table.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/transit_table.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/transit_table.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Content.V2.Model.TransitTable do @moduledoc """ ## Attributes - postalCodeGroupNames ([String.t]): A list of postal group names. The last value can be \&quot;all other locations\&quot;. Example: [\&quot;zone 1\&quot;, \&quot;zone 2\&quot;, \&quot;all other locations\&quot;]. The referred postal code groups must match the delivery country of the service. Defaults to: `null`. - rows ([TransitTableTransitTimeRow]): Defaults to: `null`. - transitTimeLabels ([String.t]): A list of transit time labels. The last value can be \&quot;all other labels\&quot;. Example: [\&quot;food\&quot;, \&quot;electronics\&quot;, \&quot;all other labels\&quot;]. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :postalCodeGroupNames => list(any()), :rows => list(GoogleApi.Content.V2.Model.TransitTableTransitTimeRow.t()), :transitTimeLabels => list(any()) } field(:postalCodeGroupNames, type: :list) field(:rows, as: GoogleApi.Content.V2.Model.TransitTableTransitTimeRow, type: :list) field(:transitTimeLabels, type: :list) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.TransitTable do def decode(value, options) do GoogleApi.Content.V2.Model.TransitTable.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.TransitTable do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
41.407407
316
0.729875
03653d01a444424d43c17856775dbead5765a489
13,632
exs
Elixir
test/ex_doc/autolink_test.exs
vgsantoniazzi/ex_doc
0f6f24b300d5486e6aaef3c13fbfab2f74cd4c5c
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
test/ex_doc/autolink_test.exs
vgsantoniazzi/ex_doc
0f6f24b300d5486e6aaef3c13fbfab2f74cd4c5c
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
test/ex_doc/autolink_test.exs
vgsantoniazzi/ex_doc
0f6f24b300d5486e6aaef3c13fbfab2f74cd4c5c
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
defmodule ExDoc.AutolinkTest do use ExUnit.Case, async: true doctest ExDoc.Autolink import ExUnit.CaptureIO defp sigil_m(text, []) do [{:p, _, [ast]}] = ExDoc.Markdown.to_ast(text, []) ast end setup do ExDoc.Refs.clear() :ok end describe "doc/3" do test "elixir stdlib module" do assert autolink("String") == ~m"[`String`](https://hexdocs.pm/elixir/String.html)" assert autolink("Elixir.String") == ~m"[`Elixir.String`](https://hexdocs.pm/elixir/String.html)" end test "other elixir core module" do assert autolink("IEx.Helpers") == ~m"[`IEx.Helpers`](https://hexdocs.pm/iex/IEx.Helpers.html)" end test "private module" do assert_unchanged("String.Unicode") end test "erlang module" do assert_unchanged(":array") end test "unknown module" do assert_unchanged("Unknown") assert_unchanged(":unknown") end test "project-local module" do ExDoc.Refs.insert([ {{:module, Foo}, true} ]) assert autolink("Foo") == ~m"[`Foo`](Foo.html)" assert autolink("String", app: :elixir) == ~m"[`String`](String.html)" assert autolink("Foo", current_module: Foo) == ~m"[`Foo`](#content)" end test "remote function" do ExDoc.Refs.insert([ {{:module, Foo}, true}, {{:function, Foo, :foo, 1}, true}, {{:function, Foo, :., 2}, true}, {{:function, Foo, :.., 2}, true} ]) assert autolink("Foo.foo/1") == ~m"[`Foo.foo/1`](Foo.html#foo/1)" assert autolink("Foo../2") == ~m"[`Foo../2`](Foo.html#./2)" assert autolink("Foo.../2") == ~m"[`Foo.../2`](Foo.html#../2)" assert_unchanged("Bad.bar/1") end test "elixir stdlib function" do assert autolink("String.upcase/2") == ~m"[`String.upcase/2`](https://hexdocs.pm/elixir/String.html#upcase/2)" end test "elixir function with default argument" do assert autolink("Enum.join/1") == ~m"[`Enum.join/1`](https://hexdocs.pm/elixir/Enum.html#join/1)" end test "erlang stdlib function" do assert autolink(":lists.all/2") == ~m"[`:lists.all/2`](http://www.erlang.org/doc/man/lists.html#all-2)" end test "local function" do ExDoc.Refs.insert([ {{:module, Foo}, true}, {{:function, Foo, :foo, 1}, true}, {{:function, Foo, :., 2}, true}, {{:function, Foo, :.., 2}, true} ]) assert autolink("foo/1", current_module: Foo) == ~m"[`foo/1`](#foo/1)" assert autolink("./2", current_module: Foo) == ~m"[`./2`](#./2)" assert autolink("../2", current_module: Foo) == ~m"[`../2`](#../2)" assert_unchanged("bar/1", current_module: Foo) end test "sibling function" do assert autolink("Earmark.as_ast/2", siblings: [:earmark]) == ~m"[`Earmark.as_ast/2`](Earmark.html#as_ast/2)" end test "auto-imported function" do assert autolink("+/2") == ~m"[`+/2`](https://hexdocs.pm/elixir/Kernel.html#+/2)" assert autolink("for/1") == ~m"[`for/1`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#for/1)" assert autolink("for/1", app: :elixir) == ~m"[`for/1`](Kernel.SpecialForms.html#for/1)" end test "elixir callback" do assert autolink("c:GenServer.handle_call/3") == ~m"[`GenServer.handle_call/3`](https://hexdocs.pm/elixir/GenServer.html#c:handle_call/3)" end test "erlang callback" do assert autolink("c::gen_server.handle_call/3") == ~m"[`:gen_server.handle_call/3`](http://www.erlang.org/doc/man/gen_server.html#Module:handle_call-3)" end test "elixir type" do assert autolink("t:Calendar.date/0") == ~m"[`Calendar.date/0`](https://hexdocs.pm/elixir/Calendar.html#t:date/0)" end test "elixir basic & built-in types" do assert autolink("t:atom/0") == ~m"[`atom/0`](https://hexdocs.pm/elixir/typespecs.html#basic-types)" assert autolink("t:keyword/0") == ~m"[`keyword/0`](https://hexdocs.pm/elixir/typespecs.html#built-in-types)" assert autolink("t:keyword/0", app: :elixir) == ~m"[`keyword/0`](typespecs.html#built-in-types)" end test "erlang type" do assert autolink("t::array.array/0") == ~m"[`:array.array/0`](http://www.erlang.org/doc/man/array.html#type-array)" end test "special forms" do assert autolink("__block__/1", current_module: Kernel.SpecialForms) == ~m"[`__block__/1`](#__block__/1)" assert autolink("__aliases__/1", current_module: Kernel.SpecialForms) == ~m"[`__aliases__/1`](#__aliases__/1)" end test "escaping" do assert autolink("Kernel.SpecialForms.%{}/1") == ~m"[`Kernel.SpecialForms.%{}/1`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%25%7B%7D/1)" assert autolink("Kernel.SpecialForms.{}/1") == ~m"[`Kernel.SpecialForms.{}/1`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%7B%7D/1)" assert autolink("Kernel.SpecialForms.<<>>/1") == ~m"[`Kernel.SpecialForms.<<>>/1`](https://hexdocs.pm/elixir/Kernel.SpecialForms.html#%3C%3C%3E%3E/1)" end test "custom link" do assert autolink(~m"[custom text](`String`)") == ~m"[custom text](https://hexdocs.pm/elixir/String.html)" assert autolink(~m"[custom text](`:lists`)") == ~m"[custom text](http://www.erlang.org/doc/man/lists.html)" assert autolink(~m"[custom text](`:lists.all/2`)") == ~m"[custom text](http://www.erlang.org/doc/man/lists.html#all-2)" # TODO: with custom links and backticks there are no false positives (you # always mean to link) so we should always warn on mismatches? # Though backticks are markdown specific, is that ok? # assert_warn(fn -> assert_unchanged(~m"[custom text](`Unknown`)") end test "mix task" do assert autolink("mix compile.elixir") == ~m"[`mix compile.elixir`](https://hexdocs.pm/mix/Mix.Tasks.Compile.Elixir.html)" assert autolink("mix help compile.elixir") == ~m"[`mix help compile.elixir`](https://hexdocs.pm/mix/Mix.Tasks.Compile.Elixir.html)" assert autolink("mix help help") == ~m"[`mix help help`](https://hexdocs.pm/mix/Mix.Tasks.Help.html)" assert autolink("mix compile.elixir", app: :mix) == ~m"[`mix compile.elixir`](Mix.Tasks.Compile.Elixir.html)" assert_unchanged("mix compile.elixir --verbose") assert_unchanged("mix unknown.task") end test "3rd party links" do assert autolink("Earmark.as_ast/2") == ~m"[`Earmark.as_ast/2`](https://hexdocs.pm/earmark/Earmark.html#as_ast/2)" assert_unchanged(":test_module.foo/0") end test "extras" do opts = [extras: ["Foo Bar.md"]] assert autolink(~m"[Foo](Foo Bar.md)", opts) == ~m"[Foo](foo-bar.html)" assert autolink(~m"[Foo](Foo Bar.md)", [ext: ".xhtml"] ++ opts) == ~m"[Foo](foo-bar.xhtml)" assert autolink(~m"[Foo](Foo Bar.md#baz)", opts) == ~m"[Foo](foo-bar.html#baz)" assert autolink(~m"[Foo](../guide/Foo Bar.md)", opts) == ~m"[Foo](foo-bar.html)" assert_unchanged(~m"[Foo](http://example.com/foo.md)", opts) assert_unchanged(~m"[Foo](#baz)", opts) end test "other link" do assert_unchanged(~m"[`String`](foo.html)") assert_unchanged(~m"[custom text](foo.html)") end test "other" do assert_unchanged("String.upcase() / 2") assert_unchanged("String.upcase()/2 ") assert_unchanged(" String.upcase()/2") assert_unchanged(":\"atom\"") assert_unchanged("1 + 2") assert_unchanged({:p, [], ["hello"]}) end end describe "typespec/3" do test "operators" do assert typespec(quote(do: +foo() :: foo())) == ~s[+foo() :: foo()] assert typespec(quote(do: foo() + foo() :: foo())) == ~s[foo() + foo() :: foo()] assert typespec(quote(do: -0 :: 0)) == ~s[-0 :: 0] end test "locals" do ExDoc.Refs.insert([ {{:module, MyModule}, true}, {{:type, MyModule, :foo, 1}, true}, {{:type, MyModule, :foo, 2}, true}, {{:type, MyModule, :foo!, 1}, true} ]) assert typespec(quote(do: t() :: foo(1))) == ~s[t() :: <a href="#t:foo/1">foo</a>(1)] assert typespec(quote(do: t() :: bar(foo(1)))) == ~s[t() :: bar(<a href="#t:foo/1">foo</a>(1))] assert typespec(quote(do: (t() :: bar(foo(1)) when bat: foo(1)))) == ~s[t() :: bar(<a href="#t:foo/1">foo</a>(1)) when bat: <a href=\"#t:foo/1\">foo</a>(1)] assert typespec(quote(do: t() :: bar(baz(1)))) == ~s[t() :: bar(baz(1))] assert typespec(quote(do: t() :: foo(bar(), bar()))) == ~s[t() :: <a href="#t:foo/2">foo</a>(bar(), bar())] assert typespec(quote(do: t() :: foo!(bar()))) == ~s[t() :: <a href="#t:foo!/1">foo!</a>(bar())] end test "remotes" do ExDoc.Refs.insert([ {{:module, Foo}, true}, {{:type, Foo, :t, 0}, true} ]) assert typespec(quote(do: t() :: Foo.t())) == ~s[t() :: <a href="Foo.html#t:t/0">Foo.t</a>()] end test "autolinks same type and function name" do ExDoc.Refs.insert([ {{:module, MyModule}, true}, {{:type, MyModule, :foo, 0}, true}, {{:type, MyModule, :foo, 1}, true} ]) assert typespec(quote(do: foo() :: foo())) ~s[foo() :: <a href="#t:foo/0">foo</a>()] assert typespec(quote(do: foo(1) :: foo(1))) == ~s[foo(1) :: <a href="#t:foo/1">foo</a>(1)] assert typespec(quote(do: (foo(1) :: foo(1) when bat: foo(1)))) == ~s[foo(1) :: <a href=\"#t:foo/1\">foo</a>(1) when bat: <a href=\"#t:foo/1\">foo</a>(1)] assert typespec(quote(do: bar(foo(1)) :: foo(1))) == ~s[bar(<a href=\"#t:foo/1\">foo</a>(1)) :: <a href=\"#t:foo/1\">foo</a>(1)] assert typespec(quote(do: (bar(foo(1)) :: foo(1) when bat: foo(1)))) == ~s[bar(<a href=\"#t:foo/1\">foo</a>(1)) :: <a href=\"#t:foo/1\">foo</a>(1) when bat: <a href=\"#t:foo/1\">foo</a>(1)] assert typespec(quote(do: bar(foo :: foo(1)) :: foo(1))) == ~s[bar(foo :: <a href=\"#t:foo/1\">foo</a>(1)) :: <a href=\"#t:foo/1\">foo</a>(1)] end test "Elixir stdlib types" do assert typespec(quote(do: t() :: String.t())) == ~s[t() :: <a href="https://hexdocs.pm/elixir/String.html#t:t/0">String.t</a>()] end test "Elixir basic types" do assert typespec(quote(do: t() :: atom())) == ~s[t() :: <a href=\"https://hexdocs.pm/elixir/typespecs.html#basic-types\">atom</a>()] end test "Elixir built-in types" do assert typespec(quote(do: t() :: keyword())) == ~s[t() :: <a href=\"https://hexdocs.pm/elixir/typespecs.html#built-in-types\">keyword</a>()] end test "Erlang stdlib types" do assert typespec(quote(do: t() :: :sets.set())) == ~s[t() :: <a href=\"http://www.erlang.org/doc/man/sets.html#type-set\">:sets.set</a>()] end end test "warnings" do ExDoc.Refs.insert([ {{:module, Foo}, true}, {{:function, Foo, :bar, 1}, false}, {{:type, Foo, :bad, 0}, false} ]) captured = assert_warn(fn -> assert_unchanged("Foo.bar/1", file: "lib/foo.ex", line: 1, id: nil) end) assert captured =~ "documentation references function Foo.bar/1" assert captured =~ ~r{lib/foo.ex:1\n$} captured = assert_warn(fn -> assert_unchanged("Foo.bar/1", file: "lib/foo.ex", id: "Foo.foo/0") end) assert captured =~ "documentation references function Foo.bar/1" assert captured =~ ~r{lib/foo.ex: Foo.foo/0\n$} assert_warn(fn -> assert_unchanged("String.upcase/9") end) assert_warn(fn -> assert_unchanged("c:GenServer.handle_call/9") end) assert_warn(fn -> assert_unchanged("t:Calendar.date/9") end) assert_warn(fn -> assert typespec(quote(do: t() :: Foo.bad())) == ~s[t() :: Foo.bad()] end) assert_warn(fn -> assert typespec(quote(do: t() :: String.bad())) == ~s[t() :: String.bad()] end) captured = assert_warn(fn -> opts = [extras: []] assert_unchanged(~m"[Foo](Foo Bar.md)", opts) end) assert captured =~ "documentation references file `Foo Bar.md` but it doesn't exist" options = [skip_undefined_reference_warnings_on: ["MyModule"], module_id: "MyModule"] assert_unchanged("String.upcase/9", options) end ## Helpers @default_options [app: :myapp, current_module: MyModule, module_id: "MyModule", file: "nofile"] defp autolink(ast_or_text, options \\ []) do ExDoc.Autolink.doc(ast(ast_or_text), Keyword.merge(@default_options, options)) end defp assert_unchanged(ast_or_text, options \\ []) do assert autolink(ast_or_text, options) == ast(ast_or_text) end defp ast(text) when is_binary(text), do: {:code, [class: "inline"], [text]} defp ast({_, _, _} = ast), do: ast defp assert_warn(fun) do captured = capture_io(:stderr, fun) captured =~ "documentation references" captured end defp typespec(ast, options \\ []) do ExDoc.Autolink.typespec(ast, Keyword.merge(@default_options, options)) end end
33.330073
132
0.558172
0365670ef76fae01b27b5507adc42a3baf883ae1
1,761
ex
Elixir
clients/api_keys/lib/google_api/api_keys/v2/model/v2_clone_key_request.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/api_keys/lib/google_api/api_keys/v2/model/v2_clone_key_request.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/api_keys/lib/google_api/api_keys/v2/model/v2_clone_key_request.ex
dazuma/elixir-google-api
6a9897168008efe07a6081d2326735fe332e522c
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.APIKeys.V2.Model.V2CloneKeyRequest do @moduledoc """ Request message for `CloneKey` method. ## Attributes * `keyId` (*type:* `String.t`, *default:* `nil`) - User specified key id (optional). If specified, it will become the final component of the key resource name. The id must be unique within the project, must conform with RFC-1034, is restricted to lower-cased letters, and has a maximum length of 63 characters. In another word, the id must match the regular expression: `[a-z]([a-z0-9-]{0,61}[a-z0-9])?`. The id must NOT be a UUID-like string. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :keyId => String.t() | nil } field(:keyId) end defimpl Poison.Decoder, for: GoogleApi.APIKeys.V2.Model.V2CloneKeyRequest do def decode(value, options) do GoogleApi.APIKeys.V2.Model.V2CloneKeyRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.APIKeys.V2.Model.V2CloneKeyRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37.468085
447
0.735378
036588f27bfea502b6aeded29387717e228116e6
423
exs
Elixir
03/part1.exs
seantanly/elixir-advent_of_code
1e39ac46bc01f5c8cffd2d2f79f9af0b71767291
[ "MIT" ]
3
2016-01-18T01:14:45.000Z
2017-05-11T09:14:49.000Z
03/part1.exs
seantanly/elixir-advent_of_code
1e39ac46bc01f5c8cffd2d2f79f9af0b71767291
[ "MIT" ]
null
null
null
03/part1.exs
seantanly/elixir-advent_of_code
1e39ac46bc01f5c8cffd2d2f79f9af0b71767291
[ "MIT" ]
null
null
null
result = Path.join(__DIR__, "input.txt") |> File.read! |> String.split("", trim: true) |> Enum.reduce({0, 0, Set.put(MapSet.new, {0,0})}, fn instr, {x, y, set} -> {x, y} = case instr do "^" -> {x, y - 1} "v" -> {x, y + 1} ">" -> {x + 1, y} "<" -> {x - 1, y} _ -> raise "Unknown instr: #{inspect instr}" end {x, y, Set.put(set, {x, y})} end) |> elem(2) |> MapSet.size |> IO.inspect ^result = 2592
22.263158
75
0.486998
0365d6eb2a9c3f1ee00642d034272254eb7a0776
68
ex
Elixir
lib/yourbot_web/views/user_session_view.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
3
2021-11-08T15:19:19.000Z
2021-11-11T03:18:35.000Z
lib/yourbot_web/views/user_session_view.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
lib/yourbot_web/views/user_session_view.ex
ConnorRigby/yourbot
eea40e63b0f93963ed14b7efab9ecbe898ab11dd
[ "Apache-2.0" ]
null
null
null
defmodule YourBotWeb.UserSessionView do use YourBotWeb, :view end
17
39
0.823529
0365fb2ac6720f28d6f2ff5232deaff3d4142caa
734
ex
Elixir
lib/pushover/model/message_response.ex
RMATech/pushover
eb4bc2eaf5f247dd8fa2902886a0de028f6b56c2
[ "MIT" ]
2
2021-02-06T14:41:02.000Z
2021-04-13T06:17:09.000Z
lib/pushover/model/message_response.ex
RMATech/pushover
eb4bc2eaf5f247dd8fa2902886a0de028f6b56c2
[ "MIT" ]
null
null
null
lib/pushover/model/message_response.ex
RMATech/pushover
eb4bc2eaf5f247dd8fa2902886a0de028f6b56c2
[ "MIT" ]
1
2021-06-23T15:33:55.000Z
2021-06-23T15:33:55.000Z
defmodule Pushover.Model.MessageResponse do @moduledoc """ A message response. ## Attributes * `request` (*type:* `String.t`) - request id, e.g. "d2543c10-e59c-41f6-913c-0d4fcfc6d3ec" * `status` (*type:* `Integer.t`) - 1 for success """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :request => String.t(), :status => Integer.t() } field(:request) field(:status) end defimpl Poison.Decoder, for: Pushover.Model.MessageResponse do def decode(value, options) do Pushover.Model.MessageResponse.decode(value, options) end end defimpl Poison.Encoder, for: Pushover.Model.MessageResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
22.242424
94
0.689373
0366044453400a2c68e58d76059563e95afed321
3,295
exs
Elixir
test/type/ci_string_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
null
null
null
test/type/ci_string_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
null
null
null
test/type/ci_string_test.exs
MrFlorius/ash
247abbb8333d252da5440a58ddf4f1b7f184342f
[ "MIT" ]
null
null
null
defmodule Ash.Test.Type.CiString do @moduledoc false use ExUnit.Case, async: true import Ash.Changeset require Ash.Query defmodule Post do @moduledoc false use Ash.Resource, data_layer: Ash.DataLayer.Ets ets do private?(true) end attributes do uuid_primary_key :id # Possible constraint combinations: # # a. [allow_empty?: false, trim?: true] (default) # b. [allow_empty?: false, trim?: false] # c. [allow_empty?: true, trim?: true] # d. [allow_empty?: true, trim?: false] # attribute :string_a, :ci_string attribute :string_b, :ci_string, constraints: [trim?: false] attribute :string_c, :ci_string, constraints: [allow_empty?: true] attribute :string_d, :ci_string, constraints: [allow_empty?: true, trim?: false] attribute :string_e, :ci_string, constraints: [min_length: 3, max_length: 6] attribute :string_f, :ci_string, constraints: [min_length: 3, max_length: 6, trim?: false] end end defmodule Api do @moduledoc false use Ash.Api resources do resource(Post) end end test "it handles non-empty values" do post = Post |> new(%{ string_a: " Foo ", string_b: " fOo ", string_c: " baR ", string_d: " BaR " }) |> Api.create!() assert Comp.equal?(post.string_a, "foo") assert Comp.equal?(post.string_b, " foo ") assert Comp.equal?(post.string_c, "bar") assert Comp.equal?(post.string_d, " bar ") end test "it handles empty values" do post = Post |> new(%{ string_a: " ", string_b: " ", string_c: " ", string_d: " " }) |> Api.create!() assert post.string_a == nil assert post.string_b == nil assert Comp.equal?(post.string_c, "") assert Comp.equal?(post.string_d, " ") end test "it handles values with length constraints" do e_allowed_values = ["123", "123456", " 123456 "] f_allowed_values = [" 2 ", "123456", " 34 "] allowed_values = Enum.zip(e_allowed_values, f_allowed_values) Enum.each(allowed_values, fn {e_val, f_val} -> Post |> new(%{string_e: e_val, string_f: f_val}) |> Api.create!() end) end test "it handles too short values with length constraints" do assert_raise(Ash.Error.Invalid, ~r/string_e: length must be greater/, fn -> Post |> new(%{string_e: " 45 "}) |> Api.create!() end) assert_raise(Ash.Error.Invalid, ~r/string_f: length must be greater/, fn -> Post |> new(%{string_f: "12"}) |> Api.create!() end) end test "it handles too long values with length constraints" do assert_raise(Ash.Error.Invalid, ~r/string_e: length must be less/, fn -> Post |> new(%{string_e: "1234567"}) |> Api.create!() end) assert_raise(Ash.Error.Invalid, ~r/string_f: length must be less/, fn -> Post |> new(%{string_f: " 45 "}) |> Api.create!() end) end test "filters are case insensitive" do Post |> new(%{string_f: "foobar"}) |> Api.create!() assert [_] = Post |> Ash.Query.filter(string_f == "FoObAr") |> Api.read!() end end
25.152672
96
0.583915
036607cdc361438736316ee16f8faa927201abb8
1,305
exs
Elixir
apps/rig_kafka/mix.exs
vanillebear/reactive-interaction-gateway
5eb2afa00b8e74bddfd712ba282a3768e8ede239
[ "Apache-2.0" ]
null
null
null
apps/rig_kafka/mix.exs
vanillebear/reactive-interaction-gateway
5eb2afa00b8e74bddfd712ba282a3768e8ede239
[ "Apache-2.0" ]
132
2018-11-26T14:00:54.000Z
2022-03-11T04:17:54.000Z
apps/rig_kafka/mix.exs
vanillebear/reactive-interaction-gateway
5eb2afa00b8e74bddfd712ba282a3768e8ede239
[ "Apache-2.0" ]
null
null
null
defmodule RigKafka.MixProject do @moduledoc false use Mix.Project def project do %{rig: rig_version, elixir: elixir_version} = versions() [ app: :rig_kafka, version: rig_version, build_path: "../../_build", config_path: "../../config/config.exs", deps_path: "../../deps", lockfile: "../../mix.lock", elixir: elixir_version, start_permanent: Mix.env() == :prod, deps: deps(), test_coverage: [tool: ExCoveralls] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], mod: {RigKafka.Application, []} ] end defp versions do {map, []} = Code.eval_file("version", "../..") map end # Run "mix help deps" to learn about dependencies. defp deps do [ # The Kafka client: {:brod, "~> 3.7"}, # For Kafka, partition from MurmurHash(key): {:murmur, "~> 1.0"}, # Apache Avro encoding/decoding library: {:erlavro, "~> 2.6.3"}, # Apache Kafka Schema Registry wrapper library: {:schemex, "~> 0.1.1"}, # Caching library using ETS: {:memoize, "~> 1.3"}, {:fake_server, "~> 2.0", only: :test}, # For generating client_id: {:uuid, "~> 1.1"} ] end end
24.166667
60
0.562452
03660d9e651c2d46bc2000ccdaf86841cd77dd73
1,823
ex
Elixir
elixir/lib/homework_web/schemas/transactions_schema.ex
Bryrow/web-homework
d142134a4d2f13cee1178724786909b0dddaa496
[ "MIT" ]
null
null
null
elixir/lib/homework_web/schemas/transactions_schema.ex
Bryrow/web-homework
d142134a4d2f13cee1178724786909b0dddaa496
[ "MIT" ]
null
null
null
elixir/lib/homework_web/schemas/transactions_schema.ex
Bryrow/web-homework
d142134a4d2f13cee1178724786909b0dddaa496
[ "MIT" ]
null
null
null
defmodule HomeworkWeb.Schemas.TransactionsSchema do @moduledoc """ Defines the graphql schema for transactions. """ use Absinthe.Schema.Notation alias HomeworkWeb.Resolvers.TransactionsResolver object :transaction do field(:id, non_null(:id)) field(:user_id, :id) @desc "amount is in cents" field(:amount, :integer) field(:credit, :boolean) field(:debit, :boolean) field(:description, :string) field(:merchant_id, :id) field(:inserted_at, :naive_datetime) field(:updated_at, :naive_datetime) field(:user, :user) do resolve(&TransactionsResolver.user/3) end field(:merchant, :merchant) do resolve(&TransactionsResolver.merchant/3) end end object :transaction_mutations do @desc "Create a new transaction" field :create_transaction, :transaction do arg(:user_id, non_null(:id)) arg(:merchant_id, non_null(:id)) @desc "amount is in cents" arg(:amount, non_null(:integer)) arg(:credit, non_null(:boolean)) arg(:debit, non_null(:boolean)) arg(:description, non_null(:string)) resolve(&TransactionsResolver.create_transaction/3) end @desc "Update a new transaction" field :update_transaction, :transaction do arg(:id, non_null(:id)) arg(:user_id, non_null(:id)) arg(:merchant_id, non_null(:id)) @desc "amount is in cents" arg(:amount, non_null(:integer)) arg(:credit, non_null(:boolean)) arg(:debit, non_null(:boolean)) arg(:description, non_null(:string)) resolve(&TransactionsResolver.update_transaction/3) end @desc "delete an existing transaction" field :delete_transaction, :transaction do arg(:id, non_null(:id)) resolve(&TransactionsResolver.delete_transaction/3) end end end
27.621212
57
0.671969
03661d435d86008da9ea3fee243f2e69a1b6faef
5,093
ex
Elixir
lib/redlock.ex
kalymero/redlock
8b6e57f4f1b9da286614948c673a0294b7d074bf
[ "MIT" ]
null
null
null
lib/redlock.ex
kalymero/redlock
8b6e57f4f1b9da286614948c673a0294b7d074bf
[ "MIT" ]
null
null
null
lib/redlock.ex
kalymero/redlock
8b6e57f4f1b9da286614948c673a0294b7d074bf
[ "MIT" ]
null
null
null
defmodule Redlock do @moduledoc ~S""" This library is an implementation of Redlock (Redis destributed lock) [Redlock](https://redis.io/topics/distlock) ## Usage resource = "example_key:#{user_id}" lock_exp_sec = 10 case Redlock.lock(resource, lock_exp_sec) do {:ok, mutex} -> # some other code which write and read on RDBMS, KVS or other storage # call unlock finally Redlock.unlock(resource, mutex) :error -> Logger.error "failed to lock resource. maybe redis connection got trouble." {:error, :system_error} end Or you can use `transaction` function def my_function() do # do something, and return {:ok, :my_result} or {:error, :my_error} end def execute_with_lock() do resource = "example_key:#{user_id}" lock_exp_sec = 10 case Redlock.transaction(resource, lock_exp_sec, &my_function/0) do {:ok, :my_result} -> Logger.info "this is the return-value of my_function/0" :ok {:error, :my_error} -> Logger.info "this is the return-value of my_function/0" :error {:error, :lock_failure} -> Logger.info "if locking has failed, Redlock returns this error" :error end end ## Setup children = [ # other workers/supervisors {Redlock, redlock_opts} ] Supervisor.start_link(children, strategy: :one_for_one) ## Options ### Single Node Mode readlock_opts = [ pool_size: 2, drift_factor: 0.01, max_retry: 3, retry_interval_base: 300, retry_interval_max: 3_000, reconnection_interval_base: 500, reconnection_interval_max: 5_000, # you must set odd number of server servers: [ [host: "redis1.example.com", port: 6379], [host: "redis2.example.com", port: 6379], [host: "redis3.example.com", port: 6379] ] ] - `pool_size`: pool_size of number of connection pool for each Redis master node, default is 2 - `drift_factor`: number used for calculating validity for results, see https://redis.io/topics/distlock for more detail. - `max_retry`: how many times you want to retry if you failed to lock resource. - `retry_interval_max`: (milliseconds) used to decide how long you want to wait untill your next try after a lock-failure. - `retry_interval_base`: (milliseconds) used to decide how long you want to wait untill your next try after a lock-failure. - `reconnection_interval_base`: (milliseconds) used to decide how long you want to wait until your next try after a redis-disconnection - `reconnection_interval_max`: (milliseconds) used to decide how long you want to wait until your next try after a redis-disconnection - `servers`: host and port settings for each redis-server. this amount must be odd. #### How long you want to wait until your next try after a redis-disconnection or lock-failure the interval(milliseconds) is decided by following calculation. min(XXX_interval_max, (XXX_interval_base * (attempts_count ** 2))) ### Cluster Mode readlock_opts = [ pool_size: 2, drift_factor: 0.01, max_retry: 3, retry_interval_base: 300, retry_interval_max: 3_000, reconnection_interval_base: 500, reconnection_interval_max: 5_000, cluster: [ # first node [ # you must set odd number of server [host: "redis1.example.com", port: 6379], [host: "redis2.example.com", port: 6379], [host: "redis3.example.com", port: 6379] ], # second node [ # you must set odd number of server [host: "redis4.example.com", port: 6379], [host: "redis5.example.com", port: 6379], [host: "redis6.example.com", port: 6379] ], # third node [ # you must set odd number of server [host: "redis7.example.com", port: 6379], [host: "redis8.example.com", port: 6379], [host: "redis9.example.com", port: 6379] ] ] ] Set `cluster` option instead of `servers`, then Redlock works as cluster mode. When you want to lock some resource, Redlock chooses a node depends on a resource key with consistent-hashing. """ def child_spec(opts) do Redlock.Supervisor.child_spec(opts) end def transaction(resource, ttl, callback) do case Redlock.Executor.lock(resource, ttl) do {:ok, mutex} -> try do callback.() after Redlock.Executor.unlock(resource, mutex) end :error -> {:error, :lock_failure} end end def lock(resource, ttl) do Redlock.Executor.lock(resource, ttl) end def unlock(resource, value) do Redlock.Executor.unlock(resource, value) end end
29.439306
137
0.606911
03662a620fef7086648acc721201d3556d18fa63
20,900
ex
Elixir
lib/swoosh/email.ex
Deepwalker/swoosh
5970e1a20e5d787347ce825f4803e972ddc30095
[ "MIT" ]
1
2020-01-19T04:55:09.000Z
2020-01-19T04:55:09.000Z
lib/swoosh/email.ex
Deepwalker/swoosh
5970e1a20e5d787347ce825f4803e972ddc30095
[ "MIT" ]
null
null
null
lib/swoosh/email.ex
Deepwalker/swoosh
5970e1a20e5d787347ce825f4803e972ddc30095
[ "MIT" ]
1
2019-11-05T19:06:55.000Z
2019-11-05T19:06:55.000Z
defmodule Swoosh.Email do @moduledoc """ Defines an Email. This module defines a `Swoosh.Email` struct and the main functions for composing an email. As it is the contract for the public APIs of Swoosh it is a good idea to make use of these functions rather than build the struct yourself. ## Email fields * `from` - the email address of the sender, example: `{"Tony Stark", "tony.stark@example.com"}` * `to` - the email address for the recipient(s), example: `[{"Steve Rogers", "steve.rogers@example.com"}]` * `subject` - the subject of the email, example: `"Hello, Avengers!"` * `cc` - the intended carbon copy recipient(s) of the email, example: `[{"Bruce Banner", "hulk.smash@example.com"}]` * `bcc` - the intended blind carbon copy recipient(s) of the email, example: `[{"Janet Pym", "wasp.avengers@example.com"}]` * `text_body` - the content of the email in plaintext, example: `"Hello"` * `html_body` - the content of the email in HTML, example: `"<h1>Hello</h1>"` * `reply_to` - the email address that should receive replies, example: `{"Clints Barton", "hawk.eye@example.com"}` * `headers` - a map of headers that should be included in the email, example: `%{"X-Accept-Language" => "en-us, en"}` * `attachments` - a list of attachments that should be included in the email, example: `[%{path: "/data/uuid-random", filename: "att.zip", content_type: "application/zip"}]` * `assigns` - a map of values that correspond with any template variables, example: `%{"first_name" => "Bruce"}` ## Private This key is reserved for use with adapters, libraries and frameworks. * `private` - a map of values that are for use by libraries/frameworks, example: `%{phoenix_template: "welcome.html.eex"}` - `hackney_options` will be passed to underlining hackney post call ## Provider options This key allow users to make use of provider-specific functionality by passing along addition parameters. * `provider_options` - a map of values that are specific to adapter provider, example: `%{async: true}` ## Examples email = new() |> to("tony.stark@example.com") |> from("bruce.banner@example.com") |> text_body("Welcome to the Avengers") The composable nature makes it very easy to continue expanding upon a given Email. email = email |> cc({"Steve Rogers", "steve.rogers@example.com"}) |> cc("wasp.avengers@example.com") |> bcc(["thor.odinson@example.com", {"Henry McCoy", "beast.avengers@example.com"}]) |> html_body("<h1>Special Welcome</h1>") You can also directly pass arguments to the `new/1` function. email = new(from: "tony.stark@example.com", to: "steve.rogers@example.com", subject: "Hello, Avengers!") """ import Swoosh.Email.Format defstruct subject: "", from: nil, to: [], cc: [], bcc: [], text_body: nil, html_body: nil, attachments: [], reply_to: nil, headers: %{}, private: %{}, assigns: %{}, provider_options: %{} @type name :: String.t() @type address :: String.t() @type mailbox :: {name, address} @type subject :: String.t() @type text_body :: String.t() @type html_body :: String.t() @type t :: %__MODULE__{ subject: String.t(), from: mailbox | nil, to: [mailbox], cc: [mailbox] | [], bcc: [mailbox] | [], text_body: text_body | nil, html_body: html_body | nil, reply_to: mailbox | nil, headers: map, private: map, assigns: map, attachments: [Swoosh.Attachment.t()], provider_options: map } @doc ~S""" Returns a `Swoosh.Email` struct. You can pass a keyword list or a map argument to the function that will be used to populate the fields of that struct. Note that it will silently ignore any fields that it doesn't know about. ## Examples iex> new() %Swoosh.Email{} iex> new(subject: "Hello, Avengers!") %Swoosh.Email{subject: "Hello, Avengers!"} iex> new(from: "tony.stark@example.com") %Swoosh.Email{from: {"", "tony.stark@example.com"}} iex> new(from: {"Tony Stark", "tony.stark@example.com"}) %Swoosh.Email{from: {"Tony Stark", "tony.stark@example.com"}} iex> new(to: "steve.rogers@example.com") %Swoosh.Email{to: [{"", "steve.rogers@example.com"}]} iex> new(to: {"Steve Rogers", "steve.rogers@example.com"}) %Swoosh.Email{to: [{"Steve Rogers", "steve.rogers@example.com"}]} iex> new(to: [{"Bruce Banner", "bruce.banner@example.com"}, "thor.odinson@example.com"]) %Swoosh.Email{to: [{"Bruce Banner", "bruce.banner@example.com"}, {"", "thor.odinson@example.com"}]} iex> new(cc: "steve.rogers@example.com") %Swoosh.Email{cc: [{"", "steve.rogers@example.com"}]} iex> new(cc: {"Steve Rogers", "steve.rogers@example.com"}) %Swoosh.Email{cc: [{"Steve Rogers", "steve.rogers@example.com"}]} iex> new(cc: [{"Bruce Banner", "bruce.banner@example.com"}, "thor.odinson@example.com"]) %Swoosh.Email{cc: [{"Bruce Banner", "bruce.banner@example.com"}, {"", "thor.odinson@example.com"}]} iex> new(bcc: "steve.rogers@example.com") %Swoosh.Email{bcc: [{"", "steve.rogers@example.com"}]} iex> new(bcc: {"Steve Rogers", "steve.rogers@example.com"}) %Swoosh.Email{bcc: [{"Steve Rogers", "steve.rogers@example.com"}]} iex> new(bcc: [{"Bruce Banner", "bruce.banner@example.com"}, "thor.odinson@example.com"]) %Swoosh.Email{bcc: [{"Bruce Banner", "bruce.banner@example.com"}, {"", "thor.odinson@example.com"}]} iex> new(html_body: "<h1>Welcome, Avengers</h1>") %Swoosh.Email{html_body: "<h1>Welcome, Avengers</h1>"} iex> new(text_body: "Welcome, Avengers") %Swoosh.Email{text_body: "Welcome, Avengers"} iex> new(reply_to: "edwin.jarvis@example.com") %Swoosh.Email{reply_to: {"", "edwin.jarvis@example.com"}} iex> new(reply_to: {"Edwin Jarvis", "edwin.jarvis@example.com"}) %Swoosh.Email{reply_to: {"Edwin Jarvis", "edwin.jarvis@example.com"}} iex> new(headers: %{"X-Accept-Language" => "en"}) %Swoosh.Email{headers: %{"X-Accept-Language" => "en"}} iex> new(assigns: %{user_id: 10}) %Swoosh.Email{assigns: %{user_id: 10}} iex> new(provider_options: %{async: true}) %Swoosh.Email{provider_options: %{async: true}} You can obviously combine these arguments together: iex> new(to: "steve.rogers@example.com", subject: "Hello, Avengers!") %Swoosh.Email{to: [{"", "steve.rogers@example.com"}], subject: "Hello, Avengers!"} """ @spec new(none | Enum.t()) :: t def new(opts \\ []) do Enum.reduce(opts, %__MODULE__{}, &do_new/2) end defp do_new({key, value}, email) when key in [ :subject, :from, :to, :cc, :bcc, :reply_to, :text_body, :html_body, :attachment ] do apply(__MODULE__, key, [email, value]) end defp do_new({key, value}, email) when key in [:headers, :assigns, :provider_options] do Map.put(email, key, value) end defp do_new({key, value}, _email) do raise ArgumentError, message: """ invalid field `#{inspect(key)}` (value=#{inspect(value)}) for Swoosh.Email.new/1. """ end @doc """ Sets a recipient in the `from` field. The recipient must be either; a tuple specifying the name and address of the recipient; a string specifying the address of the recipient. ## Examples iex> new() |> from({"Steve Rogers", "steve.rogers@example.com"}) %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: {"Steve Rogers", "steve.rogers@example.com"}, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} iex> new() |> from("steve.rogers@example.com") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: {"", "steve.rogers@example.com"}, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec from(t, mailbox | address) :: t def from(%__MODULE__{} = email, from) do from = format_recipient(from) %{email | from: from} end @doc """ Sets a recipient in the `reply_to` field. The recipient must be either; a tuple specifying the name and address of the recipient; a string specifying the address of the recipient. ## Examples iex> new() |> reply_to({"Steve Rogers", "steve.rogers@example.com"}) %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: {"Steve Rogers", "steve.rogers@example.com"}, subject: "", text_body: nil, to: []} iex> new() |> reply_to("steve.rogers@example.com") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: {"", "steve.rogers@example.com"}, subject: "", text_body: nil, to: []} """ @spec reply_to(t, mailbox | address) :: t def reply_to(%__MODULE__{} = email, reply_to) do reply_to = format_recipient(reply_to) %{email | reply_to: reply_to} end @doc """ Sets the `subject` field. The subject must be a string that contains the subject. ## Examples iex> new() |> subject("Hello, Avengers!") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "Hello, Avengers!", text_body: nil, to: []} """ @spec subject(t, subject) :: t def subject(email, subject), do: %{email | subject: subject} @doc """ Sets the `text_body` field. The text body must be a string that containing the plaintext content. ## Examples iex> new() |> text_body("Hello") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: "Hello", to: []} """ @spec text_body(t, text_body | nil) :: t def text_body(email, text_body), do: %{email | text_body: text_body} @doc """ Sets the `html_body` field. The HTML body must be a string that containing the HTML content. ## Examples iex> new() |> html_body("<h1>Hello</h1>") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: "<h1>Hello</h1>", private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec html_body(t, html_body | nil) :: t def html_body(email, html_body), do: %{email | html_body: html_body} @doc """ Adds new recipients in the `bcc` field. The recipient must be; a tuple specifying the name and address of the recipient; a string specifying the address of the recipient; or an array comprised of a combination of either. iex> new() |> bcc("steve.rogers@example.com") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [{"", "steve.rogers@example.com"}], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec bcc(t, mailbox | address | [mailbox | address]) :: t def bcc(%__MODULE__{bcc: bcc} = email, recipients) when is_list(recipients) do recipients = recipients |> Enum.map(&format_recipient(&1)) |> Enum.concat(bcc) %{email | bcc: recipients} end def bcc(%__MODULE__{} = email, recipient) do bcc(email, [recipient]) end @doc """ Puts new recipients in the `bcc` field. It will replace any previously added `bcc` recipients. """ @spec put_bcc(t, mailbox | address | [mailbox | address]) :: t def put_bcc(%__MODULE__{} = email, recipients) when is_list(recipients) do %{email | bcc: Enum.map(recipients, &format_recipient(&1))} end def put_bcc(%__MODULE__{} = email, recipient) do put_bcc(email, [recipient]) end @doc """ Adds new recipients in the `cc` field. The recipient must be; a tuple specifying the name and address of the recipient; a string specifying the address of the recipient; or an array comprised of a combination of either. ## Examples iex> new() |> cc("steve.rogers@example.com") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [{"", "steve.rogers@example.com"}], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec cc(t, mailbox | address | [mailbox | address]) :: t def cc(%__MODULE__{cc: cc} = email, recipients) when is_list(recipients) do recipients = recipients |> Enum.map(&format_recipient(&1)) |> Enum.concat(cc) %{email | cc: recipients} end def cc(%__MODULE__{} = email, recipient) do cc(email, [recipient]) end @doc """ Puts new recipients in the `cc` field. It will replace any previously added `cc` recipients. """ @spec put_cc(t, mailbox | address | [mailbox | address]) :: t def put_cc(%__MODULE__{} = email, recipients) when is_list(recipients) do %{email | cc: Enum.map(recipients, &format_recipient(&1))} end def put_cc(%__MODULE__{} = email, recipient) do put_cc(email, [recipient]) end @doc """ Adds new recipients in the `to` field. The recipient must be; a tuple specifying the name and address of the recipient; a string specifying the address of the recipient; or an array comprised of a combination of either. ## Examples iex> new() |> to("steve.rogers@example.com") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: [{"", "steve.rogers@example.com"}]} """ @spec to(t, mailbox | address | [mailbox | address]) :: t def to(%__MODULE__{to: to} = email, recipients) when is_list(recipients) do recipients = recipients |> Enum.map(&format_recipient(&1)) |> Enum.concat(to) %{email | to: recipients} end def to(%__MODULE__{} = email, recipient) do to(email, [recipient]) end @doc """ Puts new recipients in the `to` field. It will replace any previously added `to` recipients. """ @spec put_to(t, mailbox | address | [mailbox | address]) :: t def put_to(%__MODULE__{} = email, recipients) when is_list(recipients) do %{email | to: Enum.map(recipients, &format_recipient(&1))} end def put_to(%__MODULE__{} = email, recipient) do put_to(email, [recipient]) end @doc """ Adds a new `header` in the email. The name and value must be specified as strings. ## Examples iex> new() |> header("X-Magic-Number", "7") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{"X-Magic-Number" => "7"}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec header(t, String.t(), String.t()) :: t def header(%__MODULE__{} = email, name, value) when is_binary(name) and is_binary(value) do put_in(email.headers[name], value) end def header(%__MODULE__{}, name, value) do raise ArgumentError, message: """ header/3 expects the header name and value to be strings. Instead it got: name: `#{inspect(name)}`. value: `#{inspect(value)}`. """ end @doc ~S""" Stores a new **private** key and value in the email. This store is meant to be for libraries/framework usage. The name should be specified as an atom, the value can be any term. ## Examples iex> new() |> put_private(:phoenix_template, "welcome.html") %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{phoenix_template: "welcome.html"}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec put_private(t, atom, any) :: t def put_private(%__MODULE__{private: private} = email, key, value) when is_atom(key) do %{email | private: Map.put(private, key, value)} end @doc ~S""" Stores a new **provider_option** key and value in the email. This store is meant for adapter usage, to aid provider-specific functionality. The name should be specified as an atom, the value can be any term. ## Examples iex> new() |> put_provider_option(:async, true) %Swoosh.Email{assigns: %{}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{async: true}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec put_provider_option(t, atom, any) :: t def put_provider_option(%__MODULE__{provider_options: provider_options} = email, key, value) when is_atom(key) do %{email | provider_options: Map.put(provider_options, key, value)} end @doc ~S""" Stores a new variable key and value in the email. This store is meant for variables used in templating. The name should be specified as an atom, the value can be any term. ## Examples iex> new() |> assign(:username, "ironman") %Swoosh.Email{assigns: %{username: "ironman"}, attachments: [], bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: []} """ @spec assign(t, atom, any) :: t def assign(%__MODULE__{assigns: assigns} = email, key, value) when is_atom(key) do %{email | assigns: Map.put(assigns, key, value)} end @doc ~S""" Add a new attachment in the email. You can pass the path to a file, a `Swoosh.Attachment` or a `%Plug.Upload{}` struct as an argument. If you give a path we will detect the MIME type and determine the filename automatically. You can also send an inline-attachment used for embedding images in the body of emails by specifying `type: :inline` ## Examples iex> new() |> attachment("/data/att.zip") %Swoosh.Email{assigns: %{}, bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: [], attachments: [%Swoosh.Attachment{path: "/data/att.zip", content_type: "application/zip", filename: "att.zip", type: :attachment, data: nil, headers: []}]} iex> new() |> attachment(Swoosh.Attachment.new("/data/att.zip")) %Swoosh.Email{assigns: %{}, bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: [], attachments: [%Swoosh.Attachment{path: "/data/att.zip", content_type: "application/zip", filename: "att.zip", type: :attachment, data: nil, headers: []}]} iex> new() |> attachment(%Plug.Upload{path: "/data/abcdefg", content_type: "test/type", filename: "att.zip"}) %Swoosh.Email{assigns: %{}, bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: [], attachments: [%Swoosh.Attachment{path: "/data/abcdefg", content_type: "test/type", filename: "att.zip", type: :attachment, data: nil, headers: []}]} iex> new() |> attachment(Swoosh.Attachment.new("/data/att.png", type: :inline)) %Swoosh.Email{assigns: %{}, bcc: [], cc: [], from: nil, headers: %{}, html_body: nil, private: %{}, provider_options: %{}, reply_to: nil, subject: "", text_body: nil, to: [], attachments: [%Swoosh.Attachment{path: "/data/att.png", content_type: "image/png", filename: "att.png", type: :inline, data: nil, headers: []}]} """ @spec attachment(t, binary | Swoosh.Attachment.t()) :: t def attachment(%__MODULE__{attachments: attachments} = email, path) when is_binary(path) do %{email | attachments: [Swoosh.Attachment.new(path) | attachments]} end def attachment(%__MODULE__{attachments: attachments} = email, %Swoosh.Attachment{} = attachment) do %{email | attachments: [attachment | attachments]} end if Code.ensure_loaded?(Plug) do def attachment(%__MODULE__{attachments: attachments} = email, %Plug.Upload{} = upload) do %{email | attachments: [Swoosh.Attachment.new(upload) | attachments]} end end end
37.931034
175
0.61756
0366323edeccd9478636ba15fe18b71f4164f6d1
16,968
ex
Elixir
lib/ecto/date_time.ex
tokafish/ecto
45d23da6faf660303484d0c993930af674685631
[ "Apache-2.0" ]
null
null
null
lib/ecto/date_time.ex
tokafish/ecto
45d23da6faf660303484d0c993930af674685631
[ "Apache-2.0" ]
null
null
null
lib/ecto/date_time.ex
tokafish/ecto
45d23da6faf660303484d0c993930af674685631
[ "Apache-2.0" ]
null
null
null
import Kernel, except: [to_string: 1] defmodule Ecto.DateTime.Utils do @moduledoc false @doc "Pads with zero" def zero_pad(val, count) do num = Integer.to_string(val) pad_length = max(count - byte_size(num), 0) :binary.copy("0", pad_length) <> num end @doc "Converts to integer if possible" def to_i(nil), do: nil def to_i(int) when is_integer(int), do: int def to_i(bin) when is_binary(bin) do case Integer.parse(bin) do {int, ""} -> int _ -> nil end end @doc "A guard to check for dates" defmacro is_date(_year, month, day) do quote do unquote(month) in 1..12 and unquote(day) in 1..31 end end @doc "A guard to check for times" defmacro is_time(hour, min, sec, usec \\ 0) do quote do unquote(hour) in 0..23 and unquote(min) in 0..59 and unquote(sec) in 0..59 and unquote(usec) in 0..999_999 end end @doc """ Checks if the trailing part of a date/time matches ISO specs. """ defmacro is_iso_8601(x) do quote do: unquote(x) in ["", "Z"] end @doc """ Gets microseconds from rest and validates it. Returns nil if an invalid format is given. """ def usec("." <> rest) do case parse(rest, "") do {int, rest} when byte_size(int) > 6 and is_iso_8601(rest) -> String.to_integer(binary_part(int, 0, 6)) {int, rest} when byte_size(int) in 1..6 and is_iso_8601(rest) -> pad = String.duplicate("0", 6 - byte_size(int)) String.to_integer(int <> pad) _ -> nil end end def usec(rest) when is_iso_8601(rest), do: 0 def usec(_), do: nil @doc """ Compare two datetimes. Receives two datetimes and compares the `t1` against `t2` and returns `:lt`, `:eq` or `:gt`. """ def compare(%{__struct__: module} = t1, %{__struct__: module} = t2) do {:ok, t1} = module.dump(t1) {:ok, t2} = module.dump(t2) cond do t1 == t2 -> :eq t1 > t2 -> :gt true -> :lt end end defp parse(<<h, t::binary>>, acc) when h in ?0..?9, do: parse(t, <<acc::binary, h>>) defp parse(rest, acc), do: {acc, rest} end defmodule Ecto.Date do import Ecto.DateTime.Utils @doc """ Compare two dates. Receives two dates and compares the `t1` against `t2` and returns `:lt`, `:eq` or `:gt`. """ defdelegate compare(t1, t2), to: Ecto.DateTime.Utils @moduledoc """ An Ecto type for dates. """ @behaviour Ecto.Type defstruct [:year, :month, :day] @doc """ The Ecto primitive type. """ def type, do: :date @doc """ Casts the given value to date. It supports: * a binary in the "YYYY-MM-DD" format * a binary in the "YYYY-MM-DD HH:MM:DD" format (may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00Z`) * a binary in the "YYYY-MM-DD HH:MM:DD.USEC" format (may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00.030Z`) * a map with `"year"`, `"month"` and `"day"` keys with integer or binaries as values * a map with `:year`, `:month` and `:day` keys with integer or binaries as values * a tuple with `{year, month, day}` as integers or binaries * an `Ecto.Date` struct itself """ def cast(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes>>), do: from_parts(to_i(year), to_i(month), to_i(day)) def cast(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, _hour::2-bytes, ?:, _min::2-bytes, ?:, _sec::2-bytes, _rest::binary>>) when sep in [?\s, ?T], do: from_parts(to_i(year), to_i(month), to_i(day)) def cast(%Ecto.Date{} = d), do: {:ok, d} def cast(%{"year" => year, "month" => month, "day" => day}), do: from_parts(to_i(year), to_i(month), to_i(day)) def cast(%{year: year, month: month, day: day}), do: from_parts(to_i(year), to_i(month), to_i(day)) def cast({year, month, day}), do: from_parts(to_i(year), to_i(month), to_i(day)) def cast(_), do: :error @doc """ Same as `cast/1` but raises on invalid dates. """ def cast!(value) do case cast(value) do {:ok, date} -> date :error -> raise ArgumentError, "cannot cast #{inspect value} to date" end end defp from_parts(year, month, day) when is_date(year, month, day) do {:ok, %Ecto.Date{year: year, month: month, day: day}} end defp from_parts(_, _, _), do: :error @doc """ Converts an `Ecto.Date` into a date triplet. """ def dump(%Ecto.Date{year: year, month: month, day: day}) do {:ok, {year, month, day}} end def dump(_), do: :error @doc """ Converts a date triplet into an `Ecto.Date`. """ def load({year, month, day}) do {:ok, %Ecto.Date{year: year, month: month, day: day}} end def load(_), do: :error @doc """ Converts `Ecto.Date` to a readable string representation. """ def to_string(%Ecto.Date{year: year, month: month, day: day}) do zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) end @doc """ Converts `Ecto.Date` to ISO8601 representation. """ def to_iso8601(date) do to_string(date) end @doc """ Returns an `Ecto.Date` in UTC. """ def utc do {{year, month, day}, _time} = :erlang.universaltime %Ecto.Date{year: year, month: month, day: day} end @doc """ Returns an Erlang date tuple from an `Ecto.Date`. """ def to_erl(%Ecto.Date{year: year, month: month, day: day}) do {year, month, day} end @doc """ Returns an `Ecto.Date` from an Erlang date tuple. """ def from_erl({year, month, day}) do %Ecto.Date{year: year, month: month, day: day} end end defmodule Ecto.Time do import Ecto.DateTime.Utils @doc """ Compare two times. Receives two times and compares the `t1` against `t2` and returns `:lt`, `:eq` or `:gt`. """ defdelegate compare(t1, t2), to: Ecto.DateTime.Utils @moduledoc """ An Ecto type for time. """ @behaviour Ecto.Type defstruct [:hour, :min, :sec, usec: 0] @doc """ The Ecto primitive type. """ def type, do: :time @doc """ Casts the given value to time. It supports: * a binary in the "HH:MM:DD" format (may be followed by "Z", as in `12:00:00Z`) * a binary in the "HH:MM:DD.USEC" format (may be followed by "Z", as in `12:00:00.005Z`) * a map with `"hour"`, `"min"` keys with `"sec"` and `"usec"` as optional keys and values are integers or binaries * a map with `:hour`, `:min` keys with `:sec` and `:usec` as optional keys and values are integers or binaries * a tuple with `{hour, min, sec}` as integers or binaries * a tuple with `{hour, min, sec, usec}` as integers or binaries * an `Ecto.Time` struct itself """ def cast(<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>>) do if usec = usec(rest) do from_parts(to_i(hour), to_i(min), to_i(sec), usec) else :error end end def cast(%Ecto.Time{} = t), do: {:ok, t} def cast(%{"hour" => hour, "min" => min} = map), do: from_parts(to_i(hour), to_i(min), to_i(Map.get(map, "sec", 0)), to_i(Map.get(map, "usec", 0))) def cast(%{hour: hour, min: min} = map), do: from_parts(to_i(hour), to_i(min), to_i(Map.get(map, :sec, 0)), to_i(Map.get(map, :usec, 0))) def cast({hour, min, sec}), do: from_parts(to_i(hour), to_i(min), to_i(sec), 0) def cast({hour, min, sec, usec}), do: from_parts(to_i(hour), to_i(min), to_i(sec), to_i(usec)) def cast(_), do: :error @doc """ Same as `cast/1` but raises on invalid times. """ def cast!(value) do case cast(value) do {:ok, time} -> time :error -> raise ArgumentError, "cannot cast #{inspect value} to time" end end defp from_parts(hour, min, sec, usec) when is_time(hour, min, sec, usec), do: {:ok, %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}} defp from_parts(_, _, _, _), do: :error @doc """ Converts an `Ecto.Time` into a time tuple (in the form `{hour, min, sec, usec}`). """ def dump(%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do {:ok, {hour, min, sec, usec}} end def dump(_), do: :error @doc """ Converts a time tuple like the one returned by `dump/1` into an `Ecto.Time`. """ def load({hour, min, sec, usec}) do {:ok, %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}} end def load({_, _, _} = time) do {:ok, from_erl(time)} end def load(_), do: :error @doc """ Converts `Ecto.Time` to a string representation. """ def to_string(%Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do str = zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2) if is_nil(usec) or usec == 0 do str else str <> "." <> zero_pad(usec, 6) end end @doc """ Converts `Ecto.Time` to its ISO 8601 representation. """ def to_iso8601(time) do to_string(time) end @doc """ Returns an `Ecto.Time` in UTC. `precision` can be `:sec` or `:usec.` """ def utc(precision \\ :sec) def utc(:sec) do {_, {hour, min, sec}} = :erlang.universaltime %Ecto.Time{hour: hour, min: min, sec: sec} end def utc(:usec) do now = {_, _, usec} = :os.timestamp {_date, {hour, min, sec}} = :calendar.now_to_universal_time(now) %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec} end @doc """ Returns an Erlang time tuple from an `Ecto.Time`. """ def to_erl(%Ecto.Time{hour: hour, min: min, sec: sec}) do {hour, min, sec} end @doc """ Returns an `Ecto.Time` from an Erlang time tuple. """ def from_erl({hour, min, sec}) do %Ecto.Time{hour: hour, min: min, sec: sec} end end defmodule Ecto.DateTime do import Ecto.DateTime.Utils @doc """ Compare two datetimes. Receives two datetimes and compares the `t1` against `t2` and returns `:lt`, `:eq` or `:gt`. """ defdelegate compare(t1, t2), to: Ecto.DateTime.Utils @moduledoc """ An Ecto type that includes a date and a time. """ @behaviour Ecto.Type defstruct [:year, :month, :day, :hour, :min, :sec, usec: 0] @doc """ The Ecto primitive type. """ def type, do: :datetime @doc """ Casts the given value to datetime. It supports: * a binary in the "YYYY-MM-DD HH:MM:DD" format (may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00Z`) * a binary in the "YYYY-MM-DD HH:MM:DD.USEC" format (may be separated by T and/or followed by "Z", as in `2014-04-17T14:00:00.030Z`) * a map with `"year"`, `"month"`,`"day"`, `"hour"`, `"min"` keys with `"sec"` and `"usec"` as optional keys and values are integers or binaries * a map with `:year`, `:month`,`:day`, `:hour`, `:min` keys with `:sec` and `:usec` as optional keys and values are integers or binaries * a tuple with `{{year, month, day}, {hour, min, sec}}` as integers or binaries * a tuple with `{{year, month, day}, {hour, min, sec, usec}}` as integers or binaries * an `Ecto.DateTime` struct itself """ def cast(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>>) when sep in [?\s, ?T] do if usec = usec(rest) do from_parts(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(min), to_i(sec), usec) else :error end end def cast(%Ecto.DateTime{} = dt) do {:ok, dt} end def cast(%{"year" => year, "month" => month, "day" => day, "hour" => hour, "min" => min} = map) do from_parts(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(min), to_i(Map.get(map, "sec", 0)), to_i(Map.get(map, "usec", 0))) end def cast(%{year: year, month: month, day: day, hour: hour, min: min} = map) do from_parts(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(min), to_i(Map.get(map, :sec, 0)), to_i(Map.get(map, :usec, 0))) end def cast({{year, month, day}, {hour, min, sec}}) do from_parts(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(min), to_i(sec), 0) end def cast({{year, month, day}, {hour, min, sec, usec}}) do from_parts(to_i(year), to_i(month), to_i(day), to_i(hour), to_i(min), to_i(sec), to_i(usec)) end def cast(_) do :error end @doc """ Same as `cast/1` but raises on invalid datetimes. """ def cast!(value) do case cast(value) do {:ok, datetime} -> datetime :error -> raise ArgumentError, "cannot cast #{inspect value} to datetime" end end defp from_parts(year, month, day, hour, min, sec, usec) when is_date(year, month, day) and is_time(hour, min, sec, usec) do {:ok, %Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}} end defp from_parts(_, _, _, _, _, _, _), do: :error @doc """ Converts an `Ecto.DateTime` into a `{date, time}` tuple. """ def dump(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}) do {:ok, {{year, month, day}, {hour, min, sec, usec}}} end def dump(_), do: :error @doc """ Converts a `{date, time}` tuple into an `Ecto.DateTime`. """ def load({{_, _, _}, {_, _, _, _}} = datetime) do {:ok, erl_load(datetime)} end def load({{_, _, _}, {_, _, _}} = datetime) do {:ok, from_erl(datetime)} end def load(_), do: :error @doc """ Converts `Ecto.DateTime` into an `Ecto.Date`. """ def to_date(%Ecto.DateTime{year: year, month: month, day: day}) do %Ecto.Date{year: year, month: month, day: day} end @doc """ Converts `Ecto.DateTime` into an `Ecto.Time`. """ def to_time(%Ecto.DateTime{hour: hour, min: min, sec: sec, usec: usec}) do %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec} end @doc """ Converts the given `Ecto.Date` into `Ecto.DateTime` with the time being 00:00:00. """ def from_date(%Ecto.Date{year: year, month: month, day: day}) do %Ecto.DateTime{year: year, month: month, day: day, hour: 0, min: 0, sec: 0, usec: 0} end @doc """ Converts the given `Ecto.Date` and `Ecto.Time` into `Ecto.DateTime`. """ def from_date_and_time(%Ecto.Date{year: year, month: month, day: day}, %Ecto.Time{hour: hour, min: min, sec: sec, usec: usec}) do %Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec} end @doc """ Converts `Ecto.DateTime` to its string representation. """ def to_string(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}) do str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> " " <> zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2) if is_nil(usec) or usec == 0 do str else str <> "." <> zero_pad(usec, 6) end end @doc """ Converts `Ecto.DateTime` to its ISO 8601 representation without timezone specification. """ def to_iso8601(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec}) do str = zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2) <> "T" <> zero_pad(hour, 2) <> ":" <> zero_pad(min, 2) <> ":" <> zero_pad(sec, 2) if is_nil(usec) or usec == 0 do str else str <> "." <> zero_pad(usec, 6) end end @doc """ Returns an `Ecto.DateTime` in UTC. `precision` can be `:sec` or `:usec`. """ def utc(precision \\ :sec) do erl_load(autogenerate(precision)) end @doc """ Returns an Erlang datetime tuple from an `Ecto.DateTime`. """ def to_erl(%Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec}) do {{year, month, day}, {hour, min, sec}} end @doc """ Returns an `Ecto.DateTime` from an Erlang datetime tuple. """ def from_erl({{year, month, day}, {hour, min, sec}}) do %Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec} end # Callback invoked by autogenerate in schema. @doc false def autogenerate(precision \\ :sec) def autogenerate(:sec) do {date, {h, m, s}} = :erlang.universaltime {date, {h, m, s, 0}} end def autogenerate(:usec) do timestamp = {_, _, usec} = :os.timestamp {date, {h, m, s}} =:calendar.now_to_datetime(timestamp) {date, {h, m, s, usec}} end defp erl_load({{year, month, day}, {hour, min, sec, usec}}) do %Ecto.DateTime{year: year, month: month, day: day, hour: hour, min: min, sec: sec, usec: usec} end end defimpl String.Chars, for: [Ecto.DateTime, Ecto.Date, Ecto.Time] do def to_string(dt) do @for.to_string(dt) end end defimpl Inspect, for: [Ecto.DateTime, Ecto.Date, Ecto.Time] do @inspected inspect(@for) def inspect(dt, _opts) do "#" <> @inspected <> "<" <> @for.to_string(dt) <> ">" end end
28.469799
114
0.590229