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
e826e1be7963deb31b6d2a9d977ed0d23855ab7a
14,465
exs
Elixir
test/guardian_test.exs
gestsol/guardian
ee173c7ff0343d77cf10c559bd11ac2c88804ad8
[ "MIT" ]
null
null
null
test/guardian_test.exs
gestsol/guardian
ee173c7ff0343d77cf10c559bd11ac2c88804ad8
[ "MIT" ]
null
null
null
test/guardian_test.exs
gestsol/guardian
ee173c7ff0343d77cf10c559bd11ac2c88804ad8
[ "MIT" ]
null
null
null
defmodule GuardianTest do @moduledoc false import Guardian.Support.Utils, only: [gather_function_calls: 0] use ExUnit.Case, async: true setup do {:ok, %{impl: GuardianTest.Impl}} end defmodule Impl do @moduledoc false use Guardian, otp_app: :guardian, token_module: Guardian.Support.TokenModule import Guardian.Support.Utils, only: [ send_function_call: 1 ] def subject_for_token(%{id: id} = r, claims) do send_function_call({__MODULE__, :subject_for_token, [r, claims]}) {:ok, id} end def subject_for_token(%{"id" => id} = r, claims) do send_function_call({__MODULE__, :subject_for_token, [r, claims]}) {:ok, id} end def resource_from_claims(%{"sub" => id} = claims) do send_function_call({__MODULE__, :subject_for_token, [claims]}) {:ok, %{id: id}} end def build_claims(claims, resource, options) do send_function_call({__MODULE__, :build_claims, [claims, resource, options]}) if Keyword.get(options, :fail_build_claims) do {:error, Keyword.get(options, :fail_build_claims)} else {:ok, claims} end end def after_encode_and_sign(resource, claims, token, options) do send_function_call({__MODULE__, :after_encode_and_sign, [resource, claims, token, options]}) if Keyword.get(options, :fail_after_encode_and_sign) do {:error, Keyword.get(options, :fail_after_encode_and_sign)} else {:ok, token} end end def after_sign_in(conn, location) do send_function_call({__MODULE__, :after_sign_in, [:conn, location]}) conn end def before_sign_out(conn, location) do send_function_call({__MODULE__, :before_sign_out, [:conn, location]}) conn end def verify_claims(claims, options) do send_function_call({__MODULE__, :verify_claims, [claims, options]}) if Keyword.get(options, :fail_mod_verify_claims) do {:error, Keyword.get(options, :fail_mod_verify_claims)} else {:ok, claims} end end def on_verify(claims, token, options) do send_function_call({__MODULE__, :on_verify, [claims, token, options]}) if Keyword.get(options, :fail_on_verify) do {:error, Keyword.get(options, :fail_on_verify)} else {:ok, claims} end end def on_revoke(claims, token, options) do send_function_call({__MODULE__, :on_revoke, [claims, token, options]}) if Keyword.get(options, :fail_on_revoke) do {:error, Keyword.get(options, :fail_on_revoke)} else {:ok, claims} end end def on_refresh(old_stuff, new_stuff, options) do send_function_call({__MODULE__, :on_refresh, [old_stuff, new_stuff, options]}) if Keyword.get(options, :fail_on_refresh) do {:error, Keyword.get(options, :fail_on_refresh)} else {:ok, old_stuff, new_stuff} end end def on_exchange(old_stuff, new_stuff, options) do send_function_call({__MODULE__, :on_exchange, [old_stuff, new_stuff, options]}) if Keyword.get(options, :fail_on_exchange) do {:error, Keyword.get(options, :fail_on_exchange)} else {:ok, old_stuff, new_stuff} end end end describe "encode_and_sign" do @resource %{id: "bobby"} test "the impl has access to it's config", ctx do assert ctx.impl.config(:token_module) == Guardian.Support.TokenModule end test "encode_and_sign with only a resource", ctx do assert {:ok, token, full_claims} = Guardian.encode_and_sign(ctx.impl, @resource, %{}, []) assert full_claims == %{"sub" => "bobby", "typ" => "access"} expected = [ {ctx.impl, :subject_for_token, [%{id: "bobby"}, %{}]}, {Guardian.Support.TokenModule, :build_claims, [ctx.impl, @resource, "bobby", %{}, []]}, {ctx.impl, :build_claims, [full_claims, @resource, []]}, {Guardian.Support.TokenModule, :create_token, [ctx.impl, full_claims, []]}, {ctx.impl, :after_encode_and_sign, [@resource, full_claims, token, []]} ] assert gather_function_calls() == expected end test "with custom claims", ctx do claims = %{"some" => "claim"} assert {:ok, token, full_claims} = Guardian.encode_and_sign(ctx.impl, @resource, claims, []) assert full_claims == %{"sub" => "bobby", "some" => "claim", "typ" => "access"} expected = [ {ctx.impl, :subject_for_token, [@resource, claims]}, {Guardian.Support.TokenModule, :build_claims, [ctx.impl, @resource, "bobby", claims, []]}, {ctx.impl, :build_claims, [full_claims, @resource, []]}, {Guardian.Support.TokenModule, :create_token, [ctx.impl, full_claims, []]}, {ctx.impl, :after_encode_and_sign, [@resource, full_claims, token, []]} ] assert gather_function_calls() == expected end test "encode_and_sign with options", ctx do claims = %{"some" => "claim"} options = [some: "option"] assert {:ok, token, full_claims} = Guardian.encode_and_sign(ctx.impl, @resource, claims, options) assert full_claims == %{"sub" => "bobby", "some" => "claim", "typ" => "access"} expected = [ {ctx.impl, :subject_for_token, [@resource, claims]}, {Guardian.Support.TokenModule, :build_claims, [ctx.impl, @resource, "bobby", claims, options]}, {ctx.impl, :build_claims, [full_claims, @resource, options]}, {Guardian.Support.TokenModule, :create_token, [ctx.impl, full_claims, options]}, {ctx.impl, :after_encode_and_sign, [@resource, full_claims, token, options]} ] assert gather_function_calls() == expected end test "encode_and_sign when build_claims fails", ctx do assert {:error, :bad_things} = Guardian.encode_and_sign(ctx.impl, @resource, %{}, fail_build_claims: :bad_things) end test "encode_and_sign when after_encode_and_sign fails", ctx do assert {:error, :bad_things} = Guardian.encode_and_sign( ctx.impl, @resource, %{}, fail_after_encode_and_sign: :bad_things ) end test "encode_and_sign when create_token fails in the token module", ctx do assert {:error, :bad_things} = Guardian.encode_and_sign(ctx.impl, @resource, %{}, fail_create_token: :bad_things) end end describe "decode_and_verify" do setup %{impl: impl} do claims = %{"sub" => "freddy", "some" => "other_claim"} {:ok, token, claims} = Guardian.encode_and_sign(impl, @resource, claims) gather_function_calls() {:ok, token: token, claims: claims} end test "simple decode", ctx do claims = ctx.claims assert {:ok, ^claims} = Guardian.decode_and_verify(ctx.impl, ctx.token, %{}, []) expected = [ {Guardian.Support.TokenModule, :decode_token, [ctx.impl, ctx.token, []]}, {Guardian.Support.TokenModule, :verify_claims, [ctx.impl, claims, []]}, {ctx.impl, :verify_claims, [claims, []]}, {GuardianTest.Impl, :on_verify, [claims, ctx.token, []]} ] assert gather_function_calls() == expected end test "verifying specific claims", ctx do claims = ctx.claims assert {:ok, ^claims} = Guardian.decode_and_verify(ctx.impl, ctx.token, %{some: "other_claim"}) end test "a failing claim check", ctx do assert {:error, "not_a"} = Guardian.decode_and_verify(ctx.impl, ctx.token, %{not_a: "thing"}) end test "failure on decoding", ctx do assert {:error, :decode_failure} = Guardian.decode_and_verify( ctx.impl, ctx.token, %{}, fail_decode_token: :decode_failure ) end test "fails verifying within the token module", ctx do assert {:error, :verify_failure} = Guardian.decode_and_verify( ctx.impl, ctx.token, %{}, fail_verify_claims: :verify_failure ) end test "fails verifying within the module", ctx do assert {:error, :verify_failure} = Guardian.decode_and_verify( ctx.impl, ctx.token, %{}, fail_mod_verify_claims: :verify_failure ) end test "fails on verify", ctx do assert {:error, :on_verify_failure} = Guardian.decode_and_verify( ctx.impl, ctx.token, %{}, fail_on_verify: :on_verify_failure ) end end describe "resource_from_token" do setup %{impl: impl} do claims = %{"sub" => "freddy", "some" => "other_claim"} {:ok, token, claims} = Guardian.encode_and_sign(impl, @resource, claims) gather_function_calls() {:ok, token: token, claims: claims} end test "it finds the resource", ctx do resource = @resource claims = ctx.claims assert {:ok, ^resource, ^claims} = Guardian.resource_from_token(ctx.impl, ctx.token, %{}, []) end test "it returns an error when token can't be decoded", ctx do invalid_token = -1 assert {:error, :invalid_token} = Guardian.resource_from_token(ctx.impl, invalid_token, %{}, []) end end describe "revoke" do setup %{impl: impl} do claims = %{"sub" => "freddy", "some" => "other_claim"} {:ok, token, claims} = Guardian.encode_and_sign(impl, @resource, claims) gather_function_calls() {:ok, token: token, claims: claims} end test "it calls all the right things", ctx do claims = ctx.claims assert {:ok, ^claims} = Guardian.revoke(ctx.impl, ctx.token, []) expected = [ {Guardian.Support.TokenModule, :revoke, [ctx.impl, claims, ctx.token, []]}, {GuardianTest.Impl, :on_revoke, [claims, ctx.token, []]} ] assert gather_function_calls() == expected end test "it fails before going to the impl if the token module fails", ctx do assert {:error, :fails} = Guardian.revoke(ctx.impl, ctx.token, fail_revoke: :fails) expected = [ {Guardian.Support.TokenModule, :revoke, [ctx.impl, ctx.claims, ctx.token, [fail_revoke: :fails]]} ] assert gather_function_calls() == expected end end describe "refresh" do setup %{impl: impl} do claims = %{"sub" => "freddy", "some" => "other_claim"} {:ok, token, claims} = Guardian.encode_and_sign(impl, @resource, claims) gather_function_calls() {:ok, token: token, claims: claims} end test "it calls all the right things", ctx do claims = ctx.claims token = ctx.token assert {:ok, {^token, ^claims}, {new_t, new_c}} = Guardian.refresh(ctx.impl, ctx.token, []) expected = [ {Guardian.Support.TokenModule, :decode_token, [ctx.impl, ctx.token, []]}, {Guardian.Support.TokenModule, :verify_claims, [ctx.impl, ctx.claims, []]}, {ctx.impl, :verify_claims, [ctx.claims, []]}, {ctx.impl, :on_verify, [ctx.claims, ctx.token, []]}, {Guardian.Support.TokenModule, :refresh, [ctx.impl, ctx.token, []]}, {Guardian.Support.TokenModule, :decode_token, [ctx.impl, ctx.token, []]}, {ctx.impl, :on_refresh, [{ctx.token, ctx.claims}, {new_t, new_c}, []]} ] assert gather_function_calls() == expected end test "it fails before going to the impl if the token module fails", ctx do assert {:error, :fails} = Guardian.refresh(ctx.impl, ctx.token, fail_refresh: :fails) expected = [ {Guardian.Support.TokenModule, :decode_token, [ctx.impl, ctx.token, [fail_refresh: :fails]]}, {Guardian.Support.TokenModule, :verify_claims, [ctx.impl, ctx.claims, [fail_refresh: :fails]]}, {ctx.impl, :verify_claims, [ctx.claims, [fail_refresh: :fails]]}, {ctx.impl, :on_verify, [ctx.claims, ctx.token, [fail_refresh: :fails]]}, {Guardian.Support.TokenModule, :refresh, [ctx.impl, ctx.token, [fail_refresh: :fails]]} ] assert gather_function_calls() == expected end end describe "exchange" do setup %{impl: impl} do claims = %{"sub" => "freddy", "some" => "other_claim"} {:ok, token, claims} = Guardian.encode_and_sign(impl, @resource, claims) gather_function_calls() {:ok, token: token, claims: claims} end test "it calls all the right things", ctx do claims = ctx.claims token = ctx.token assert {:ok, {^token, ^claims}, {new_t, new_c}} = Guardian.exchange(ctx.impl, token, claims["typ"], "refresh", []) expected = [ {Guardian.Support.TokenModule, :decode_token, [ctx.impl, ctx.token, []]}, {Guardian.Support.TokenModule, :verify_claims, [ctx.impl, ctx.claims, []]}, {ctx.impl, :verify_claims, [ctx.claims, []]}, {ctx.impl, :on_verify, [ctx.claims, ctx.token, []]}, {Guardian.Support.TokenModule, :exchange, [ctx.impl, ctx.token, "access", "refresh", []]}, {Guardian.Support.TokenModule, :decode_token, [ctx.impl, ctx.token, []]}, {GuardianTest.Impl, :on_exchange, [{ctx.token, ctx.claims}, {new_t, new_c}, []]} ] assert gather_function_calls() == expected end test "it fails before going to the impl if the token module fails", ctx do claims = ctx.claims token = ctx.token assert {:error, :fails} = Guardian.exchange( ctx.impl, ctx.token, claims["typ"], "refresh", fail_exchange: :fails ) expected = [ {Guardian.Support.TokenModule, :decode_token, [ctx.impl, token, [fail_exchange: :fails]]}, {Guardian.Support.TokenModule, :verify_claims, [ctx.impl, claims, [fail_exchange: :fails]]}, {ctx.impl, :verify_claims, [claims, [fail_exchange: :fails]]}, {ctx.impl, :on_verify, [claims, token, [fail_exchange: :fails]]}, {Guardian.Support.TokenModule, :exchange, [ctx.impl, token, "access", "refresh", [fail_exchange: :fails]]} ] assert gather_function_calls() == expected end end end
33.717949
98
0.602351
e826ff935c71857fa7a24a12c1c0de3d02ff6e8f
1,870
ex
Elixir
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_intent_message_suggestions.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
1
2019-01-03T22:30:36.000Z
2019-01-03T22:30:36.000Z
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_intent_message_suggestions.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_intent_message_suggestions.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessageSuggestions do @moduledoc """ The collection of suggestions. ## Attributes - suggestions ([GoogleCloudDialogflowV2IntentMessageSuggestion]): Required. The list of suggested replies. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :suggestions => list(GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessageSuggestion.t()) } field( :suggestions, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessageSuggestion, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessageSuggestions do def decode(value, options) do GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessageSuggestions.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2IntentMessageSuggestions do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.241379
129
0.762032
e82710e81f6c87f2f2d544cae9b42c18df0a9b34
875
ex
Elixir
lib/ex_diet_web/graphql/resolvers/accounts.ex
mugimaru/ex_diet
9602c07af27255decbb32fd7ae0c12b3ffe662a3
[ "Apache-2.0" ]
2
2020-06-25T11:51:46.000Z
2020-09-30T14:00:40.000Z
lib/ex_diet_web/graphql/resolvers/accounts.ex
mugimaru/ex_diet
9602c07af27255decbb32fd7ae0c12b3ffe662a3
[ "Apache-2.0" ]
null
null
null
lib/ex_diet_web/graphql/resolvers/accounts.ex
mugimaru/ex_diet
9602c07af27255decbb32fd7ae0c12b3ffe662a3
[ "Apache-2.0" ]
1
2020-01-29T08:43:07.000Z
2020-01-29T08:43:07.000Z
defmodule ExDietWeb.GraphQL.Resolvers.Accounts do @moduledoc false require Logger alias ExDiet.Accounts alias ExDiet.Accounts.{User, Authentication} def login(_, %{input: %{email: email, password: password}}, _) do with {:ok, user} <- Accounts.login_with_password(email, password), {:ok, token, _} <- Authentication.encode_and_sign(user) do {:ok, %{user: user, token: token}} else error -> Logger.debug(fn -> "Unable to login user #{inspect(error)}" end) {:error, :invalid_credentials} end end def logout(_, _, %{context: %{user: %User{} = user}}) do Accounts.logout(user) end def create_user(_, %{input: attrs}, _) do with {:ok, user} <- Accounts.create_user(attrs), {:ok, token, _} <- Authentication.encode_and_sign(user) do {:ok, %{user: user, token: token}} end end end
28.225806
72
0.633143
e8272a310b83900c4e9bc6680568dbde69433da3
1,674
ex
Elixir
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/tiers_list_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/tiers_list_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/tiers_list_response.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the elixir code generator program. # Do not edit the class manually. defmodule GoogleApi.SQLAdmin.V1beta4.Model.TiersListResponse do @moduledoc """ Tiers list response. ## Attributes * `items` (*type:* `list(GoogleApi.SQLAdmin.V1beta4.Model.Tier.t)`, *default:* `nil`) - List of tiers. * `kind` (*type:* `String.t`, *default:* `sql#tiersList`) - This is always sql#tiersList. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :items => list(GoogleApi.SQLAdmin.V1beta4.Model.Tier.t()), :kind => String.t() } field(:items, as: GoogleApi.SQLAdmin.V1beta4.Model.Tier, type: :list) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.TiersListResponse do def decode(value, options) do GoogleApi.SQLAdmin.V1beta4.Model.TiersListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.TiersListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.48
106
0.727599
e8273db09169ba3395ab75c446996f4a5c8c7890
463
ex
Elixir
lib/models/suggested_action.ex
Mohammad-Haseeb/ex_microsoftbot
72c417ce1e6dd42cf982bf856f3b402b67cf820e
[ "MIT" ]
35
2016-05-11T02:34:27.000Z
2021-04-29T07:34:11.000Z
lib/models/suggested_action.ex
Mohammad-Haseeb/ex_microsoftbot
72c417ce1e6dd42cf982bf856f3b402b67cf820e
[ "MIT" ]
27
2016-07-10T18:32:25.000Z
2021-09-29T07:00:22.000Z
lib/models/suggested_action.ex
Mohammad-Haseeb/ex_microsoftbot
72c417ce1e6dd42cf982bf856f3b402b67cf820e
[ "MIT" ]
23
2016-05-10T18:53:13.000Z
2021-06-25T22:04:21.000Z
defmodule ExMicrosoftBot.Models.SuggestedAction do @moduledoc """ Microsoft bot suggested action structure """ @derive [Poison.Encoder] defstruct [:actions, :to] @type t :: %ExMicrosoftBot.Models.SuggestedAction{ actions: [ExMicrosoftBot.Models.CardAction.t], to: String.t, } @doc false def decoding_map() do %ExMicrosoftBot.Models.SuggestedAction{ actions: [ExMicrosoftBot.Models.CardAction.decoding_map()] } end end
22.047619
64
0.712743
e82747425e386be8ec469f6201b0edf27ec1e098
878
ex
Elixir
lib/functor.ex
rob-brown/MonadEx
a8b15e3207c0efa53749c4574496da70a6ca8f9d
[ "MIT" ]
325
2015-03-03T01:44:05.000Z
2022-03-25T20:29:58.000Z
lib/functor.ex
rob-brown/MonadEx
a8b15e3207c0efa53749c4574496da70a6ca8f9d
[ "MIT" ]
11
2015-05-29T13:33:20.000Z
2021-05-11T13:48:14.000Z
lib/functor.ex
rob-brown/MonadEx
a8b15e3207c0efa53749c4574496da70a6ca8f9d
[ "MIT" ]
17
2015-04-18T09:46:50.000Z
2019-11-12T21:28:21.000Z
defprotocol Functor do @moduledoc """ > Functors are mappings or homomorphisms between categories –[Wikipedia](https://en.wikipedia.org/wiki/Functor) Functors always take one parameter. They also preserve identity and composition (see `Functor.Law`). """ @fallback_to_any true @doc """ Takes a function and a functor and returns a functor. In Haskell types: fmap :: (a -> b) -> f a -> f b """ @spec fmap(t, (term -> term)) :: t def fmap(value, fun) end defimpl Functor, for: List do def fmap(list, fun) when is_function(fun, 1) do list |> Enum.map(fun) end end defimpl Functor, for: Function do def fmap(lhs_fun, rhs_fun) do &(&1 |> lhs_fun.() |> rhs_fun.()) end end defimpl Functor, for: Any do def fmap(nil, fun) when is_function(fun, 1), do: nil def fmap(value, fun) when is_function(fun, 1) do fun.(value) end end
21.95
69
0.664009
e8275a510163f88db404f2eb3e3230f9c6601d5d
1,456
exs
Elixir
test/groupher_server_web/query/cms/community_meta_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
240
2018-11-06T09:36:54.000Z
2022-02-20T07:12:36.000Z
test/groupher_server_web/query/cms/community_meta_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
363
2018-07-11T03:38:14.000Z
2021-12-14T01:42:40.000Z
test/groupher_server_web/query/cms/community_meta_test.exs
coderplanets/coderplanets_server
3663e56340d6d050e974c91f7e499d8424fc25e9
[ "Apache-2.0" ]
22
2019-01-27T11:47:56.000Z
2021-02-28T13:17:52.000Z
defmodule GroupherServer.Test.Query.CMS.CommunityMeta do @moduledoc false use GroupherServer.TestTools # alias GroupherServer.Accounts.Model.User alias GroupherServer.CMS setup do guest_conn = simu_conn(:guest) {:ok, user} = db_insert(:user) community_attrs = mock_attrs(:community) |> Map.merge(%{user_id: user.id}) {:ok, ~m(guest_conn community_attrs user)a} end describe "[community meta]" do @query """ query($id: ID) { community(id: $id) { id title articlesCount meta { postsCount jobsCount reposCount } } } """ test "community have valid [thread]s_count in meta", ~m(guest_conn community_attrs user)a do {:ok, community} = CMS.create_community(community_attrs) {:ok, _post} = CMS.create_article(community, :post, mock_attrs(:post), user) {:ok, _post} = CMS.create_article(community, :post, mock_attrs(:post), user) {:ok, _post} = CMS.create_article(community, :job, mock_attrs(:job), user) {:ok, _post} = CMS.create_article(community, :repo, mock_attrs(:repo), user) variables = %{id: community.id} results = guest_conn |> query_result(@query, variables, "community") meta = results["meta"] assert results["articlesCount"] == 4 assert meta["postsCount"] == 2 assert meta["jobsCount"] == 1 assert meta["reposCount"] == 1 end end end
28.54902
96
0.629121
e82792667422a85c0dede14a212b45ed3407eecd
2,344
ex
Elixir
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/app_version.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/app_version.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/android_enterprise/lib/google_api/android_enterprise/v1/model/app_version.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.AndroidEnterprise.V1.Model.AppVersion do @moduledoc """ This represents a single version of the app. ## Attributes - isProduction (boolean()): True if this version is a production APK. Defaults to: `null`. - track (String.t): Deprecated, use trackId instead. Defaults to: `null`. - trackId ([String.t]): Track ids that the app version is published in. Replaces the track field (deprecated), but doesn&#39;t include the production track (see isProduction instead). Defaults to: `null`. - versionCode (integer()): Unique increasing identifier for the app version. Defaults to: `null`. - versionString (String.t): The string used in the Play store by the app developer to identify the version. The string is not necessarily unique or localized (for example, the string could be \&quot;1.4\&quot;). Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :isProduction => any(), :track => any(), :trackId => list(any()), :versionCode => any(), :versionString => any() } field(:isProduction) field(:track) field(:trackId, type: :list) field(:versionCode) field(:versionString) end defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.AppVersion do def decode(value, options) do GoogleApi.AndroidEnterprise.V1.Model.AppVersion.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.AppVersion do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.066667
234
0.723976
e827ae3c5deb88b56ff6e4133debbb75714cbbd0
937
ex
Elixir
backend/test/support/channel_case.ex
danesjenovdan/kjer.si
185410ede2d42892e4d91c000099283254c5dc7a
[ "Unlicense" ]
2
2019-11-02T21:28:34.000Z
2019-11-28T18:01:08.000Z
backend/test/support/channel_case.ex
danesjenovdan/kjer.si
185410ede2d42892e4d91c000099283254c5dc7a
[ "Unlicense" ]
17
2019-11-29T16:23:38.000Z
2022-02-14T05:11:41.000Z
backend/test/support/channel_case.ex
danesjenovdan/kjer.si
185410ede2d42892e4d91c000099283254c5dc7a
[ "Unlicense" ]
null
null
null
defmodule KjerSiWeb.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` 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, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with channels import Phoenix.ChannelTest # The default endpoint for testing @endpoint KjerSiWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(KjerSi.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(KjerSi.Repo, {:shared, self()}) end :ok end end
24.657895
68
0.715048
e827f5d24ea39db4b828a8be13f4d412645af638
3,749
ex
Elixir
lib/live_sup_web/live/widgets/team_members_live.ex
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
null
null
null
lib/live_sup_web/live/widgets/team_members_live.ex
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
3
2022-02-23T15:51:48.000Z
2022-03-14T22:52:43.000Z
lib/live_sup_web/live/widgets/team_members_live.ex
livesup-dev/livesup
eaf9ffc78d3043bd9e3408f0f4df26ed16eb8446
[ "Apache-2.0", "MIT" ]
null
null
null
defmodule LiveSupWeb.Live.Widgets.TeamMembersLive do use LiveSupWeb.Live.Widgets.WidgetLive @impl true def render_widget(assigns) do ~H""" <.live_component module={SmartRenderComponent} id={@widget_data.id} let={widget_data} widget_data={@widget_data}> <!-- Team Members --> <.live_component module={WidgetHeaderComponent} id={"#{widget_data.id}-header"} widget_data={widget_data} /> <!-- Widget Content --> <div class="items-center p-2 bg-white rounded-md dark:bg-darker min-h-[132px]"> <%= if Enum.any?(widget_data.data) do %> <div class="divide-y divide-gray-100 dark:divide-gray-500"> <%= for user <- widget_data.data do %> <div class="flex py-4 first:pt-0 gap-3 flex-wrap dark:divide-blue-300"> <div class="flex-none relative pt-1"> <img src={user[:avatar]} class="w-10 h-10 rounded-full transition-opacity duration-200 "/> <%= if user[:night] == true do %> <i class="absolute bottom-0 right-0 rounded-full bg-slate-700 p-[1px]"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" /> </svg></i> <% else %> <i class="absolute bottom-0 right-0 rounded-full bg-slate-700 p-[1px]"><svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="rgb(252, 211, 77)"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" /> </svg></i> <% end %> </div> <div class="grow"> <p> <strong class="block"><%= user[:full_name] %></strong> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 inline-block" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"> <path stroke-linecap="round" stroke-linejoin="round" d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> <span class="text-sm align-middle inline-block"> <%= user[:address] %> </span> | <span class="text-sm"> <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 inline-block" fill="none" viewBox="0 0 24 24" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /> </svg> <date class=" align-middle inline-block"><%= user[:now_str] %></date> </span> </p> </div> </div> <% end %> </div> <% else %> <p class="text-center m-2">This team has no members.</p> <% end %> </div> <!-- /Widget Content --> <!-- /Team Members --> <.live_component module={WidgetFooterComponent} id={"#{widget_data.id}-footer"} widget_data={widget_data} /> </.live_component> """ end end
62.483333
280
0.529208
e8281a1ad556b19f5dc76955b75dcf94025cd45f
98
exs
Elixir
config/test.exs
Ispirata/cfexexl
98dc50b1cfe5a682b051b38b83cebc644bc08488
[ "Apache-2.0" ]
5
2017-09-25T18:09:08.000Z
2017-09-26T07:09:10.000Z
config/test.exs
Ispirata/cfexexl
98dc50b1cfe5a682b051b38b83cebc644bc08488
[ "Apache-2.0" ]
11
2017-09-25T17:03:33.000Z
2021-03-12T15:13:54.000Z
config/test.exs
Ispirata/cfexexl
98dc50b1cfe5a682b051b38b83cebc644bc08488
[ "Apache-2.0" ]
3
2017-10-11T16:38:07.000Z
2021-03-12T10:54:50.000Z
use Mix.Config config :cfxxl, :test_endpoint, base_url: "http://localhost:8888", options: []
16.333333
36
0.693878
e8281a661326f17adad395c5b91c11136793a169
1,545
exs
Elixir
test/jrac_test.exs
agleb/jrac
bf140b7b899c9ad87f61512cd11223503f60998e
[ "MIT" ]
null
null
null
test/jrac_test.exs
agleb/jrac
bf140b7b899c9ad87f61512cd11223503f60998e
[ "MIT" ]
null
null
null
test/jrac_test.exs
agleb/jrac
bf140b7b899c9ad87f61512cd11223503f60998e
[ "MIT" ]
null
null
null
defmodule JracTest do use ExUnit.Case use Jrac.Behaviour, app_name: :jrac, base_url_key_name: :base_url_key, headers: [{"Accept", "application/json"}] test "build_url" do assert "https://reqres.in/api/test" == JracTest.build_url("test") end test "build_url/1 guard" do assert nil == JracTest.build_url(1) end test "build_url/2 with map" do assert "https://reqres.in/api/test?t=1" == JracTest.build_url("test", %{"t" => 1}) end test "build_url/2 guard" do assert nil == JracTest.build_url(1, 1) assert nil == JracTest.build_url(1, %{"t" => 1}) end test "do_get_single" do assert {:ok, %{ "data" => _data }} = JracTest.do_get_single("users", "4") end test "do_get_page" do assert {:ok, %{ "data" => _data }} = JracTest.do_get_page("users", %{"page" => "2"}) end test "do_post" do params = %{ "name" => "morpheus", "job" => "leader" } assert {:ok, %{"createdAt" => _, "id" => _}} = JracTest.do_post("users", params) end test "do_put" do params = %{ "name" => "morpheus", "job" => "leader" } assert {:ok, %{"updatedAt" => _}} = JracTest.do_put("users", "2", params) end test "do_patch" do params = %{ "name" => "morpheus", "job" => "leader" } assert {:ok, %{"updatedAt" => _}} = JracTest.do_patch("users", "2", params) end test "do_delete" do assert {:ok} = JracTest.do_delete("users", "4") end end
21.760563
86
0.544337
e8285f089cad32379beca567be6481da317951f4
8,592
ex
Elixir
backend/lib/backend/game.ex
ugbots/ggj2022
1c7b9f6694268951f93a11fde91fa9573c179c26
[ "MIT" ]
null
null
null
backend/lib/backend/game.ex
ugbots/ggj2022
1c7b9f6694268951f93a11fde91fa9573c179c26
[ "MIT" ]
null
null
null
backend/lib/backend/game.ex
ugbots/ggj2022
1c7b9f6694268951f93a11fde91fa9573c179c26
[ "MIT" ]
null
null
null
defmodule Backend.Game do import Ecto.Query, warn: false alias Backend.Accounts alias Backend.Accounts.User alias Backend.Logs alias Backend.Items alias Backend.Repo alias Backend.Game.Inventory ## ## Accessors ## @doc """ Gets the name of all items held by the given user. """ @spec inventory_for_user(%User{}) :: %Inventory{} def inventory_for_user(user) do Repo.one(Ecto.assoc(user, :inventory)) end @doc """ Gets the name of all items held by the given user. """ @spec all_item_atoms_for_user(%User{}) :: [String.t()] def all_item_atoms_for_user(user) do inventory_for_user(user).items |> Map.keys() |> Enum.map(fn name -> String.to_atom(name) end) end @spec victory_points_for_user(%User{}) :: integer() def victory_points_for_user(user) do inventory_for_user(user).items |> Enum.reduce(0, fn {k, amount}, acc -> item = Items.get_item(String.to_atom(k)) acc + Map.get(item, :victory_points, 0) * amount end) end @spec all_weapon_atoms_for_user(%User{}) :: [atom()] def all_weapon_atoms_for_user(user) do inventory_for_user(user).items |> Enum.flat_map(fn {item_name, _} -> atom = String.to_atom(item_name) item = Items.get_item(atom) if Map.has_key?(item, :weapon) do [atom] else [] end end) end @spec create_inventory_for_user(%User{}) :: any def create_inventory_for_user(user) do %Inventory{} |> Inventory.changeset(%{ last_read: DateTime.utc_now(), items: %{ gold: 100 }, user_id: user.id }) |> Repo.insert() end @spec buy_product_for_user(%User{}, binary()) :: any def buy_product_for_user(user, product_name) do inventory = inventory_for_user(user) product = String.to_atom(product_name) requirements = Items.requirements_for_item(product) delta = Items.cost_delta_for_item(product) |> Map.put(product, 1) case adjust(inventory, requirements, delta) do :ok -> Logs.create_user_log(user, "Bought #{product_name}.") {:error, message} -> Logs.create_user_log( user, "Cannot buy #{product_name}: #{message}" ) end end def donate_to_username_from_user(user, target_username, amount_str, product_name) do amount = elem(Integer.parse(amount_str), 0) inventory = Repo.one(Ecto.assoc(user, :inventory)) delta = Map.put(%{}, String.to_atom(product_name), -amount) target_user = Accounts.get_by_username(target_username) cond do user.username == target_username -> Logs.create_user_log(user, "Cannot donate to yourself.") amount <= 0 -> Logs.create_user_log(user, "Donation amount must be positive.") (result = can_afford(inventory, %{}, delta)) != :ok -> {:error, message} = result Logs.create_user_log( user, "Cannot donate #{amount_str} #{product_name} " <> "to #{target_username}: #{message}" ) target_user == nil -> Logs.create_user_log( user, "Cannot donate #{amount_str} #{product_name} " <> "to #{target_username}: user not found." ) target_user.team != user.team -> Logs.create_user_log( user, "Cannot donate #{amount_str} #{product_name} " <> "to #{target_username}: user must be on your team." ) true -> target_inv = Repo.one(Ecto.assoc(target_user, :inventory)) target_delta = Map.put(%{}, String.to_atom(product_name), amount) adjust(target_inv, %{}, target_delta) Logs.create_user_log( target_user, "Received #{amount_str} #{product_name} from #{user.username}" ) adjust(inventory, %{}, delta) Logs.create_user_log( user, "Donated #{amount_str} #{product_name} to #{target_username}" ) end end def attack_username_from_user( user, target_username, target_product_name, amount_str, product_name ) do product = String.to_atom(product_name) target_product = String.to_atom(target_product_name) amount = elem(Integer.parse(amount_str), 0) inventory = inventory_for_user(user) user_delta = Map.put(%{}, product, -amount) target_user = Accounts.get_by_username(target_username) cond do user.username == target_username -> Logs.create_user_log(user, "Cannot attack yourself.") amount <= 0 -> Logs.create_user_log(user, "Attack size must be positive.") (result = can_afford(inventory, %{}, user_delta)) != :ok -> {:error, message} = result raise {inventory, user_delta} Logs.create_user_log( user, "Cannot attack #{target_username} " <> "with #{amount_str} #{product_name}: #{message}" ) target_user == nil -> Logs.create_user_log( user, "Cannot attack #{target_username} " <> "with #{amount_str} #{product_name}: user not found" ) target_user.team == user.team -> Logs.create_user_log( user, "Cannot attack #{target_username} " <> "with #{amount_str} #{product_name}: Cannot attack user on your team." ) true -> total_damage = amount * Items.get_item(product).weapon.damage target_resistance = Items.get_item(target_product).damage_resistance is_defending = target_user.passive_activity == "defend" items_destroyed = trunc(total_damage / target_resistance) items_destroyed = if is_defending do trunc(items_destroyed / 2) else items_destroyed end target_inv = inventory_for_user(target_user) target_delta = Map.put(%{}, target_product, -items_destroyed) adjust(target_inv, %{}, target_delta) defense_str = if is_defending, do: " You were defending.", else: "" Logs.create_user_log( target_user, "Attacked by #{user.username} with #{amount} #{product_name}!" <> defense_str <> " Lost #{items_destroyed} #{target_product_name}." ) adjust(inventory, %{}, user_delta) defense_str = if is_defending, do: " They were defending.", else: "" Logs.create_user_log( user, "Attacked #{target_username} with #{amount} #{product_name}!" <> defense_str <> " Destroyed #{items_destroyed} #{target_product_name}." ) end end @spec reconcile_inventory_for_user(%User{}) :: any() def reconcile_inventory_for_user(user) do Accounts.get_inventory(user) |> reconcile(user.passive_activity) |> Repo.update() end @spec reconcile(%Inventory{}, String.t()) :: Ecto.Changeset.t() defp reconcile(inv, activity_str) do activity = String.to_atom(activity_str) now = DateTime.utc_now() then = inv.last_read seconds_between = DateTime.diff(now, then) elapsed_seconds = trunc(seconds_between) items = case Map.get(Items.generated_items(), activity, nil) do nil -> inv.items item -> gen = item.generated old_amount = Map.get(inv.items, activity_str, 0) delta = trunc(elapsed_seconds / gen.seconds_per_item) Map.put(inv.items, activity_str, old_amount + delta) end params = %{ last_read: now, items: items } Inventory.changeset(inv, params) end defp can_afford(inv, requirements, delta) do has_requirements = Enum.all?(requirements, fn {item, amount} -> Map.get(inv.items, Atom.to_string(item), 0) >= amount end) delta_does_not_go_negative = Enum.all?(delta, fn {item, amount} -> Map.get(inv.items, Atom.to_string(item), 0) + amount >= 0 end) cond do not has_requirements -> {:error, "Missing required items"} not delta_does_not_go_negative -> {:error, "Can't afford to."} true -> :ok end end defp adjust(inv, requirements, delta) do case can_afford(inv, requirements, delta) do {:error, message} -> {:error, message} :ok -> items = Enum.reduce(delta, inv.items, fn {item, amount}, acc -> key = Atom.to_string(item) Map.put(acc, key, Map.get(acc, key, 0) + amount) end) Repo.update(Inventory.changeset(inv, %{items: items})) :ok end end end
28.078431
86
0.609055
e82860e923f13d2da245ca27c564e626c2f9ccbb
6,726
exs
Elixir
test/elixir/test/view_pagination_test.exs
frapa/couchdb
6c28960f0fe2eec06aca7d58fd73f3c7cdbe1112
[ "Apache-2.0" ]
1
2022-01-14T20:52:55.000Z
2022-01-14T20:52:55.000Z
test/elixir/test/view_pagination_test.exs
frapa/couchdb
6c28960f0fe2eec06aca7d58fd73f3c7cdbe1112
[ "Apache-2.0" ]
null
null
null
test/elixir/test/view_pagination_test.exs
frapa/couchdb
6c28960f0fe2eec06aca7d58fd73f3c7cdbe1112
[ "Apache-2.0" ]
null
null
null
defmodule ViewPaginationTest do use CouchTestCase @moduletag :view_pagination @moduletag kind: :single_node @moduledoc """ Integration tests for pagination. This is a port of the view_pagination.js test suite. """ @tag :pending # Offsets are always null on 4.x @tag :with_db test "basic view pagination", context do db_name = context[:db_name] docs = make_docs(0..99) bulk_save(db_name, docs) query_function = "function(doc) { emit(doc.integer, null); }" 0..99 |> Enum.filter(fn number -> rem(number, 10) === 0 end) |> Enum.each(fn i -> query_options = %{"startkey" => i, "startkey_docid" => i, limit: 10} result = query(db_name, query_function, nil, query_options) assert result["total_rows"] === length(docs) assert length(result["rows"]) === 10 assert result["offset"] === i Enum.each(0..9, &assert(Enum.at(result["rows"], &1)["key"] === &1 + i)) end) end @tag :pending # Offsets are always null on 4.x @tag :with_db test "aliases start_key and start_key_doc_id should work", context do db_name = context[:db_name] docs = make_docs(0..99) bulk_save(db_name, docs) query_function = "function(doc) { emit(doc.integer, null); }" 0..99 |> Enum.filter(fn number -> rem(number, 10) === 0 end) |> Enum.each(fn i -> query_options = %{"start_key" => i, "start_key_docid" => i, limit: 10} result = query(db_name, query_function, nil, query_options) assert result["total_rows"] === length(docs) assert length(result["rows"]) === 10 assert result["offset"] === i Enum.each(0..9, &assert(Enum.at(result["rows"], &1)["key"] === &1 + i)) end) end @tag :pending # Offsets are always null on 4.x @tag :with_db test "descending view pagination", context do db_name = context[:db_name] docs = make_docs(0..99) bulk_save(db_name, docs) query_function = "function(doc) { emit(doc.integer, null); }" 100..0 |> Enum.filter(fn number -> rem(number, 10) === 0 end) |> Enum.map(&(&1 - 1)) |> Enum.filter(&(&1 > 0)) |> Enum.each(fn i -> query_options = %{ "startkey" => i, "startkey_docid" => i, limit: 10, descending: true } result = query(db_name, query_function, nil, query_options) assert result["total_rows"] === length(docs) assert length(result["rows"]) === 10 assert result["offset"] === length(docs) - i - 1 Enum.each(0..9, &assert(Enum.at(result["rows"], &1)["key"] === i - &1)) end) end @tag :pending # Offsets are always null on 4.x @tag :with_db test "descending=false parameter should just be ignored", context do db_name = context[:db_name] docs = make_docs(0..99) bulk_save(db_name, docs) query_function = "function(doc) { emit(doc.integer, null); }" 0..99 |> Enum.filter(fn number -> rem(number, 10) === 0 end) |> Enum.each(fn i -> query_options = %{ "start_key" => i, "start_key_docid" => i, limit: 10, descending: false } result = query(db_name, query_function, nil, query_options) assert result["total_rows"] === length(docs) assert length(result["rows"]) === 10 assert result["offset"] === i Enum.each(0..9, &assert(Enum.at(result["rows"], &1)["key"] === &1 + i)) end) end @tag :pending # Offsets are always null on 4.x @tag :with_db test "endkey document id", context do db_name = context[:db_name] docs = make_docs(0..99) bulk_save(db_name, docs) query_function = "function(doc) { emit(null, null); }" query_options = %{ "startkey" => :null, "startkey_docid" => 1, "endkey" => :null, "endkey_docid" => 40, } result = query(db_name, query_function, nil, query_options) test_end_key_doc_id(result, docs) end @tag :pending # Offsets are always null on 4.x @tag :with_db test "endkey document id, but with end_key_doc_id alias", context do db_name = context[:db_name] docs = make_docs(0..99) bulk_save(db_name, docs) query_function = "function(doc) { emit(null, null); }" query_options = %{ "start_key" => :null, "start_key_doc_id" => 1, "end_key" => :null, "end_key_doc_id" => 40, } result = query(db_name, query_function, nil, query_options) test_end_key_doc_id(result, docs) end defp test_end_key_doc_id(query_result, docs) do assert length(query_result["rows"]) === 35 assert query_result["total_rows"] === length(docs) assert query_result["offset"] === 1 assert Enum.at(query_result["rows"], 0)["id"] === "1" assert Enum.at(query_result["rows"], 1)["id"] === "10" assert Enum.at(query_result["rows"], 2)["id"] === "11" assert Enum.at(query_result["rows"], 3)["id"] === "12" assert Enum.at(query_result["rows"], 4)["id"] === "13" assert Enum.at(query_result["rows"], 5)["id"] === "14" assert Enum.at(query_result["rows"], 6)["id"] === "15" assert Enum.at(query_result["rows"], 7)["id"] === "16" assert Enum.at(query_result["rows"], 8)["id"] === "17" assert Enum.at(query_result["rows"], 9)["id"] === "18" assert Enum.at(query_result["rows"], 10)["id"] === "19" assert Enum.at(query_result["rows"], 11)["id"] === "2" assert Enum.at(query_result["rows"], 12)["id"] === "20" assert Enum.at(query_result["rows"], 13)["id"] === "21" assert Enum.at(query_result["rows"], 14)["id"] === "22" assert Enum.at(query_result["rows"], 15)["id"] === "23" assert Enum.at(query_result["rows"], 16)["id"] === "24" assert Enum.at(query_result["rows"], 17)["id"] === "25" assert Enum.at(query_result["rows"], 18)["id"] === "26" assert Enum.at(query_result["rows"], 19)["id"] === "27" assert Enum.at(query_result["rows"], 20)["id"] === "28" assert Enum.at(query_result["rows"], 21)["id"] === "29" assert Enum.at(query_result["rows"], 22)["id"] === "3" assert Enum.at(query_result["rows"], 23)["id"] === "30" assert Enum.at(query_result["rows"], 24)["id"] === "31" assert Enum.at(query_result["rows"], 25)["id"] === "32" assert Enum.at(query_result["rows"], 26)["id"] === "33" assert Enum.at(query_result["rows"], 27)["id"] === "34" assert Enum.at(query_result["rows"], 28)["id"] === "35" assert Enum.at(query_result["rows"], 29)["id"] === "36" assert Enum.at(query_result["rows"], 30)["id"] === "37" assert Enum.at(query_result["rows"], 31)["id"] === "38" assert Enum.at(query_result["rows"], 32)["id"] === "39" assert Enum.at(query_result["rows"], 33)["id"] === "4" assert Enum.at(query_result["rows"], 34)["id"] === "40" end end
34.142132
77
0.594707
e828b078f5fcaa3825f42a2c666bad8607a60291
167
ex
Elixir
priv/templates/phx.gen.html/view.ex
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
18,092
2015-01-01T01:51:04.000Z
2022-03-31T19:37:14.000Z
priv/templates/phx.gen.html/view.ex
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,905
2015-01-01T00:22:47.000Z
2022-03-31T17:06:21.000Z
priv/templates/phx.gen.html/view.ex
faheempatel/phoenix
a83318f2a2284b7ab29b0b86cdd9d2e1f4d0a7c9
[ "MIT" ]
3,205
2015-01-03T10:58:22.000Z
2022-03-30T14:55:57.000Z
defmodule <%= inspect context.web_module %>.<%= inspect Module.concat(schema.web_namespace, schema.alias) %>View do use <%= inspect context.web_module %>, :view end
41.75
115
0.730539
e828ef57e60374d6e3977b3a5755e050ae3c4b4b
739
ex
Elixir
elixir/lib/keepa_api/model/category.ex
mindviser/keepaSDK
24627e3372bf2ca75d8a42de79d31046e4ae14c1
[ "MIT" ]
3
2019-09-18T20:18:24.000Z
2021-07-26T18:08:29.000Z
elixir/lib/keepa_api/model/category.ex
mindviser/keepaSDK
24627e3372bf2ca75d8a42de79d31046e4ae14c1
[ "MIT" ]
3
2020-05-15T21:27:09.000Z
2022-02-09T01:00:00.000Z
elixir/lib/keepa_api/model/category.ex
mindviser/keepaSDK
24627e3372bf2ca75d8a42de79d31046e4ae14c1
[ "MIT" ]
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 KeepaAPI.Model.Category do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"domainId", :"catId", :"name", :"children", :"parent", :"highestRank", :"productCount" ] @type t :: %__MODULE__{ :"domainId" => integer(), :"catId" => integer(), :"name" => String.t, :"children" => [integer()], :"parent" => integer(), :"highestRank" => integer(), :"productCount" => integer() } end defimpl Poison.Decoder, for: KeepaAPI.Model.Category do def decode(value, _options) do value end end
19.447368
91
0.603518
e8291076cf336c3f32e0d0654a778393928ebddf
24,058
ex
Elixir
clients/licensing/lib/google_api/licensing/v1/api/license_assignments.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/licensing/lib/google_api/licensing/v1/api/license_assignments.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/licensing/lib/google_api/licensing/v1/api/license_assignments.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.Licensing.V1.Api.LicenseAssignments do @moduledoc """ API calls for all endpoints tagged `LicenseAssignments`. """ alias GoogleApi.Licensing.V1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Revoke a license. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `sku_id` (*type:* `String.t`) - A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs. * `user_id` (*type:* `String.t`) - The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a userId is subject to change, do not use a userId value as a key for persistent data. This key could break if the current user's email address changes. If the userId is suspended, the license status changes. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_delete( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_delete( connection, product_id, sku_id, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:delete) |> Request.url("/{productId}/sku/{skuId}/user/{userId}", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1), "skuId" => URI.encode(sku_id, &URI.char_unreserved?/1), "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [decode: false]) end @doc """ Get a specific user's license by product SKU. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `sku_id` (*type:* `String.t`) - A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs. * `user_id` (*type:* `String.t`) - The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a userId is subject to change, do not use a userId value as a key for persistent data. This key could break if the current user's email address changes. If the userId is suspended, the license status changes. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Licensing.V1.Model.LicenseAssignment{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_get( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Licensing.V1.Model.LicenseAssignment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_get( connection, product_id, sku_id, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{productId}/sku/{skuId}/user/{userId}", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1), "skuId" => URI.encode(sku_id, &URI.char_unreserved?/1), "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Licensing.V1.Model.LicenseAssignment{}]) end @doc """ Assign a license. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `sku_id` (*type:* `String.t`) - A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Licensing.V1.Model.LicenseAssignmentInsert.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Licensing.V1.Model.LicenseAssignment{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_insert( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Licensing.V1.Model.LicenseAssignment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_insert( connection, product_id, sku_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:post) |> Request.url("/{productId}/sku/{skuId}/user", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1), "skuId" => URI.encode(sku_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Licensing.V1.Model.LicenseAssignment{}]) end @doc """ List all users assigned licenses for a specific product SKU. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `customer_id` (*type:* `String.t`) - Customer's customerId. A previous version of this API accepted the primary domain name as a value for this field. If the customer is suspended, the server returns an error. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:maxResults` (*type:* `integer()`) - The maxResults query string determines how many entries are returned on each page of a large response. This is an optional parameter. The value must be a positive number. * `:pageToken` (*type:* `String.t`) - Token to fetch the next page of data. The maxResults query string is related to the pageToken since maxResults determines how many entries are returned on each page. This is an optional query string. If not specified, the server returns the first page. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Licensing.V1.Model.LicenseAssignmentList{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_list_for_product( Tesla.Env.client(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Licensing.V1.Model.LicenseAssignmentList.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_list_for_product( connection, product_id, customer_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :maxResults => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{productId}/users", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :customerId, customer_id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Licensing.V1.Model.LicenseAssignmentList{}]) end @doc """ List all users assigned licenses for a specific product SKU. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `sku_id` (*type:* `String.t`) - A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs. * `customer_id` (*type:* `String.t`) - Customer's customerId. A previous version of this API accepted the primary domain name as a value for this field. If the customer is suspended, the server returns an error. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:maxResults` (*type:* `integer()`) - The maxResults query string determines how many entries are returned on each page of a large response. This is an optional parameter. The value must be a positive number. * `:pageToken` (*type:* `String.t`) - Token to fetch the next page of data. The maxResults query string is related to the pageToken since maxResults determines how many entries are returned on each page. This is an optional query string. If not specified, the server returns the first page. * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Licensing.V1.Model.LicenseAssignmentList{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_list_for_product_and_sku( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Licensing.V1.Model.LicenseAssignmentList.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_list_for_product_and_sku( connection, product_id, sku_id, customer_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :maxResults => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/{productId}/sku/{skuId}/users", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1), "skuId" => URI.encode(sku_id, &URI.char_unreserved?/1) }) |> Request.add_param(:query, :customerId, customer_id) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Licensing.V1.Model.LicenseAssignmentList{}]) end @doc """ Reassign a user's product SKU with a different SKU in the same product. This method supports patch semantics. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `sku_id` (*type:* `String.t`) - A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs. * `user_id` (*type:* `String.t`) - The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a userId is subject to change, do not use a userId value as a key for persistent data. This key could break if the current user's email address changes. If the userId is suspended, the license status changes. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Licensing.V1.Model.LicenseAssignment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Licensing.V1.Model.LicenseAssignment{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_patch( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Licensing.V1.Model.LicenseAssignment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_patch( connection, product_id, sku_id, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:patch) |> Request.url("/{productId}/sku/{skuId}/user/{userId}", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1), "skuId" => URI.encode(sku_id, &URI.char_unreserved?/1), "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Licensing.V1.Model.LicenseAssignment{}]) end @doc """ Reassign a user's product SKU with a different SKU in the same product. ## Parameters * `connection` (*type:* `GoogleApi.Licensing.V1.Connection.t`) - Connection to server * `product_id` (*type:* `String.t`) - A product's unique identifier. For more information about products in this version of the API, see Products and SKUs. * `sku_id` (*type:* `String.t`) - A product SKU's unique identifier. For more information about available SKUs in this version of the API, see Products and SKUs. * `user_id` (*type:* `String.t`) - The user's current primary email address. If the user's email address changes, use the new email address in your API requests. Since a userId is subject to change, do not use a userId value as a key for persistent data. This key could break if the current user's email address changes. If the userId is suspended, the license status changes. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:alt` (*type:* `String.t`) - Data format for the response. * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - An opaque string that represents a user for quota purposes. Must not exceed 40 characters. * `:userIp` (*type:* `String.t`) - Deprecated. Please use quotaUser instead. * `:body` (*type:* `GoogleApi.Licensing.V1.Model.LicenseAssignment.t`) - * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.Licensing.V1.Model.LicenseAssignment{}}` on success * `{:error, info}` on failure """ @spec licensing_license_assignments_update( Tesla.Env.client(), String.t(), String.t(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.Licensing.V1.Model.LicenseAssignment.t()} | {:ok, Tesla.Env.t()} | {:error, any()} def licensing_license_assignments_update( connection, product_id, sku_id, user_id, optional_params \\ [], opts \\ [] ) do optional_params_config = %{ :alt => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :userIp => :query, :body => :body } request = Request.new() |> Request.method(:put) |> Request.url("/{productId}/sku/{skuId}/user/{userId}", %{ "productId" => URI.encode(product_id, &URI.char_unreserved?/1), "skuId" => URI.encode(sku_id, &URI.char_unreserved?/1), "userId" => URI.encode(user_id, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Licensing.V1.Model.LicenseAssignment{}]) end end
45.912214
298
0.635256
e82912a24470b6241a2f2f78d51776624e5dd54d
1,479
ex
Elixir
lib/xadmin/render.ex
ntsai/xadmin
82d8be63e69483ff66472481e66f9870face355b
[ "MIT" ]
5
2016-08-30T01:23:50.000Z
2021-09-22T14:39:00.000Z
lib/xadmin/render.ex
ntsai/xadmin
82d8be63e69483ff66472481e66f9870face355b
[ "MIT" ]
null
null
null
lib/xadmin/render.ex
ntsai/xadmin
82d8be63e69483ff66472481e66f9870face355b
[ "MIT" ]
1
2021-12-10T11:10:55.000Z
2021-12-10T11:10:55.000Z
alias XAdmin.Utils defprotocol XAdmin.Render do # @fallback_to_any true def to_string(data) end defimpl XAdmin.Render, for: Atom do def to_string(nil), do: "" def to_string(atom), do: "#{atom}" end defimpl XAdmin.Render, for: BitString do def to_string(data), do: data end defimpl XAdmin.Render, for: Integer do def to_string(data), do: Integer.to_string(data) end defimpl XAdmin.Render, for: Float do def to_string(data), do: Float.to_string(data) end defimpl XAdmin.Render, for: Ecto.Time do def to_string(dt) do dt |> Ecto.Time.to_string |> String.replace("Z", "") end end defimpl XAdmin.Render, for: Ecto.DateTime do def to_string(dt) do dt |> Utils.to_datetime |> :calendar.universal_time_to_local_time |> Utils.format_datetime end end defimpl XAdmin.Render, for: Ecto.Date do def to_string(dt) do Ecto.Date.to_string dt end end defimpl XAdmin.Render, for: Decimal do def to_string(decimal) do Decimal.to_string decimal end end defimpl XAdmin.Render, for: Map do def to_string(map) do Poison.encode! map end end defimpl XAdmin.Render, for: List do def to_string(list) do if Enum.all?(list, &(is_integer(&1))) do str = List.to_string(list) if String.printable? str do str else Poison.encode! list end else Poison.encode! list end end end # defimpl XAdmin.Render, for: Any do # def to_string(data), do: "#{inspect data}" # end
19.207792
50
0.684922
e8292d366659610d1c5162f83f29e797547bf0d0
1,035
ex
Elixir
test/support/conn_case.ex
tajchumber/live-view-chat
d98d445b145a197eadc4381e264f3d1918f0b90f
[ "Apache-2.0" ]
50
2019-05-23T11:59:30.000Z
2022-03-11T04:12:36.000Z
test/support/conn_case.ex
tajchumber/live-view-chat
d98d445b145a197eadc4381e264f3d1918f0b90f
[ "Apache-2.0" ]
6
2019-05-18T09:53:46.000Z
2021-01-27T11:26:15.000Z
test/support/conn_case.ex
tajchumber/live-view-chat
d98d445b145a197eadc4381e264f3d1918f0b90f
[ "Apache-2.0" ]
18
2019-05-18T08:13:51.000Z
2021-11-23T13:57:33.000Z
defmodule PhatWeb.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, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias PhatWeb.Router.Helpers, as: Routes # The default endpoint for testing @endpoint PhatWeb.Endpoint end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Phat.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Phat.Repo, {:shared, self()}) end {:ok, conn: Phoenix.ConnTest.build_conn()} end end
26.538462
66
0.71401
e829335f2d1350140d40a156f3d3ce436d54f684
1,210
ex
Elixir
web/channels/user_socket.ex
bbulpett/chatroom-rtc
9992f3fc80dc685b87a152ef71d6f6b4fc245238
[ "MIT" ]
2
2017-02-16T09:44:44.000Z
2018-07-30T06:17:05.000Z
web/channels/user_socket.ex
bbulpett/chatroom-rtc
9992f3fc80dc685b87a152ef71d6f6b4fc245238
[ "MIT" ]
null
null
null
web/channels/user_socket.ex
bbulpett/chatroom-rtc
9992f3fc80dc685b87a152ef71d6f6b4fc245238
[ "MIT" ]
null
null
null
defmodule Chatroom.UserSocket do use Phoenix.Socket ## Channels # channel "room:*", Chatroom.RoomChannel channel "lobby", Chatroom.PageChannel ## Transports transport :websocket, Phoenix.Transports.WebSocket # transport :longpoll, Phoenix.Transports.LongPoll # Socket params are passed from the client and can # be used to verify and authenticate a user. After # verification, you can put default assigns into # the socket that will be set for all channels, ie # # {:ok, assign(socket, :user_id, verified_user_id)} # # To deny connection, return `:error`. # # See `Phoenix.Token` documentation for examples in # performing token verification on connect. def connect(_params, socket) do {:ok, socket} end # Socket id's are topics that allow you to identify all sockets for a given user: # # def id(socket), do: "users_socket:#{socket.assigns.user_id}" # # Would allow you to broadcast a "disconnect" event and terminate # all active sockets and channels for a given user: # # Chatroom.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{}) # # Returning `nil` makes this socket anonymous. def id(_socket), do: nil end
30.25
83
0.704132
e8294a30ff395f9a2f7840f1f154df3a393defa3
5,558
exs
Elixir
test/oli/interop/ingest_test.exs
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
45
2020-04-17T15:40:27.000Z
2022-03-25T00:13:30.000Z
test/oli/interop/ingest_test.exs
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
944
2020-02-13T02:37:01.000Z
2022-03-31T17:50:07.000Z
test/oli/interop/ingest_test.exs
chrislawson/oli-torus
94165b211ab74fac3e7c8a14110a394fa9a6f320
[ "MIT" ]
23
2020-07-28T03:36:13.000Z
2022-03-17T14:29:02.000Z
defmodule Oli.Interop.IngestTest do alias Oli.Interop.Ingest alias Oli.Interop.Export alias Oli.Publishing.AuthoringResolver alias Oli.Resources.Revision alias Oli.Repo use Oli.DataCase def by_title(project, title) do query = from r in Revision, where: r.title == ^title, limit: 1 AuthoringResolver.from_revision_slug(project.slug, Repo.one(query).slug) end def unzip_to_memory(data) do File.write("export.zip", data) result = :zip.unzip(to_charlist("export.zip"), [:memory]) File.rm!("export.zip") case result do {:ok, entries} -> entries _ -> [] end end def verify_export(entries) do assert length(entries) == 11 m = Enum.reduce(entries, %{}, fn {f, c}, m -> Map.put(m, f, c) end) assert Map.has_key?(m, '_hierarchy.json') assert Map.has_key?(m, '_media-manifest.json') assert Map.has_key?(m, '_project.json') hierarchy = Map.get(m, '_hierarchy.json') |> Jason.decode!() assert length(Map.get(hierarchy, "children")) == 1 unit = Map.get(hierarchy, "children") |> hd assert Map.get(unit, "title") == "Analog and Digital Unit" end # This mimics the result of unzipping a digest file, but instead reads the individual # files from disk (which makes updating and evolving this unit test easier). To mimic # the zip read result, we have to read all the JSON files in and present them as a # list of tuples where the first tuple item is a charlist representation of the file name # (just the file name, not the full path) and the second tuple item is the contents of # the file. def simulate_unzipping() do Path.wildcard("./test/oli/interop/digest/*.json") |> Enum.map(fn f -> {String.split(f, "/") |> Enum.reverse() |> hd |> String.to_charlist(), File.read(f)} end) |> Enum.map(fn {f, {:ok, contents}} -> {f, contents} end) end describe "course project ingest" do setup do Oli.Seeder.base_project_with_resource2() end test "ingest/1 and then export/1 works end to end", %{author: author} do {:ok, project} = simulate_unzipping() |> Ingest.process(author) Export.export(project) |> unzip_to_memory() |> verify_export() end test "ingest/1 processes the digest files and creates a course", %{author: author} do {:ok, p} = simulate_unzipping() |> Ingest.process(author) # verify project project = Repo.get(Oli.Authoring.Course.Project, p.id) assert project.title == "KTH CS101" assert p.title == project.title # verify project access for author access = Repo.get_by(Oli.Authoring.Authors.AuthorProject, author_id: author.id, project_id: project.id ) refute is_nil(access) # verify that the tags were created tags = Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "tag") assert length(tags) == 2 # verify correct number of hierarchy elements were created containers = Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "container") # 4 defined in the course, plus 1 for the root assert length(containers) == 4 + 1 # verify correct number of practice pages were created practice_pages = Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "page") |> Enum.filter(fn p -> !p.graded end) assert length(practice_pages) == 3 # verify that every practice page has a content attribute with a model assert Enum.all?(practice_pages, fn p -> Map.has_key?(p.content, "model") end) # verify that the page that had a link to another page had that link rewired correctly src = Enum.filter(practice_pages, fn p -> p.title == "Analog and Digital Page" end) |> hd dest = Enum.filter(practice_pages, fn p -> p.title == "Contents: Analog and Digital Page" end) |> hd link = Enum.at(src.content["model"], 0) |> Map.get("children") |> Enum.at(1) |> Map.get("children") |> Enum.at(5) assert link["href"] == "/course/link/#{dest.slug}" # spot check some elements to ensure that they were correctly constructed: # check an internal hierarchy node, one that contains references to only # other hierarchy nodes c = by_title(project, "Analog and Digital Unit") assert length(c.children) == 3 children = AuthoringResolver.from_resource_id(project.slug, c.children) assert Enum.at(children, 0).title == "Contents: Analog and Digital" assert Enum.at(children, 1).title == "Analog and Digital" assert Enum.at(children, 2).title == "Analog and Digital Quiz" # check a leaf hierarchy node, one that contains only page references c = by_title(project, "Analog and Digital") assert length(c.children) == 1 children = AuthoringResolver.from_resource_id(project.slug, c.children) assert Enum.at(children, 0).title == "Analog and Digital Page" # verify that all the activities were created correctly activities = Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "activity") assert length(activities) == 3 # verify the one activity that had a tag had the tag applied properly tag = Enum.filter(tags, fn p -> p.title == "Easy" end) |> hd tagged_activity = Enum.filter(activities, fn p -> p.title == "CATA" end) |> hd assert tagged_activity.tags == [tag.resource_id] end end end
35.177215
95
0.654732
e82956f928654fda9416e49fd19ebce1e199cd49
4,879
ex
Elixir
components/notifications-service/server/lib/formatters/compliance_helper.ex
oscar123mendoza/automate
b4c8f4e636bf82e453f684fff88fdc5d9253c0c5
[ "Apache-2.0" ]
4
2019-10-24T05:59:51.000Z
2021-08-16T15:17:27.000Z
components/notifications-service/server/lib/formatters/compliance_helper.ex
oscar123mendoza/automate
b4c8f4e636bf82e453f684fff88fdc5d9253c0c5
[ "Apache-2.0" ]
null
null
null
components/notifications-service/server/lib/formatters/compliance_helper.ex
oscar123mendoza/automate
b4c8f4e636bf82e453f684fff88fdc5d9253c0c5
[ "Apache-2.0" ]
null
null
null
defmodule Notifications.Formatters.ComplianceHelper do @moduledoc "Tools for the management of compliance notifications" alias Notifications.Profile @crit_control_threshold 0.7 # TODO: mp 2017-09-22 # Note that this is currently tested indirectly in webhook.compliance_test.ex # when we examine the payloads - most of which are generated by this module. # # This code is probably disposable, as this filtering will soon be happening # on the sendering side of the notification. # # If this plan changees, we'll # The next round of updates remove a lot of that due to changes in the way we # are handling payload testing for formatters. We'll move the specific # success-culling bheavior tests over here, to this module then. @doc """ This removes the following from the failed profiles in the provided ComplianceFailure: * all non-critical controls * within the controls all tests that are not failed In addition, if a control is left with no results (all tests passed) , the control itself will be removed from the containing profile. Finally, it augments the returned structure as follows: * each profile has the field :number_of_controls added, which reflects the number of controls in the full profile before it was pruned. * each remaining control has the following fields added for compatibility with the original usage * status - it will always be "failed", because we have filtered out successes. * number_of_tests - the original number of tests before pruning * number_of_failed_test - the size of the list of remaining results (tests) The best part is that this will probably be deleted, as we're moving the filtering to be done on the sender's side - it should send only what we need to process a failed compliance notification, and the things we prune are not needed by any outbound alerts. """ @spec prune_and_augment(Notifications.ComplianceFailure.t) :: Notifications.ComplianceFailure.t def prune_and_augment(%Notifications.ComplianceFailure{} = notification) do %{notification | failed_profiles: prune_profiles(notification.failed_profiles, [], @crit_control_threshold)} end def prune_and_augment(%Notifications.ComplianceFailure{} = notification, control_threshold) do %{notification | failed_profiles: prune_profiles(notification.failed_profiles, [], control_threshold)} end defp prune_profiles([], acc, control_threshold), do: acc defp prune_profiles([profile | profiles], acc, control_threshold) do failed_controls = prune_controls(profile.failed_controls, [], control_threshold) if length(failed_controls) > 0 do prune_controls(profiles, acc, control_threshold) additions = %{ controls: failed_controls, number_of_controls: profile.stats.num_tests, } newprof = profile |> Map.delete(:failed_controls) |> Map.delete(:stats) |> Map.merge(additions) prune_profiles(profiles, [newprof| acc], control_threshold) else prune_profiles(profiles, acc, control_threshold) end end # While all controls we receive have failures, some may not be critical. # For critical controls, further prune the results to limit to failures only. # For non-critical, drop them from the controls list. defp prune_controls([], acc, impact), do: acc defp prune_controls([%Profile.Control{impact: impact} = control | controls], acc, control_threshold) when impact >= control_threshold do pruned_results = prune_results(control.failed_results, []) stats = control.stats additions = %{results: pruned_results, number_of_tests: stats.num_tests, number_of_failed_tests: stats.num_failed_tests, status: "failed"} updated_results = control |> Map.delete(:stats) |> Map.delete(:failed_results) |> Map.merge(additions) prune_controls(controls, [updated_results | acc], control_threshold) end # Any control that's not critical gets excluded # # TODO - THIS filter must occur prior, because it can prevent # # the alert from needing to be triggered. defp prune_controls([_control | controls], acc, control_threshold), do: prune_controls(controls, acc, control_threshold) # Include only failed tests - that's all we're shipping to the webhook. If the test is not # failed it's dropped from the results list. We do know that a provided result will contain # at least one failure. defp prune_results([], acc), do: acc defp prune_results([%Profile.Control.Result{status: "failed"} = result | results], acc) do prune_results(results, [result | acc]) end # Anything that's not a failure gets excluded defp prune_results([_| results], acc), do: prune_results(results, acc) end
47.368932
138
0.722279
e82969ee4eb6255707a7e68db3797b883bcb0cfd
2,658
ex
Elixir
lib/ecto/migration/schema_migration.ex
elanmajkrzak/ecto_sql
bbaa22b32cf96ca5e90994bb0637e812487c53d4
[ "Apache-2.0" ]
null
null
null
lib/ecto/migration/schema_migration.ex
elanmajkrzak/ecto_sql
bbaa22b32cf96ca5e90994bb0637e812487c53d4
[ "Apache-2.0" ]
1
2021-01-19T22:05:44.000Z
2021-02-18T22:38:43.000Z
lib/ecto/migration/schema_migration.ex
elanmajkrzak/ecto_sql
bbaa22b32cf96ca5e90994bb0637e812487c53d4
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Migration.SchemaMigration do # Defines a schema that works with a table that tracks schema migrations. # The table name defaults to `schema_migrations`. @moduledoc false use Ecto.Schema import Ecto.Query, only: [from: 2] @primary_key false schema "schema_migrations" do field :version, :integer field :migration_script, :string timestamps updated_at: false end # The migration flag is used to signal to the repository # we are in a migration operation. @opts [timeout: :infinity, log: false, schema_migration: true] def ensure_schema_migrations_table!(repo, config, opts) do {repo, source} = get_repo_and_source(repo, config) table_name = String.to_atom(source) table = %Ecto.Migration.Table{name: table_name, prefix: opts[:prefix]} meta = Ecto.Adapter.lookup_meta(repo.get_dynamic_repo()) commands = [ {:add, :version, :bigint, primary_key: true}, {:add, :migration_script, :text, []}, {:add, :inserted_at, :naive_datetime, []} ] # DDL queries do not log, so we do not need to pass log: false here. repo.__adapter__().execute_ddl(meta, {:create_if_not_exists, table, commands}, @opts) end def ensure_schema_migrations_table_updated!(repo, config, opts) do {repo, source} = get_repo_and_source(repo, config) table_name = String.to_atom(source) table = %Ecto.Migration.Table{name: table_name, prefix: opts[:prefix]} meta = Ecto.Adapter.lookup_meta(repo.get_dynamic_repo()) commands = [ {:add_if_not_exists, :migration_script, :text, []} ] # DDL queries do not log, so we do not need to pass log: false here. repo.__adapter__().execute_ddl(meta, {:alter, table, commands}, @opts) end def versions(repo, config, prefix) do {repo, source} = get_repo_and_source(repo, config) {repo, from(m in source, select: [type(m.version, :integer), type(m.migration_script, :string)]), [prefix: prefix] ++ @opts} end def up(repo, config, version, migration_script, prefix) do {repo, source} = get_repo_and_source(repo, config) %__MODULE__{version: version, migration_script: migration_script} |> Ecto.put_meta(source: source) |> repo.insert([prefix: prefix] ++ @opts) end def down(repo, config, version, _migration_script, prefix) do {repo, source} = get_repo_and_source(repo, config) from(m in source, where: m.version == type(^version, :integer)) |> repo.delete_all([prefix: prefix] ++ @opts) end def get_repo_and_source(repo, config) do {Keyword.get(config, :migration_repo, repo), Keyword.get(config, :migration_source, "schema_migrations")} end end
35.44
128
0.698646
e8296bcabb01df2c1e793cb88c8898d2acdf53af
1,119
ex
Elixir
lib/filix/uploading/commands/request_upload.ex
MrDoops/filix
8be676e7733df5ea6a5ed78c7cb50f9e0fd76fd3
[ "MIT" ]
null
null
null
lib/filix/uploading/commands/request_upload.ex
MrDoops/filix
8be676e7733df5ea6a5ed78c7cb50f9e0fd76fd3
[ "MIT" ]
null
null
null
lib/filix/uploading/commands/request_upload.ex
MrDoops/filix
8be676e7733df5ea6a5ed78c7cb50f9e0fd76fd3
[ "MIT" ]
null
null
null
defmodule Filix.Uploading.Commands.RequestUpload do @moduledoc """ Command validation layer for Requesting Uploads """ use Ecto.Schema import Ecto.Changeset @required_fields ~w(name size type tags)a @optional_fields ~w(storage_provider)a @primary_key {:id, :binary_id, autogenerate: true} embedded_schema do field :name, :string field :size, :integer field :type, :string field :tags, {:array, :string} field :storage_provider, :string field :requested_on, :utc_datetime end def new(params) do command = changeset(params) case command.valid? do true -> {:ok, apply_changes(command)} false -> {:error, command.errors} end end defp changeset(params) do %__MODULE__{} |> cast(params, @required_fields ++ @optional_fields) |> validate_required(@required_fields) |> Map.put_new(:requested_on, DateTime.utc_now()) |> ensure_configured_storage_provider() end defp ensure_configured_storage_provider(changeset) do # TODO: check that the storage provider can map to a configured storage provider changeset end end
26.642857
84
0.705987
e82976f28194d9aa4b7b318bdb710ae71ad4801c
6,623
ex
Elixir
lib/oli/rendering/content.ex
jrissler/oli-torus
747f9e4360163d76a6ca5daee3aab1feab0c99b1
[ "MIT" ]
1
2022-03-17T20:35:47.000Z
2022-03-17T20:35:47.000Z
lib/oli/rendering/content.ex
jrissler/oli-torus
747f9e4360163d76a6ca5daee3aab1feab0c99b1
[ "MIT" ]
9
2021-11-02T16:52:09.000Z
2022-03-25T15:14:01.000Z
lib/oli/rendering/content.ex
marc-hughes/oli-torus-1
aa3c9bb2d91b678a365be839761eaf86c60ee35c
[ "MIT" ]
null
null
null
defmodule Oli.Rendering.Content do @moduledoc """ This modules defines the rendering functionality for Oli structured content. Rendering is extensible to any format which implements the behavior defined in this module, then specifying that format at render time. For an example of how exactly to extend this, see `content/html.ex`. """ import Oli.Utils alias Oli.Rendering.Context @type next :: (() -> String.t()) @type children :: [%{}] @callback example(%Context{}, next, %{}) :: [any()] @callback learn_more(%Context{}, next, %{}) :: [any()] @callback manystudentswonder(%Context{}, next, %{}) :: [any()] @callback text(%Context{}, %{}) :: [any()] @callback p(%Context{}, next, %{}) :: [any()] @callback h1(%Context{}, next, %{}) :: [any()] @callback h2(%Context{}, next, %{}) :: [any()] @callback h3(%Context{}, next, %{}) :: [any()] @callback h4(%Context{}, next, %{}) :: [any()] @callback h5(%Context{}, next, %{}) :: [any()] @callback h6(%Context{}, next, %{}) :: [any()] @callback img(%Context{}, next, %{}) :: [any()] @callback img_inline(%Context{}, next, %{}) :: [any()] @callback youtube(%Context{}, next, %{}) :: [any()] @callback iframe(%Context{}, next, %{}) :: [any()] @callback audio(%Context{}, next, %{}) :: [any()] @callback table(%Context{}, next, %{}) :: [any()] @callback tr(%Context{}, next, %{}) :: [any()] @callback th(%Context{}, next, %{}) :: [any()] @callback td(%Context{}, next, %{}) :: [any()] @callback ol(%Context{}, next, %{}) :: [any()] @callback ul(%Context{}, next, %{}) :: [any()] @callback li(%Context{}, next, %{}) :: [any()] @callback math(%Context{}, next, %{}) :: [any()] @callback math_line(%Context{}, next, %{}) :: [any()] @callback code(%Context{}, next, %{}) :: [any()] @callback code_line(%Context{}, next, %{}) :: [any()] @callback blockquote(%Context{}, next, %{}) :: [any()] @callback a(%Context{}, next, %{}) :: [any()] @callback popup(%Context{}, next, %{}) :: [any()] @callback selection(%Context{}, next, %{}) :: [any()] @callback error(%Context{}, %{}, {Atom.t(), String.t(), String.t()}) :: [any()] @doc """ Renders an Oli content element that contains children. Returns an IO list of strings. Content elements with purposes attached are deprecated but the rendering code is left here to support these existing elements. """ def render( %Context{} = context, %{"type" => "content", "children" => children, "purpose" => "example"} = element, writer ) do next = fn -> Enum.map(children, fn child -> render(context, child, writer) end) end writer.example(context, next, element) end def render( %Context{} = context, %{"type" => "content", "children" => children, "purpose" => "learnmore"} = element, writer ) do next = fn -> Enum.map(children, fn child -> render(context, child, writer) end) end writer.learn_more(context, next, element) end def render( %Context{} = context, %{"type" => "content", "children" => children, "purpose" => "manystudentswonder"} = element, writer ) do next = fn -> Enum.map(children, fn child -> render(context, child, writer) end) end writer.manystudentswonder(context, next, element) end def render(%Context{} = context, %{"type" => "content", "children" => children}, writer) do Enum.map(children, fn child -> render(context, child, writer) end) end # Renders text content def render(%Context{} = context, %{"text" => _text} = text_element, writer) do writer.text(context, text_element) end # Renders content children def render(%Context{} = context, children, writer) when is_list(children) do Enum.map(children, fn child -> render(context, child, writer) end) end # Renders a content element by calling the provided writer implementation on a # supported element type. def render( %Context{render_opts: render_opts} = context, %{"type" => type, "children" => children} = element, writer ) do next = fn -> render(context, children, writer) end case type do "p" -> writer.p(context, next, element) "h1" -> writer.h1(context, next, element) "h2" -> writer.h2(context, next, element) "h3" -> writer.h3(context, next, element) "h4" -> writer.h4(context, next, element) "h5" -> writer.h5(context, next, element) "h6" -> writer.h6(context, next, element) "img" -> writer.img(context, next, element) "img_inline" -> writer.img_inline(context, next, element) "youtube" -> writer.youtube(context, next, element) "iframe" -> writer.iframe(context, next, element) "audio" -> writer.audio(context, next, element) "table" -> writer.table(context, next, element) "tr" -> writer.tr(context, next, element) "th" -> writer.th(context, next, element) "td" -> writer.td(context, next, element) "ol" -> writer.ol(context, next, element) "ul" -> writer.ul(context, next, element) "li" -> writer.li(context, next, element) "math" -> writer.math(context, next, element) "math_line" -> writer.math_line(context, next, element) "code" -> writer.code(context, next, element) "code_line" -> writer.code_line(context, next, element) "blockquote" -> writer.blockquote(context, next, element) "a" -> writer.a(context, next, element) "popup" -> writer.popup(context, next, element) _ -> {error_id, error_msg} = log_error("Content element type is not supported", element) if render_opts.render_errors do writer.error(context, element, {:unsupported, error_id, error_msg}) else [] end end end def render(%Context{} = context, %{"type" => "selection"} = selection, writer) do writer.selection(context, fn -> true end, selection) end # Renders an error message if none of the signatures above match. Logging and rendering of errors # can be configured using the render_opts in context def render(%Context{render_opts: render_opts} = context, element, writer) do {error_id, error_msg} = log_error("Content element is invalid", element) if render_opts.render_errors do writer.error(context, element, {:invalid, error_id, error_msg}) else [] end end end
31.240566
99
0.588706
e829819832d968cdee4ceb07487eaa6e3a3f8516
5,279
ex
Elixir
lib/wax/attestation_statement_format/fido_u2f.ex
4eek/wax
eee7c5460267dce2cd8fe76df2e05f46e90e50b6
[ "Apache-2.0" ]
101
2019-02-11T10:39:34.000Z
2022-03-18T16:01:26.000Z
lib/wax/attestation_statement_format/fido_u2f.ex
4eek/wax
eee7c5460267dce2cd8fe76df2e05f46e90e50b6
[ "Apache-2.0" ]
19
2019-02-14T22:34:34.000Z
2022-01-25T17:42:13.000Z
lib/wax/attestation_statement_format/fido_u2f.ex
4eek/wax
eee7c5460267dce2cd8fe76df2e05f46e90e50b6
[ "Apache-2.0" ]
10
2019-03-12T15:56:21.000Z
2020-09-20T01:36:23.000Z
defmodule Wax.AttestationStatementFormat.FIDOU2F do require Logger @moduledoc false @behaviour Wax.AttestationStatementFormat @impl Wax.AttestationStatementFormat def verify( att_stmt, auth_data, client_data_hash, %Wax.Challenge{attestation: "direct"} = challenge ) do with :ok <- valid_cbor?(att_stmt), {:ok, pub_key} <- extract_and_verify_public_key(att_stmt), :ok <- verify_aaguid_null(auth_data), public_key_u2f <- get_raw_cose_key(auth_data), verification_data <- get_verification_data(auth_data, client_data_hash, public_key_u2f), :ok <- valid_signature?(att_stmt["sig"], verification_data, pub_key), :ok <- attestation_certificate_valid?(att_stmt["x5c"], challenge) do {attestation_type, metadata_statement} = determine_attestation_type(att_stmt["x5c"], challenge) {:ok, {attestation_type, att_stmt["x5c"], metadata_statement } } else error -> error end end def verify(_attstmt, _auth_data, _client_data_hash, _challenge) do {:error, :invalid_attestation_conveyance_preference} end @spec valid_cbor?(Wax.Attestation.statement()) :: :ok | {:error, any()} defp valid_cbor?(att_stmt) do if is_binary(att_stmt["sig"]) and is_list(att_stmt["x5c"]) and length(Map.keys(att_stmt)) == 2 # only these two keys do :ok else {:error, :attestation_fidou2f_invalid_cbor} end end @spec extract_and_verify_public_key(Wax.Attestation.statement()) :: {:ok, X509.PublicKey.t()} | {:error, any()} defp extract_and_verify_public_key(att_stmt) do case att_stmt["x5c"] do [der] -> cert = X509.Certificate.from_der!(der) pub_key = X509.Certificate.public_key(cert) Logger.debug("#{__MODULE__}: verifying validity of public key for certificate " <> "#{inspect(cert)}") if Wax.Utils.Certificate.public_key_algorithm(cert) == {1, 2, 840, 10045, 2, 1} and elem(pub_key, 1) == {:namedCurve, {1, 2, 840, 10045, 3, 1, 7}} do {:ok, pub_key} else {:error, :attestation_fidou2f_invalid_public_key_algorithm} end _ -> {:error, :attestation_fidou2f_multiple_x5c} end end @spec verify_aaguid_null(Wax.AuthenticatorData.t()) :: :ok | {:error, atom()} defp verify_aaguid_null(auth_data) do if :binary.decode_unsigned(auth_data.attested_credential_data.aaguid) == 0 do :ok else {:error, :attestation_fidou2f_non_nil_aaguid} end end @spec get_raw_cose_key(Wax.AuthenticatorData.t()) :: binary() defp get_raw_cose_key(auth_data) do x = auth_data.attested_credential_data.credential_public_key[-2] y = auth_data.attested_credential_data.credential_public_key[-3] <<04>> <> x <> y end @spec get_verification_data(Wax.AuthenticatorData.t(), Wax.ClientData.hash(), binary()) :: binary() defp get_verification_data(auth_data, client_data_hash, public_key_u2f) do <<0>> <> auth_data.rp_id_hash <> client_data_hash <> auth_data.attested_credential_data.credential_id <> public_key_u2f end @spec valid_signature?(binary(), binary(), X509.PublicKey.t()) :: :ok | {:error, any()} defp valid_signature?(sig, verification_data, pub_key) do Logger.debug("#{__MODULE__}: verifying signature #{inspect(sig)} " <> "of data #{inspect(verification_data)} " <> "with public key #{inspect(pub_key)}") if :public_key.verify(verification_data, :sha256, sig, pub_key) do :ok else {:error, :attestation_fidou2f_invalid_signature} end end @spec attestation_certificate_valid?([binary()], Wax.Challenge.t()) :: :ok | {:error, any()} def attestation_certificate_valid?( [leaf_cert | _], %Wax.Challenge{verify_trust_root: true} = challenge ) do acki = Wax.Utils.Certificate.attestation_certificate_key_identifier(leaf_cert) case Wax.Metadata.get_by_acki(acki, challenge) do %Wax.Metadata.Statement{} -> :ok nil -> {:error, :attestation_fidou2f_root_trust_certificate_not_found} end end def attestation_certificate_valid?(_, %Wax.Challenge{verify_trust_root: false}) do :ok end @spec determine_attestation_type([binary()], Wax.Challenge.t()) :: {Wax.Attestation.type(), Wax.Metadata.Statement.t()} | {Wax.Attestation.type(), nil} defp determine_attestation_type([leaf_cert | _], challenge) do acki = Wax.Utils.Certificate.attestation_certificate_key_identifier(leaf_cert) Logger.debug("#{__MODULE__}: determining attestation type for acki=#{inspect(acki)}") case Wax.Metadata.get_by_acki(acki, challenge) do nil -> {:uncertain, nil} # here we assume that :basic and :attca are exclusive for a given authenticator # but this seems however unspecified metadata_statement -> if :tag_attestation_basic_full in metadata_statement.attestation_types do {:basic, metadata_statement} else if :tag_attestation_attca in metadata_statement.attestation_types do {:attca, metadata_statement} else {:uncertain, nil} end end end end end
31.052941
97
0.671908
e8298859ef877133e6d486d9f788023b835a6a8e
812
exs
Elixir
ch6.exs
kbuechl/ProgrammingElixir
c46e6d5f10ccbc25203752cef6d073977969b2cf
[ "MIT" ]
null
null
null
ch6.exs
kbuechl/ProgrammingElixir
c46e6d5f10ccbc25203752cef6d073977969b2cf
[ "MIT" ]
null
null
null
ch6.exs
kbuechl/ProgrammingElixir
c46e6d5f10ccbc25203752cef6d073977969b2cf
[ "MIT" ]
null
null
null
defmodule Ex4 do def sum(0), do: 0 def sum(n), do: n + sum(n-1) end defmodule Ex5 do def gcd(x,0), do: x def gcd(x,y), do: gcd(y,rem(x,y)) end defmodule Ex6 do defmodule Chop do def guess(actual,low..high) when low <= high do half = div(high+low,2) IO.puts "Is it #{half}" doGuess(half,actual,low..high) end def guess(_,low..high) when low > high do IO.puts "passed it" end def doGuess(half,actual,low.._high) when half > actual do guess(actual,low..half-1) end def doGuess(half,actual,_low..high) when half < actual do guess(actual,half+1..high) end def doGuess(half,actual,_low.._high) when half == actual do IO.puts half end end end
24.606061
67
0.555419
e8298953c94c3b9fb4d5d8d4b73b3981470e4ff0
8,834
ex
Elixir
lib/new_relic/tracer/macro.ex
marocchino/elixir_agent
3c63715b130cf5997868c3a59097da256bf65102
[ "Apache-2.0" ]
null
null
null
lib/new_relic/tracer/macro.ex
marocchino/elixir_agent
3c63715b130cf5997868c3a59097da256bf65102
[ "Apache-2.0" ]
null
null
null
lib/new_relic/tracer/macro.ex
marocchino/elixir_agent
3c63715b130cf5997868c3a59097da256bf65102
[ "Apache-2.0" ]
null
null
null
defmodule NewRelic.Tracer.Macro do require Logger # Function Tracer Macros # 1) __on_definition__: When a function is defined & it's been marked to @trace, we # store information about the function in module attributes # 2) __before_compile__: We take the list of functions that are marked to @trace and: # a) Make them overridable # b) Re-define them with our tracing code wrapped around the original logic @moduledoc false alias NewRelic.Tracer defguardp is_variable(name, context) when is_atom(name) and (is_atom(context) or is_nil(context)) # Take no action on the definition of a function head def __on_definition__(_env, _access, _name, _args, _guards, nil), do: nil def __on_definition__(_env, _access, _name, _args, _guards, []), do: nil def __on_definition__(%{module: module}, access, name, args, guards, do: body) do if trace_info = trace_function?(module, name, length(args)) |> trace_deprecated?(module, name) do Module.put_attribute(module, :nr_tracers, %{ module: module, access: access, function: name, args: args, guards: guards, body: body, trace_info: trace_info }) Module.put_attribute(module, :nr_last_tracer, {name, length(args), trace_info}) Module.delete_attribute(module, :trace) end end # Take no action if there are other function-level clauses def __on_definition__(%{module: module}, _access, name, args, _guards, clauses) do if trace_function?(module, name, length(args)) do found = clauses |> Keyword.drop([:do]) |> Keyword.keys() |> Enum.map(&"`#{&1}`") |> Enum.join(", ") Logger.warn( "[New Relic] Unable to trace `#{inspect(module)}.#{name}/#{length(args)}` " <> "due to additional function-level clauses: #{found} -- please remove @trace" ) Module.delete_attribute(module, :trace) end end defmacro __before_compile__(%{module: module}) do Module.delete_attribute(module, :nr_last_tracer) Module.make_overridable(module, function_specs(module)) quote do (unquote_splicing(function_definitions(module))) end end def trace_function?(module, name, arity), do: trace_function?(:via_annotation, module) || trace_function?(:via_multiple_heads, module, name, arity) def trace_function?(:via_annotation, module), do: Module.get_attribute(module, :trace) def trace_function?(:via_multiple_heads, module, name, arity) do case Module.get_attribute(module, :nr_last_tracer) do {^name, ^arity, trace_info} -> trace_info _ -> false end end def trace_deprecated?({_, category: :datastore}, module, name) do Logger.warn( "[New Relic] Trace `:datastore` deprecated in favor of automatic ecto instrumentation. " <> "Please remove @trace from #{inspect(module)}.#{name}" ) false end def trace_deprecated?(trace_info, _, _) do trace_info end def function_specs(module), do: module |> Module.get_attribute(:nr_tracers) |> Enum.map(&traced_function_spec/1) |> Enum.uniq() def function_definitions(module), do: module |> Module.get_attribute(:nr_tracers) |> Enum.map(&traced_function_definition/1) |> Enum.reverse() def traced_function_spec(%{function: function, args: args}), do: {function, length(args)} def traced_function_definition(%{ module: module, access: :def, function: function, args: args, body: body, guards: [], trace_info: trace_info }) do quote do def unquote(function)(unquote_splicing(build_function_args(args))) do unquote(traced_function_body(body, module, function, args, trace_info)) end end end def traced_function_definition(%{ module: module, access: :def, function: function, args: args, body: body, guards: guards, trace_info: trace_info }) do quote do def unquote(function)(unquote_splicing(build_function_args(args))) when unquote_splicing(guards) do unquote(traced_function_body(body, module, function, args, trace_info)) end end end def traced_function_definition(%{ module: module, access: :defp, function: function, args: args, body: body, guards: [], trace_info: trace_info }) do quote do defp unquote(function)(unquote_splicing(build_function_args(args))) do unquote(traced_function_body(body, module, function, args, trace_info)) end end end def traced_function_definition(%{ module: module, access: :defp, function: function, args: args, body: body, guards: guards, trace_info: trace_info }) do quote do defp unquote(function)(unquote_splicing(build_function_args(args))) when unquote_splicing(guards) do unquote(traced_function_body(body, module, function, args, trace_info)) end end end def traced_function_body(body, module, function, args, trace_info) do quote do current_ref = make_ref() {span, previous_span, previous_span_attrs} = NewRelic.DistributedTrace.set_current_span( label: {unquote(module), unquote(function), unquote(length(args))}, ref: current_ref ) start_time = System.system_time() start_time_mono = System.monotonic_time() [reductions: start_reductions] = Process.info(self(), [:reductions]) try do unquote(body) rescue exception -> message = NewRelic.Util.Error.format_reason(:error, exception) NewRelic.DistributedTrace.set_span(:error, message: message) reraise exception, __STACKTRACE__ catch :exit, value -> message = NewRelic.Util.Error.format_reason(:exit, value) NewRelic.DistributedTrace.set_span(:error, message: "(EXIT) #{message}") exit(value) after end_time_mono = System.monotonic_time() [reductions: end_reductions] = Process.info(self(), [:reductions]) parent_ref = case previous_span do {_, ref} -> ref nil -> :root end duration_ms = System.convert_time_unit(end_time_mono - start_time_mono, :native, :millisecond) duration_acc = Process.get({:nr_duration_acc, parent_ref}, 0) Process.put({:nr_duration_acc, parent_ref}, duration_acc + duration_ms) child_duration_ms = Process.delete({:nr_duration_acc, current_ref}) || 0 if parent_ref == :root, do: Process.delete({:nr_duration_acc, parent_ref}) reductions = end_reductions - start_reductions Tracer.Report.call( {unquote(module), unquote(function), unquote(build_call_args(args))}, unquote(trace_info), inspect(self()), {span, previous_span || :root}, {start_time, start_time_mono, end_time_mono, child_duration_ms, reductions} ) NewRelic.DistributedTrace.reset_span( previous_span: previous_span, previous_span_attrs: previous_span_attrs ) end end end def build_function_args(args) when is_list(args), do: Enum.map(args, &build_function_args/1) # Don't try to re-declare the default argument def build_function_args({:\\, _, [arg, _default]}), do: arg def build_function_args(arg), do: arg def build_call_args(args) do Macro.postwalk(args, &rewrite_call_term/1) end # Unwrap Struct literals into a Map, they can't be re-referenced directly due to enforced_keys @struct_keys [:__aliases__, :__MODULE__] def rewrite_call_term({:%, line, [{key, _, _} = struct, {:%{}, _, members}]}) when key in @struct_keys do {:%{}, line, [{:__struct__, struct}] ++ members} end # Strip default arguments def rewrite_call_term({:\\, _, [arg, _default]}), do: arg # Drop the de-structuring side of a pattern match def rewrite_call_term({:=, _, [left, right]}) do cond do :__ignored__ == left -> right :__ignored__ == right -> left is_variable?(right) -> right is_variable?(left) -> left end end # Replace ignored variables with an atom def rewrite_call_term({name, _, context} = term) when is_variable(name, context) do case Atom.to_string(name) do "__" <> _special_form -> term "_" <> _ignored_var -> :__ignored__ _ -> term end end def rewrite_call_term(term), do: term def is_variable?({name, _, context}) when is_variable(name, context), do: true def is_variable?(_term), do: false end
30.567474
97
0.642744
e829c4ce907b2bf68416411b24c2898e2949c7ba
2,612
ex
Elixir
lib/cforum_web/controllers/users/session_controller.ex
Rolf-B/cforum_ex
2dcdfc76f0788824a5aa173c249a7051c61af0c4
[ "MIT" ]
null
null
null
lib/cforum_web/controllers/users/session_controller.ex
Rolf-B/cforum_ex
2dcdfc76f0788824a5aa173c249a7051c61af0c4
[ "MIT" ]
103
2021-10-13T04:24:01.000Z
2022-03-31T04:26:23.000Z
lib/cforum_web/controllers/users/session_controller.ex
Rolf-B/cforum_ex
2dcdfc76f0788824a5aa173c249a7051c61af0c4
[ "MIT" ]
null
null
null
defmodule CforumWeb.Users.SessionController do use CforumWeb, :controller alias Cforum.Abilities alias Cforum.Users alias Cforum.Users.User alias Cforum.Messages alias Cforum.Messages.Message alias Cforum.Threads alias Cforum.Threads.Thread alias CforumWeb.Views.ViewHelpers.Path def new(conn, _params) do changeset = User.login_changeset(%User{}) render(conn, "new.html", changeset: changeset) end def create(conn, %{"user" => %{"login" => user, "password" => pass, "remember_me" => remember}}) do case Users.authenticate_user(user, pass) do {:ok, user} -> conn = case remember do "true" -> token = Phoenix.Token.sign(CforumWeb.Endpoint, "user", user.user_id) conn |> put_resp_cookie("remember_me", token, max_age: 30 * 24 * 60 * 60, http_only: true, domain: Application.get_env(:cforum, :cookie_domain) ) _ -> conn end conn |> put_session(:user_id, user.user_id) |> configure_session(renew: true) |> put_flash(:info, gettext("You logged in successfully")) |> redirect(to: return_url(conn)) {:error, changeset} -> conn |> put_flash(:error, gettext("Username or password wrong")) |> render("new.html", changeset: changeset) end end def delete(conn, _) do conn |> configure_session(drop: true) |> put_flash(:info, gettext("You logged out successfully")) |> delete_resp_cookie("remember_me") |> redirect(to: Path.root_path(conn, :index)) end def allowed?(conn, :delete, _), do: Abilities.signed_in?(conn) def allowed?(conn, action, _) when action in [:new, :create], do: !Abilities.signed_in?(conn) def allowed?(_, _, _), do: false defp return_url(conn) do with mid when not is_nil(mid) and mid != "" <- conn.params["return_to"], true <- Regex.match?(~r/^\d+$/, mid), %Message{} = msg <- Messages.get_message(mid), %Thread{} = thread <- Threads.get_thread(msg.thread_id) do if String.starts_with?(conn.host, "blog."), do: Path.blog_thread_path(conn, :show, thread), else: Path.message_path(conn, :show, thread, msg) else _ -> Path.root_path(conn, :index) end end def not_allowed(conn, :new) do conn |> put_flash(:info, gettext("You are already logged in!")) |> redirect(to: Path.root_path(conn, :index)) end def not_allowed(conn, _), do: raise(Cforum.Errors.ForbiddenError, conn: conn) end
30.729412
101
0.61026
e829cb7651dee416c497153c7cca59a24075eb5c
200
exs
Elixir
myApp/priv/repo/migrations/20180428220535_create_user.exs
CaptainAwesomeDi/unnamedproject
1b2bbdbc9774a073e70eb8fcd255339d7a36df70
[ "MIT" ]
null
null
null
myApp/priv/repo/migrations/20180428220535_create_user.exs
CaptainAwesomeDi/unnamedproject
1b2bbdbc9774a073e70eb8fcd255339d7a36df70
[ "MIT" ]
null
null
null
myApp/priv/repo/migrations/20180428220535_create_user.exs
CaptainAwesomeDi/unnamedproject
1b2bbdbc9774a073e70eb8fcd255339d7a36df70
[ "MIT" ]
null
null
null
defmodule MyApp.Repo.Migrations.CreateUser do use Ecto.Migration def change do create table(:users) do add :name, :string add :age, :integer timestamps() end end end
15.384615
45
0.65
e829cd18e8c263402e644f7888960b2696015b60
31
ex
Elixir
astreu/lib/pubsub/pubsub.ex
wesleimp/Astreu
4d430733e7ecc8b3eba8e27811a152aa2c6d79c1
[ "Apache-2.0" ]
10
2021-02-10T12:00:26.000Z
2021-11-17T10:35:48.000Z
astreu/lib/pubsub/pubsub.ex
wesleimp/Astreu
4d430733e7ecc8b3eba8e27811a152aa2c6d79c1
[ "Apache-2.0" ]
11
2021-01-30T15:46:00.000Z
2021-04-27T01:44:07.000Z
astreu/lib/pubsub/pubsub.ex
wesleimp/Astreu
4d430733e7ecc8b3eba8e27811a152aa2c6d79c1
[ "Apache-2.0" ]
4
2021-01-29T12:18:32.000Z
2021-04-22T20:20:58.000Z
defmodule Astreu.PubSub do end
10.333333
26
0.83871
e829cf4fd0e56551a3f70da419d896ff8fcce035
1,980
exs
Elixir
mysite/config/prod.exs
palm86/Your-first-Phoenix-app-tutorial
e7de041e141254da6a731aead3a180fb9bd20c79
[ "MIT" ]
null
null
null
mysite/config/prod.exs
palm86/Your-first-Phoenix-app-tutorial
e7de041e141254da6a731aead3a180fb9bd20c79
[ "MIT" ]
null
null
null
mysite/config/prod.exs
palm86/Your-first-Phoenix-app-tutorial
e7de041e141254da6a731aead3a180fb9bd20c79
[ "MIT" ]
null
null
null
use Mix.Config # For production, we configure the host to read the PORT # from the system environment. Therefore, you will need # to set PORT=80 before running your server. # # You should also configure the url host to something # meaningful, we use this information when generating URLs. # # Finally, we also include the path to a manifest # containing the digested version of static files. This # manifest is generated by the mix phoenix.digest task # which you typically run after static files are built. config :mysite, Mysite.Endpoint, http: [port: {:system, "PORT"}], url: [host: "example.com", port: 80], cache_static_manifest: "priv/static/manifest.json" # Do not print debug messages in production config :logger, level: :info # ## SSL Support # # To get SSL working, you will need to add the `https` key # to the previous section and set your `:url` port to 443: # # config :mysite, Mysite.Endpoint, # ... # url: [host: "example.com", port: 443], # https: [port: 443, # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"), # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")] # # Where those two env variables return an absolute path to # the key and cert in disk or a relative path inside priv, # for example "priv/ssl/server.key". # # We also recommend setting `force_ssl`, ensuring no data is # ever sent via http, always redirecting to https: # # config :mysite, Mysite.Endpoint, # force_ssl: [hsts: true] # # Check `Plug.SSL` for all available options in `force_ssl`. # ## Using releases # # If you are doing OTP releases, you need to instruct Phoenix # to start the server for all endpoints: # # config :phoenix, :serve_endpoints, true # # Alternatively, you can configure exactly which server to # start per endpoint: # # config :mysite, Mysite.Endpoint, server: true # # Finally import the config/prod.secret.exs # which should be versioned separately. import_config "prod.secret.exs"
31.935484
67
0.712121
e829f24dfdd46ff043ea752bf90dff36ca96017f
691
ex
Elixir
lib/asciinema_web/views/application_view.ex
potherca-contrib/asciinema-server
c5ac6e45e8f117d4d59c9c33da6b59b448e40f0e
[ "Apache-2.0" ]
null
null
null
lib/asciinema_web/views/application_view.ex
potherca-contrib/asciinema-server
c5ac6e45e8f117d4d59c9c33da6b59b448e40f0e
[ "Apache-2.0" ]
null
null
null
lib/asciinema_web/views/application_view.ex
potherca-contrib/asciinema-server
c5ac6e45e8f117d4d59c9c33da6b59b448e40f0e
[ "Apache-2.0" ]
null
null
null
defmodule AsciinemaWeb.ApplicationView do import Phoenix.HTML.Tag, only: [content_tag: 3] def present?([]), do: false def present?(nil), do: false def present?(""), do: false def present?(_), do: true def time_tag(time) do iso_8601_ts = Timex.format!(time, "{ISO:Extended:Z}") rfc_1123_ts = Timex.format!(time, "{RFC1123z}") content_tag(:time, datetime: iso_8601_ts) do "on #{rfc_1123_ts}" end end def time_ago_tag(time) do iso_8601_ts = Timex.format!(time, "{ISO:Extended:Z}") rfc_1123_ts = Timex.format!(time, "{RFC1123z}") content_tag(:time, datetime: iso_8601_ts, title: rfc_1123_ts) do Timex.from_now(time) end end end
25.592593
68
0.665702
e829f56a1bd3a2f30786a2d71fccef18c22fee4f
792
ex
Elixir
testData/org/elixir_lang/parser_definition/matched_call_operation/matched_expression_parsing_test_case/Variable.ex
ArtemGordinsky/intellij-elixir
e2d9b4dfc65651b293d499043edeaad606cf5652
[ "Apache-2.0" ]
null
null
null
testData/org/elixir_lang/parser_definition/matched_call_operation/matched_expression_parsing_test_case/Variable.ex
ArtemGordinsky/intellij-elixir
e2d9b4dfc65651b293d499043edeaad606cf5652
[ "Apache-2.0" ]
null
null
null
testData/org/elixir_lang/parser_definition/matched_call_operation/matched_expression_parsing_test_case/Variable.ex
ArtemGordinsky/intellij-elixir
e2d9b4dfc65651b293d499043edeaad606cf5652
[ "Apache-2.0" ]
null
null
null
variable &one variable one \\ default variable one when guard variable one :: type variable one | new variable one = two variable one or two variable one || two variable one and two variable one && two variable one != two variable one < two variable one |> two variable one + two variable one / two variable one * two variable one ^^^ two variable !one variable One.Two variable One.two variable @one variable one variable @1 variable &1 variable !1 variable not 1 variable (;) variable ?1 variable 0b10 variable 1.2e-3 variable 1 variable 0xFF variable 0o7 variable [] variable "StringLine" variable """ String Heredoc """ variable 'CharListLine' variable ''' CharListLine ''' variable ~x{sigil}modifiers variable nil variable :atom variable One
16.5
27
0.717172
e82a28cc25b1be6d35a9af21da58965f34803084
2,551
ex
Elixir
clients/big_query/lib/google_api/big_query/v2/model/table_data_insert_all_request.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/table_data_insert_all_request.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/big_query/lib/google_api/big_query/v2/model/table_data_insert_all_request.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.BigQuery.V2.Model.TableDataInsertAllRequest do @moduledoc """ ## Attributes - ignoreUnknownValues (boolean()): [Optional] Accept rows that contain values that do not match the schema. The unknown values are ignored. Default is false, which treats unknown values as errors. Defaults to: `null`. - kind (String.t): The resource type of the response. Defaults to: `null`. - rows ([TableDataInsertAllRequestRows]): The rows to insert. Defaults to: `null`. - skipInvalidRows (boolean()): [Optional] Insert all valid rows of a request, even if invalid rows exist. The default value is false, which causes the entire request to fail if any invalid rows exist. Defaults to: `null`. - templateSuffix (String.t): [Experimental] If specified, treats the destination table as a base template, and inserts the rows into an instance table named \&quot;{destination}{templateSuffix}\&quot;. BigQuery will manage creation of the instance table, using the schema of the base template table. See https://cloud.google.com/bigquery/streaming-data-into-bigquery#template-tables for considerations when working with templates tables. Defaults to: `null`. """ defstruct [ :"ignoreUnknownValues", :"kind", :"rows", :"skipInvalidRows", :"templateSuffix" ] end defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.TableDataInsertAllRequest do import GoogleApi.BigQuery.V2.Deserializer def decode(value, options) do value |> deserialize(:"rows", :list, GoogleApi.BigQuery.V2.Model.TableDataInsertAllRequestRows, options) end end defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.TableDataInsertAllRequest do def encode(value, options) do GoogleApi.BigQuery.V2.Deserializer.serialize_non_nil(value, options) end end
45.553571
460
0.75931
e82a29711b399df697887fc00794c9f6a748534b
7,583
ex
Elixir
clients/poly/lib/google_api/poly/v1/api/assets.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/poly/lib/google_api/poly/v1/api/assets.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/poly/lib/google_api/poly/v1/api/assets.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Poly.V1.Api.Assets do @moduledoc """ API calls for all endpoints tagged `Assets`. """ alias GoogleApi.Poly.V1.Connection alias GoogleApi.Gax.{Request, Response} @doc """ Returns detailed information about an asset given its name. PRIVATE assets are returned only if the currently authenticated user (via OAuth token) is the author of the asset. ## Parameters - connection (GoogleApi.Poly.V1.Connection): Connection to server - name (String.t): Required. An asset&#39;s name in the form &#x60;assets/{ASSET_ID}&#x60;. - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). ## Returns {:ok, %GoogleApi.Poly.V1.Model.Asset{}} on success {:error, info} on failure """ @spec poly_assets_get(Tesla.Env.client(), String.t(), keyword()) :: {:ok, GoogleApi.Poly.V1.Model.Asset.t()} | {:error, Tesla.Env.t()} def poly_assets_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/{+name}", %{ "name" => URI.encode_www_form(name) }) |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Poly.V1.Model.Asset{}]) end @doc """ Lists all public, remixable assets. These are assets with an access level of PUBLIC and published under the CC-By license. ## Parameters - connection (GoogleApi.Poly.V1.Connection): Connection to server - optional_params (KeywordList): [optional] Optional parameters - :$.xgafv (String.t): V1 error format. - :access_token (String.t): OAuth access token. - :alt (String.t): Data format for response. - :callback (String.t): JSONP - :fields (String.t): Selector specifying which fields to include in a partial response. - :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String.t): OAuth 2.0 token for the current user. - :prettyPrint (boolean()): Returns response with indentations and line breaks. - :quotaUser (String.t): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. - :upload_protocol (String.t): Upload protocol for media (e.g. \&quot;raw\&quot;, \&quot;multipart\&quot;). - :uploadType (String.t): Legacy upload protocol for media (e.g. \&quot;media\&quot;, \&quot;multipart\&quot;). - :category (String.t): Filter assets based on the specified category. Supported values are: &#x60;animals&#x60;, &#x60;architecture&#x60;, &#x60;art&#x60;, &#x60;food&#x60;, &#x60;nature&#x60;, &#x60;objects&#x60;, &#x60;people&#x60;, &#x60;scenes&#x60;, &#x60;technology&#x60;, and &#x60;transport&#x60;. - :curated (boolean()): Return only assets that have been curated by the Poly team. - :format (String.t): Return only assets with the matching format. Acceptable values are: &#x60;BLOCKS&#x60;, &#x60;FBX&#x60;, &#x60;GLTF&#x60;, &#x60;GLTF2&#x60;, &#x60;OBJ&#x60;, &#x60;TILT&#x60;. - :keywords (String.t): One or more search terms to be matched against all text that Poly has indexed for assets, which includes display_name, description, and tags. Multiple keywords should be separated by spaces. - :maxComplexity (String.t): Returns assets that are of the specified complexity or less. Defaults to COMPLEX. For example, a request for MEDIUM assets also includes SIMPLE assets. - :orderBy (String.t): Specifies an ordering for assets. Acceptable values are: &#x60;BEST&#x60;, &#x60;NEWEST&#x60;, &#x60;OLDEST&#x60;. Defaults to &#x60;BEST&#x60;, which ranks assets based on a combination of popularity and other features. - :pageSize (integer()): The maximum number of assets to be returned. This value must be between &#x60;1&#x60; and &#x60;100&#x60;. Defaults to &#x60;20&#x60;. - :pageToken (String.t): Specifies a continuation token from a previous search whose results were split into multiple pages. To get the next page, submit the same request specifying the value from next_page_token. ## Returns {:ok, %GoogleApi.Poly.V1.Model.ListAssetsResponse{}} on success {:error, info} on failure """ @spec poly_assets_list(Tesla.Env.client(), keyword()) :: {:ok, GoogleApi.Poly.V1.Model.ListAssetsResponse.t()} | {:error, Tesla.Env.t()} def poly_assets_list(connection, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :upload_protocol => :query, :uploadType => :query, :category => :query, :curated => :query, :format => :query, :keywords => :query, :maxComplexity => :query, :orderBy => :query, :pageSize => :query, :pageToken => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1/assets") |> Request.add_optional_params(optional_params_config, optional_params) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.Poly.V1.Model.ListAssetsResponse{}]) end end
50.553333
310
0.67981
e82a3bc0860fae7009c9f33a9dcb09af618fcff4
1,806
ex
Elixir
clients/slides/lib/google_api/slides/v1/connection.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/slides/lib/google_api/slides/v1/connection.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/slides/lib/google_api/slides/v1/connection.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Slides.V1.Connection do @moduledoc """ Handle Tesla connections for GoogleApi.Slides.V1. """ @type t :: Tesla.Env.client() use GoogleApi.Gax.Connection, scopes: [ # See, edit, create, and delete all of your Google Drive files "https://www.googleapis.com/auth/drive", # View and manage Google Drive files and folders that you have opened or created with this app "https://www.googleapis.com/auth/drive.file", # See and download all your Google Drive files "https://www.googleapis.com/auth/drive.readonly", # View and manage your Google Slides presentations "https://www.googleapis.com/auth/presentations", # View your Google Slides presentations "https://www.googleapis.com/auth/presentations.readonly", # See, edit, create, and delete your spreadsheets in Google Drive "https://www.googleapis.com/auth/spreadsheets", # View your Google Spreadsheets "https://www.googleapis.com/auth/spreadsheets.readonly" ], otp_app: :google_api_slides, base_url: "https://slides.googleapis.com/" end
35.411765
100
0.719269
e82a681585c9c0cbbceb5eed9037dda6bf2d77df
2,633
ex
Elixir
lib/chess/move/figure_route.ex
7hoenix/Chess
8b57b2d6dd4235e2ee67622f6521f83cd237417b
[ "MIT" ]
8
2018-11-12T13:45:42.000Z
2022-03-15T14:45:26.000Z
lib/chess/move/figure_route.ex
7hoenix/Chess
8b57b2d6dd4235e2ee67622f6521f83cd237417b
[ "MIT" ]
1
2021-08-30T08:58:53.000Z
2021-10-13T09:15:36.000Z
lib/chess/move/figure_route.ex
7hoenix/Chess
8b57b2d6dd4235e2ee67622f6521f83cd237417b
[ "MIT" ]
3
2020-12-08T22:32:37.000Z
2022-01-27T17:54:55.000Z
defmodule Chess.Move.FigureRoute do @moduledoc """ Module for checking figures routes """ alias Chess.Figure defmacro __using__(_opts) do quote do defp do_check_figure_route(%Figure{color: color, type: "p"}, route, [_, move_from_y], _) do unless pion_move?(route, move_from_y, color), do: {:error, "Pion can not move like this"} end defp do_check_figure_route(%Figure{type: "r"}, route, _, _) do unless linear_move?(route), do: {:error, "Rook can not move like this"} end defp do_check_figure_route(%Figure{type: "n"}, route, _, _) do unless knight_move?(route), do: {:error, "Knight can not move like this"} end defp do_check_figure_route(%Figure{type: "b"}, route, _, _) do unless diagonal_move?(route), do: {:error, "Bishop can not move like this"} end defp do_check_figure_route(%Figure{type: "q"}, route, _, _) do unless diagonal_move?(route) || linear_move?(route), do: {:error, "Queen can not move like this"} end defp do_check_figure_route(%Figure{color: color, type: "k"}, route, _, castling) do unless king_move?(route, castling, color), do: {:error, "King can not move like this"} end defp pion_move?([x_route, y_route], move_from_y, "w") do abs(x_route) == 1 && y_route == 1 || x_route == 0 && (y_route == 1 || y_route == 2 && move_from_y == start_line_for_pion("w")) end defp pion_move?([x_route, y_route], move_from_y, _) do abs(x_route) == 1 && y_route == -1 || x_route == 0 && (y_route == -1 || y_route == -2 && move_from_y == start_line_for_pion("b")) end defp start_line_for_pion("w"), do: "2" defp start_line_for_pion(_), do: "7" defp linear_move?([x_route, y_route]), do: x_route == 0 || y_route == 0 defp diagonal_move?([x_route, y_route]), do: abs(x_route) == abs(y_route) defp knight_move?([x_route, y_route]), do: abs(x_route) == 2 && abs(y_route) == 1 || abs(x_route) == 1 && abs(y_route) == 2 defp king_move?([x_route, y_route], castling, color) do possible = [-1, 0, 1] x_route in possible && y_route in possible || x_route in [-2, 2] && y_route == 0 && String.contains?(castling, possible_castling(x_route, color)) end defp possible_castling(x_route, color) do way_of_castling(x_route) |> side_of_castling(color) end defp way_of_castling(2), do: "k" defp way_of_castling(_), do: "q" defp side_of_castling(side, "w"), do: String.capitalize(side) defp side_of_castling(side, _), do: side end end end
38.15942
153
0.622104
e82a8a15a364835c3b46be373fb7600f342c64b4
5,941
ex
Elixir
clients/my_business_lodging/lib/google_api/my_business_lodging/v1/model/policies.ex
renovate-bot/elixir-google-api
1da34cd39b670c99f067011e05ab90af93fef1f6
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/my_business_lodging/lib/google_api/my_business_lodging/v1/model/policies.ex
swansoffiee/elixir-google-api
9ea6d39f273fb430634788c258b3189d3613dde0
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/my_business_lodging/lib/google_api/my_business_lodging/v1/model/policies.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.MyBusinessLodging.V1.Model.Policies do @moduledoc """ Property rules that impact guests. ## Attributes * `allInclusiveAvailable` (*type:* `boolean()`, *default:* `nil`) - All inclusive available. The hotel offers a rate option that includes the cost of the room, meals, activities, and other amenities that might otherwise be charged separately. * `allInclusiveAvailableException` (*type:* `String.t`, *default:* `nil`) - All inclusive available exception. * `allInclusiveOnly` (*type:* `boolean()`, *default:* `nil`) - All inclusive only. The only rate option offered by the hotel is a rate that includes the cost of the room, meals, activities and other amenities that might otherwise be charged separately. * `allInclusiveOnlyException` (*type:* `String.t`, *default:* `nil`) - All inclusive only exception. * `checkinTime` (*type:* `GoogleApi.MyBusinessLodging.V1.Model.TimeOfDay.t`, *default:* `nil`) - Check-in time. The time of the day at which the hotel begins providing guests access to their unit at the beginning of their stay. * `checkinTimeException` (*type:* `String.t`, *default:* `nil`) - Check-in time exception. * `checkoutTime` (*type:* `GoogleApi.MyBusinessLodging.V1.Model.TimeOfDay.t`, *default:* `nil`) - Check-out time. The time of the day on the last day of a guest's reserved stay at which the guest must vacate their room and settle their bill. Some hotels may offer late or early check out for a fee. * `checkoutTimeException` (*type:* `String.t`, *default:* `nil`) - Check-out time exception. * `kidsStayFree` (*type:* `boolean()`, *default:* `nil`) - Kids stay free. The children of guests are allowed to stay in the room/suite of a parent or adult without an additional fee. The policy may or may not stipulate a limit of the child's age or the overall number of children allowed. * `kidsStayFreeException` (*type:* `String.t`, *default:* `nil`) - Kids stay free exception. * `maxChildAge` (*type:* `integer()`, *default:* `nil`) - Max child age. The hotel allows children up to a certain age to stay in the room/suite of a parent or adult without an additional fee. * `maxChildAgeException` (*type:* `String.t`, *default:* `nil`) - Max child age exception. * `maxKidsStayFreeCount` (*type:* `integer()`, *default:* `nil`) - Max kids stay free count. The hotel allows a specific, defined number of children to stay in the room/suite of a parent or adult without an additional fee. * `maxKidsStayFreeCountException` (*type:* `String.t`, *default:* `nil`) - Max kids stay free count exception. * `paymentOptions` (*type:* `GoogleApi.MyBusinessLodging.V1.Model.PaymentOptions.t`, *default:* `nil`) - Forms of payment accepted at the property. * `smokeFreeProperty` (*type:* `boolean()`, *default:* `nil`) - Smoke free property. Smoking is not allowed inside the building, on balconies, or in outside spaces. Hotels that offer a designated area for guests to smoke are not considered smoke-free properties. * `smokeFreePropertyException` (*type:* `String.t`, *default:* `nil`) - Smoke free property exception. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :allInclusiveAvailable => boolean() | nil, :allInclusiveAvailableException => String.t() | nil, :allInclusiveOnly => boolean() | nil, :allInclusiveOnlyException => String.t() | nil, :checkinTime => GoogleApi.MyBusinessLodging.V1.Model.TimeOfDay.t() | nil, :checkinTimeException => String.t() | nil, :checkoutTime => GoogleApi.MyBusinessLodging.V1.Model.TimeOfDay.t() | nil, :checkoutTimeException => String.t() | nil, :kidsStayFree => boolean() | nil, :kidsStayFreeException => String.t() | nil, :maxChildAge => integer() | nil, :maxChildAgeException => String.t() | nil, :maxKidsStayFreeCount => integer() | nil, :maxKidsStayFreeCountException => String.t() | nil, :paymentOptions => GoogleApi.MyBusinessLodging.V1.Model.PaymentOptions.t() | nil, :smokeFreeProperty => boolean() | nil, :smokeFreePropertyException => String.t() | nil } field(:allInclusiveAvailable) field(:allInclusiveAvailableException) field(:allInclusiveOnly) field(:allInclusiveOnlyException) field(:checkinTime, as: GoogleApi.MyBusinessLodging.V1.Model.TimeOfDay) field(:checkinTimeException) field(:checkoutTime, as: GoogleApi.MyBusinessLodging.V1.Model.TimeOfDay) field(:checkoutTimeException) field(:kidsStayFree) field(:kidsStayFreeException) field(:maxChildAge) field(:maxChildAgeException) field(:maxKidsStayFreeCount) field(:maxKidsStayFreeCountException) field(:paymentOptions, as: GoogleApi.MyBusinessLodging.V1.Model.PaymentOptions) field(:smokeFreeProperty) field(:smokeFreePropertyException) end defimpl Poison.Decoder, for: GoogleApi.MyBusinessLodging.V1.Model.Policies do def decode(value, options) do GoogleApi.MyBusinessLodging.V1.Model.Policies.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.MyBusinessLodging.V1.Model.Policies do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
62.536842
302
0.717556
e82ab68957145b7d4c2826dd0dfe93324894e2cf
132
exs
Elixir
test/eksel_test.exs
jnylen/eksel
4270eef1100cf5399e80d41d3230cbfbcfb52be3
[ "MIT" ]
null
null
null
test/eksel_test.exs
jnylen/eksel
4270eef1100cf5399e80d41d3230cbfbcfb52be3
[ "MIT" ]
null
null
null
test/eksel_test.exs
jnylen/eksel
4270eef1100cf5399e80d41d3230cbfbcfb52be3
[ "MIT" ]
null
null
null
defmodule EkselTest do use ExUnit.Case doctest Eksel test "greets the world" do assert Eksel.hello() == :world end end
14.666667
34
0.69697
e82ac2aae53ea1fe608687959dc58a06b0db31d6
37
exs
Elixir
elixir/simple.exs
xxxbxxx/advent-of-code
e340ea5c92e12c55ef2b4391e58d9fb733043aa7
[ "Unlicense" ]
null
null
null
elixir/simple.exs
xxxbxxx/advent-of-code
e340ea5c92e12c55ef2b4391e58d9fb733043aa7
[ "Unlicense" ]
null
null
null
elixir/simple.exs
xxxbxxx/advent-of-code
e340ea5c92e12c55ef2b4391e58d9fb733043aa7
[ "Unlicense" ]
null
null
null
IO.puts("Hello world from Elixir")
9.25
34
0.702703
e82ae347f59b865c95ad393242aa632399408c4c
620
exs
Elixir
priv/repo/migrations/20220208092928_create_access_tokens.exs
mpotra/composable_ecto_queries
c8498b23d8bc05dc410f5bc163c6641049cd07a6
[ "MIT" ]
null
null
null
priv/repo/migrations/20220208092928_create_access_tokens.exs
mpotra/composable_ecto_queries
c8498b23d8bc05dc410f5bc163c6641049cd07a6
[ "MIT" ]
null
null
null
priv/repo/migrations/20220208092928_create_access_tokens.exs
mpotra/composable_ecto_queries
c8498b23d8bc05dc410f5bc163c6641049cd07a6
[ "MIT" ]
null
null
null
defmodule Repo.Migrations.CreateAccessTokens do use Ecto.Migration def change do create table("access_tokens") do add(:issuer_id, references("issuers", type: :bigserial, on_delete: :delete_all), null: false ) add(:audience_id, references("audience", type: :bigserial, on_delete: :delete_all), null: true ) add(:expires_in, :integer, null: false, default: 3600) # Timestamps add(:created_at, :utc_datetime_usec, null: false, default: fragment("CURRENT_TIMESTAMP")) add(:revoked_at, :utc_datetime_usec, null: true, default: nil) end end end
29.52381
95
0.670968
e82af33513056cafca784277bb2a38138b70c5a4
375
ex
Elixir
lib/movement/persisters/revision_uncorrect_all.ex
suryatmodulus/accent
6aaf34075c33f3d9d84d38237af4a39b594eb808
[ "BSD-3-Clause" ]
806
2018-04-07T20:40:33.000Z
2022-03-30T01:39:57.000Z
lib/movement/persisters/revision_uncorrect_all.ex
suryatmodulus/accent
6aaf34075c33f3d9d84d38237af4a39b594eb808
[ "BSD-3-Clause" ]
194
2018-04-07T13:49:37.000Z
2022-03-30T19:58:45.000Z
lib/movement/persisters/revision_uncorrect_all.ex
doc-ai/accent
e337e16f3658cc0728364f952c0d9c13710ebb06
[ "BSD-3-Clause" ]
89
2018-04-09T13:55:49.000Z
2022-03-24T07:09:31.000Z
defmodule Movement.Persisters.RevisionUncorrectAll do @behaviour Movement.Persister alias Accent.Repo alias Movement.Persisters.Base, as: BasePersister @batch_action "uncorrect_all" def persist(context) do Repo.transaction(fn -> context |> Movement.Context.assign(:batch_action, @batch_action) |> BasePersister.execute() end) end end
22.058824
62
0.730667
e82af6f0d216fc60c7362680c4c1b47b0486c7c6
983
ex
Elixir
lib/mix/tasks/plex.token.ex
wisq/plextube
96984d6e6a114709e563c1dcb7a557fd14d46ef6
[ "Apache-2.0" ]
15
2017-09-18T12:02:12.000Z
2022-02-15T00:35:00.000Z
lib/mix/tasks/plex.token.ex
wisq/plextube
96984d6e6a114709e563c1dcb7a557fd14d46ef6
[ "Apache-2.0" ]
null
null
null
lib/mix/tasks/plex.token.ex
wisq/plextube
96984d6e6a114709e563c1dcb7a557fd14d46ef6
[ "Apache-2.0" ]
2
2017-09-21T20:17:49.000Z
2020-04-12T12:21:42.000Z
defmodule Mix.Tasks.Plex.Token do use Mix.Task @shortdoc "Get a Plex application token" def run([username, password]) do {:ok, _started} = Application.ensure_all_started(:plextube) headers = Plextube.Plex.headers(false) body = URI.encode_query(%{ "user[login]" => username, "user[password]" => password, }) token = HTTPoison.post!("https://plex.tv/users/sign_in.json", body, [{"Content-Type", "application/x-www-form-urlencoded"} | headers]) |> Map.fetch!(:body) |> Poison.decode! |> Map.fetch!("user") |> Map.fetch!("authentication_token") IO.puts "Authentication successful! Your token: #{inspect(token)}" IO.puts "" IO.puts "Put this token in your config/pipedrive.exs:" IO.puts "" IO.puts " config :plextube," IO.puts " plex_token: #{inspect(token)}" IO.puts "" end def run(_) do Mix.raise "Usage: mix plex.token <Plex username> <Plex password>" end end
27.305556
74
0.624619
e82afcffe4ed47fa83ac59aebf960fd1e60afcfb
70
exs
Elixir
test/test_helper.exs
dreamingechoes/bloggex
9ead10ec1fd8fda0da3cb08106c43a9043188199
[ "MIT" ]
1
2020-01-14T03:17:51.000Z
2020-01-14T03:17:51.000Z
test/test_helper.exs
dreamingechoes/bloggex
9ead10ec1fd8fda0da3cb08106c43a9043188199
[ "MIT" ]
null
null
null
test/test_helper.exs
dreamingechoes/bloggex
9ead10ec1fd8fda0da3cb08106c43a9043188199
[ "MIT" ]
null
null
null
ExUnit.start() Ecto.Adapters.SQL.Sandbox.mode(Bloggex.Repo, :manual)
17.5
53
0.771429
e82b04d35c7ec62650b18bf912f656b46949beeb
584
exs
Elixir
spec/web/views/auth_view_spec.exs
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
spec/web/views/auth_view_spec.exs
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
spec/web/views/auth_view_spec.exs
Squadster/squadster-api
cf04af79317148d7a08c649d5b5d0197722acb7a
[ "MIT" ]
null
null
null
defmodule Squadster.Web.AuthViewSpec do use ESpec.Phoenix, async: true, view: AuthView use ESpec.Phoenix.Extend, :view describe "callback.json" do let :user, do: insert(:user) let :content do render(SquadsterWeb.AuthView, "callback.json", user: user(), show_info: true) end it "renders user info" do %{user: user} = content() expect user |> to(eq(user() |> Map.take(Squadster.Accounts.User.user_fields))) end it "renders show_info" do %{show_info: show_info} = content() expect show_info |> to(eq true) end end end
26.545455
84
0.65411
e82b3eead6af4383c41162559caed17088d9f4fc
19,286
exs
Elixir
lib/elixir/test/elixir/module/types/types_test.exs
tnascimento/elixir
9a4d10e702f33d2fa47718cde05375b506b4a3d6
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/module/types/types_test.exs
tnascimento/elixir
9a4d10e702f33d2fa47718cde05375b506b4a3d6
[ "Apache-2.0" ]
null
null
null
lib/elixir/test/elixir/module/types/types_test.exs
tnascimento/elixir
9a4d10e702f33d2fa47718cde05375b506b4a3d6
[ "Apache-2.0" ]
null
null
null
Code.require_file("type_helper.exs", __DIR__) defmodule Module.Types.TypesTest do use ExUnit.Case, async: true alias Module.Types alias Module.Types.{Pattern, Expr} defmacro warning(patterns \\ [], guards \\ [], body) do min_line = min_line(patterns ++ guards ++ [body]) patterns = reset_line(patterns, min_line) guards = reset_line(guards, min_line) body = reset_line(body, min_line) expr = TypeHelper.expand_expr(patterns, guards, body, __CALLER__) quote do Module.Types.TypesTest.__expr__(unquote(Macro.escape(expr))) end end defmacro generated(ast) do Macro.prewalk(ast, fn node -> Macro.update_meta(node, &([generated: true] ++ &1)) end) end def __expr__({patterns, guards, body}) do with {:ok, _types, context} <- Pattern.of_head(patterns, guards, TypeHelper.new_stack(), TypeHelper.new_context()), {:ok, _type, context} <- Expr.of_expr(body, :dynamic, TypeHelper.new_stack(), context) do case context.warnings do [warning] -> to_message(:warning, warning) _ -> :none end else {:error, {type, reason, context}} -> to_message(:error, {type, reason, context}) end end defp reset_line(ast, min_line) do Macro.prewalk(ast, fn ast -> Macro.update_meta(ast, fn meta -> Keyword.update!(meta, :line, &(&1 - min_line + 1)) end) end) end defp min_line(ast) do {_ast, min} = Macro.prewalk(ast, :infinity, fn {_fun, meta, _args} = ast, min -> {ast, min(min, Keyword.get(meta, :line, 1))} other, min -> {other, min} end) min end defp to_message(:warning, {module, warning, _location}) do warning |> module.format_warning() |> IO.iodata_to_binary() end defp to_message(:error, {type, reason, context}) do {Module.Types, error, _location} = Module.Types.error_to_warning(type, reason, context) error |> Module.Types.format_warning() |> IO.iodata_to_binary() |> String.trim_trailing("\nConflict found at") end test "expr_to_string/1" do assert Types.expr_to_string({1, 2}) == "{1, 2}" assert Types.expr_to_string(quote(do: Foo.bar(arg))) == "Foo.bar(arg)" assert Types.expr_to_string(quote(do: :erlang.band(a, b))) == "Bitwise.band(a, b)" assert Types.expr_to_string(quote(do: :erlang.orelse(a, b))) == "a or b" assert Types.expr_to_string(quote(do: :erlang."=:="(a, b))) == "a === b" assert Types.expr_to_string(quote(do: :erlang.list_to_atom(a))) == "List.to_atom(a)" assert Types.expr_to_string(quote(do: :maps.remove(a, b))) == "Map.delete(b, a)" assert Types.expr_to_string(quote(do: :erlang.element(1, a))) == "elem(a, 0)" assert Types.expr_to_string(quote(do: :erlang.element(:erlang.+(a, 1), b))) == "elem(b, a)" end test "undefined function warnings" do assert warning([], URI.unknown("foo")) == "URI.unknown/1 is undefined or private" assert warning([], if(true, do: URI.unknown("foo"))) == "URI.unknown/1 is undefined or private" assert warning([], try(do: :ok, after: URI.unknown("foo"))) == "URI.unknown/1 is undefined or private" end describe "function head warnings" do test "warns on literals" do string = warning([var = 123, var = "abc"], var) assert string == """ incompatible types: integer() !~ binary() in expression: # types_test.ex:1 var = "abc" where "var" was given the type integer() in: # types_test.ex:1 var = 123 where "var" was given the type binary() in: # types_test.ex:1 var = "abc" """ end test "warns on binary patterns" do string = warning([<<var::integer, var::binary>>], var) assert string == """ incompatible types: integer() !~ binary() in expression: # types_test.ex:1 <<..., var::binary>> where "var" was given the type integer() in: # types_test.ex:1 <<var::integer, ...>> where "var" was given the type binary() in: # types_test.ex:1 <<..., var::binary>> """ end test "warns on recursive patterns" do string = warning([{var} = var], var) assert string == """ incompatible types: {var1} !~ var1 in expression: # types_test.ex:1 {var} = var where "var" was given the type {var1} in: # types_test.ex:1 {var} = var """ end test "warns on guards" do string = warning([var], [is_integer(var) and is_binary(var)], var) assert string == """ incompatible types: integer() !~ binary() in expression: # types_test.ex:1 is_binary(var) where "var" was given the type integer() in: # types_test.ex:1 is_integer(var) where "var" was given the type binary() in: # types_test.ex:1 is_binary(var) """ end test "warns on guards with multiple variables" do string = warning([x = y], [is_integer(x) and is_binary(y)], {x, y}) assert string == """ incompatible types: integer() !~ binary() in expression: # types_test.ex:1 is_binary(y) where "x" was given the same type as "y" in: # types_test.ex:1 x = y where "y" was given the type integer() in: # types_test.ex:1 is_integer(x) where "y" was given the type binary() in: # types_test.ex:1 is_binary(y) """ end test "warns on guards from cases unless generated" do string = warning( [var], [is_integer(var)], case var do _ when is_binary(var) -> :ok end ) assert is_binary(string) string = generated( warning( [var], [is_integer(var)], case var do _ when is_binary(var) -> :ok end ) ) assert string == :none end test "only show relevant traces in warning" do string = warning([x = y, z], [is_integer(x) and is_binary(y) and is_boolean(z)], {x, y, z}) assert string == """ incompatible types: integer() !~ binary() in expression: # types_test.ex:1 is_binary(y) where "x" was given the same type as "y" in: # types_test.ex:1 x = y where "y" was given the type integer() in: # types_test.ex:1 is_integer(x) where "y" was given the type binary() in: # types_test.ex:1 is_binary(y) """ end test "check body" do string = warning([x], [is_integer(x)], :foo = x) assert string == """ incompatible types: integer() !~ :foo in expression: # types_test.ex:1 :foo = x where "x" was given the type integer() in: # types_test.ex:1 is_integer(x) where "x" was given the type :foo in: # types_test.ex:1 :foo = x """ end test "check binary" do string = warning([foo], [is_binary(foo)], <<foo>>) assert string == """ incompatible types: binary() !~ integer() in expression: # types_test.ex:1 <<foo>> where "foo" was given the type binary() in: # types_test.ex:1 is_binary(foo) where "foo" was given the type integer() in: # types_test.ex:1 <<foo>> HINT: all expressions given to binaries are assumed to be of type \ integer() unless said otherwise. For example, <<expr>> assumes "expr" \ is an integer. Pass a modifier, such as <<expr::float>> or <<expr::binary>>, \ to change the default behaviour. """ string = warning([foo], [is_binary(foo)], <<foo::integer>>) assert string == """ incompatible types: binary() !~ integer() in expression: # types_test.ex:1 <<foo::integer>> where "foo" was given the type binary() in: # types_test.ex:1 is_binary(foo) where "foo" was given the type integer() in: # types_test.ex:1 <<foo::integer>> """ end test "is_tuple warning" do string = warning([foo], [is_tuple(foo)], {_} = foo) assert string == """ incompatible types: tuple() !~ {dynamic()} in expression: # types_test.ex:1 {_} = foo where "foo" was given the type tuple() in: # types_test.ex:1 is_tuple(foo) where "foo" was given the type {dynamic()} in: # types_test.ex:1 {_} = foo HINT: use pattern matching or "is_tuple(foo) and tuple_size(foo) == 1" to guard a sized tuple. """ end test "function call" do string = warning([foo], [rem(foo, 2.0) == 0], foo) assert string == """ expected Kernel.rem/2 to have signature: var1, float() -> dynamic() but it has signature: integer(), integer() -> integer() in expression: # types_test.ex:1 rem(foo, 2.0) """ end test "operator call" do string = warning([foo], [foo - :bar == 0], foo) assert string == """ expected Kernel.-/2 to have signature: var1, :bar -> dynamic() but it has signature: integer(), integer() -> integer() float(), integer() | float() -> float() integer() | float(), float() -> float() in expression: # types_test.ex:1 foo - :bar """ end end describe "map warnings" do test "handling of non-singleton types in maps" do string = warning( [], ( event = %{"type" => "order"} %{"amount" => amount} = event %{"user" => user} = event %{"id" => user_id} = user {:order, user_id, amount} ) ) assert string == """ incompatible types: binary() !~ map() in expression: # types_test.ex:5 %{"id" => user_id} = user where "amount" was given the type binary() in: # types_test.ex:3 %{"amount" => amount} = event where "amount" was given the same type as "user" in: # types_test.ex:4 %{"user" => user} = event where "user" was given the type binary() in: # types_test.ex:4 %{"user" => user} = event where "user" was given the type map() in: # types_test.ex:5 %{"id" => user_id} = user """ end test "show map() when comparing against non-map" do string = warning( [foo], ( foo.bar :atom = foo ) ) assert string == """ incompatible types: map() !~ :atom in expression: # types_test.ex:4 :atom = foo where "foo" was given the type map() (due to calling var.field) in: # types_test.ex:3 foo.bar where "foo" was given the type :atom in: # types_test.ex:4 :atom = foo HINT: "var.field" (without parentheses) implies "var" is a map() while \ "var.fun()" (with parentheses) implies "var" is an atom() """ end test "use module as map (without parentheses)" do string = warning( [foo], ( %module{} = foo module.__struct__ ) ) assert string == """ incompatible types: map() !~ atom() in expression: # types_test.ex:4 module.__struct__ where "module" was given the type atom() in: # types_test.ex:3 %module{} where "module" was given the type map() (due to calling var.field) in: # types_test.ex:4 module.__struct__ HINT: "var.field" (without parentheses) implies "var" is a map() while \ "var.fun()" (with parentheses) implies "var" is an atom() """ end test "use map as module (with parentheses)" do string = warning([foo], [is_map(foo)], foo.__struct__()) assert string == """ incompatible types: map() !~ atom() in expression: # types_test.ex:1 foo.__struct__() where "foo" was given the type map() in: # types_test.ex:1 is_map(foo) where "foo" was given the type atom() (due to calling var.fun()) in: # types_test.ex:1 foo.__struct__() HINT: "var.field" (without parentheses) implies "var" is a map() while \ "var.fun()" (with parentheses) implies "var" is an atom() """ end test "non-existent map field warning" do string = warning( ( map = %{foo: 1} map.bar ) ) assert string == """ undefined field "bar" in expression: # types_test.ex:3 map.bar expected one of the following fields: foo where "map" was given the type map() in: # types_test.ex:2 map = %{foo: 1} """ end test "non-existent struct field warning" do string = warning( [foo], ( %URI{} = foo foo.bar ) ) assert string == """ undefined field "bar" in expression: # types_test.ex:4 foo.bar expected one of the following fields: __struct__, authority, fragment, host, path, port, query, scheme, userinfo where "foo" was given the type %URI{} in: # types_test.ex:3 %URI{} = foo """ end test "expands type variables" do string = warning( [%{foo: key} = event, other_key], [is_integer(key) and is_atom(other_key)], %{foo: ^other_key} = event ) assert string == """ incompatible types: %{foo: integer()} !~ %{foo: atom()} in expression: # types_test.ex:3 %{foo: ^other_key} = event where "event" was given the type %{foo: integer(), optional(dynamic()) => dynamic()} in: # types_test.ex:1 %{foo: key} = event where "event" was given the type %{foo: atom(), optional(dynamic()) => dynamic()} in: # types_test.ex:3 %{foo: ^other_key} = event """ end test "expands map when maps are nested" do string = warning( [map1, map2], ( [_var1, _var2] = [map1, map2] %{} = map1 %{} = map2.subkey ) ) assert string == """ incompatible types: %{subkey: var1, optional(dynamic()) => dynamic()} !~ %{optional(dynamic()) => dynamic()} | %{optional(dynamic()) => dynamic()} in expression: # types_test.ex:5 map2.subkey where "map2" was given the type %{optional(dynamic()) => dynamic()} | %{optional(dynamic()) => dynamic()} in: # types_test.ex:3 [_var1, _var2] = [map1, map2] where "map2" was given the type %{subkey: var1, optional(dynamic()) => dynamic()} (due to calling var.field) in: # types_test.ex:5 map2.subkey HINT: "var.field" (without parentheses) implies "var" is a map() while "var.fun()" (with parentheses) implies "var" is an atom() """ end end describe "regressions" do test "recursive map fields" do assert warning( [queried], with( true <- is_nil(queried.foo.bar), _ = queried.foo ) do %{foo: %{other_id: _other_id} = foo} = queried %{other_id: id} = foo %{id: id} end ) == :none end test "no-recursion on guards with map fields" do assert warning( [assigns], ( variable_enum = assigns.variable_enum case true do _ when variable_enum != nil -> assigns.variable_enum end ) ) == :none end test "map patterns with pinned keys and field access" do assert warning( [x, y], ( key_var = y %{^key_var => _value} = x key_var2 = y %{^key_var2 => _value2} = x y.z ) ) == :none end test "map patterns with pinned keys" do assert warning( [x, y], ( key_var = y %{^key_var => _value} = x key_var2 = y %{^key_var2 => _value2} = x key_var3 = y %{^key_var3 => _value3} = x ) ) == :none end test "map updates with var key" do assert warning( [state0, key0], ( state1 = %{state0 | key0 => true} key1 = key0 state2 = %{state1 | key1 => true} state2 ) ) == :none end end end
25.748999
143
0.463445
e82b598723e3f9b95110b07aef940f69f59f53db
257
ex
Elixir
lib/ephemeral2.ex
losvedir/ephemeral2
4d48d6b7724127efc4f416ec45c4c2cb28472fc3
[ "MIT" ]
864
2015-05-12T13:00:28.000Z
2022-02-03T20:17:12.000Z
lib/ephemeral2.ex
losvedir/ephemeral2
4d48d6b7724127efc4f416ec45c4c2cb28472fc3
[ "MIT" ]
4
2015-05-13T22:07:17.000Z
2015-07-10T17:03:31.000Z
lib/ephemeral2.ex
losvedir/ephemeral2
4d48d6b7724127efc4f416ec45c4c2cb28472fc3
[ "MIT" ]
71
2015-05-12T13:30:05.000Z
2021-10-01T03:37:40.000Z
defmodule Ephemeral2 do @moduledoc """ Ephemeral2 keeps the contexts that define your domain and business logic. Contexts are also responsible for managing your data, regardless if it comes from the database, an external API or others. """ end
25.7
66
0.758755
e82b64c6493737ce65263ca0e8f2a552e8f6a717
3,482
ex
Elixir
lib/fortnox_ex/api/default.ex
rsystem-se/fortnox_ex
42516a8d364d7b3efb2d09bcfd1bd6dbb0238463
[ "MIT" ]
2
2021-02-03T14:40:22.000Z
2021-02-03T17:11:48.000Z
lib/fortnox_ex/api/default.ex
rsystem-se/fortnox_ex
42516a8d364d7b3efb2d09bcfd1bd6dbb0238463
[ "MIT" ]
null
null
null
lib/fortnox_ex/api/default.ex
rsystem-se/fortnox_ex
42516a8d364d7b3efb2d09bcfd1bd6dbb0238463
[ "MIT" ]
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 FortnoxEx.Api.Default do @moduledoc """ API calls for all endpoints tagged `Default`. """ alias FortnoxEx.Connection import FortnoxEx.RequestBuilder @doc """ Get customer by customer number ## Parameters - connection (FortnoxEx.Connection): Connection to server - customer_number (String.t): The customer number - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %FortnoxEx.Model.Customer{}} on success {:error, info} on failure """ @spec get_customer_by_customer_number(Tesla.Env.client, String.t, keyword()) :: {:ok, FortnoxEx.Model.Customer.t} | {:error, Tesla.Env.t} def get_customer_by_customer_number(connection, customer_number, _opts \\ []) do %{} |> method(:get) |> url("/customers/#{customer_number}") |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> evaluate_response([ { 200, %FortnoxEx.Model.Customer{}} ]) end @doc """ List customers ## Parameters - connection (FortnoxEx.Connection): Connection to server - opts (KeywordList): [optional] Optional parameters - :financialyeardate (String.t): Selects by date, what financial year that should be used - :financialyear (String.t): Selects what financial year that should be used - :fromdate (String.t): Defines a selection based on a start date. Only available for invoices, orders, offers and vouchers. - :lastmodified (String.t): Retrieves all records since the provided timestamp. - :limit (integer()): Limit per page. Default 100, from 1 to 500 are valid options. - :offset (integer()): Offset - :page (integer()): Page, with 1 beeing the first page - :sortby (String.t): A result can be sorted, either ascending or descending, by specific fields. These fields are listed in the table under the section “Fields” in the documentation for each resource. This is made in the same way as the search and the filter, by adding GET parameters. Apart from the filters and the search, sorting uses two parameters. One named “sortby”, which specifies the field that the result should be sorted by and one named “sortorder”, which specifies the order in which the sorting should be made. - :sortorder (String.t): Sorting order - :todate (String.t): Defines a selection based on an end date. Only available for invoices, orders, offers and vouchers - :filter (String.t): Filters on active and inactive customers ## Returns {:ok, %FortnoxEx.Model.CustomerList{}} on success {:error, info} on failure """ @spec list_customers(Tesla.Env.client, keyword()) :: {:ok, FortnoxEx.Model.CustomerList.t} | {:error, Tesla.Env.t} def list_customers(connection, opts \\ []) do optional_params = %{ :"financialyeardate" => :query, :"financialyear" => :query, :"fromdate" => :query, :"lastmodified" => :query, :"limit" => :query, :"offset" => :query, :"page" => :query, :"sortby" => :query, :"sortorder" => :query, :"todate" => :query, :"filter" => :query } %{} |> method(:get) |> url("/customers") |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> evaluate_response([ { 200, %FortnoxEx.Model.CustomerList{}} ]) end end
39.568182
530
0.674325
e82b7c681a6f085db8ba6b1dc13f1b1d4470ff5f
1,608
ex
Elixir
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/remove_tenant_project_request.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/remove_tenant_project_request.ex
linjunpop/elixir-google-api
444cb2b2fb02726894535461a474beddd8b86db4
[ "Apache-2.0" ]
null
null
null
clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/remove_tenant_project_request.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.ServiceConsumerManagement.V1.Model.RemoveTenantProjectRequest do @moduledoc """ Request message to remove a tenant project resource from the tenancy unit. ## Attributes - tag (String.t): Tag of the resource within the tenancy unit. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :tag => any() } field(:tag) end defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.RemoveTenantProjectRequest do def decode(value, options) do GoogleApi.ServiceConsumerManagement.V1.Model.RemoveTenantProjectRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.RemoveTenantProjectRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
32.16
98
0.759328
e82b94fd2f49b9408518926c700f29f555f100d8
122
ex
Elixir
web/admin/user_properties.ex
mijkenator/elapi
55a85edf6fcadd89e390a682404c79bab93282b0
[ "Artistic-2.0" ]
null
null
null
web/admin/user_properties.ex
mijkenator/elapi
55a85edf6fcadd89e390a682404c79bab93282b0
[ "Artistic-2.0" ]
null
null
null
web/admin/user_properties.ex
mijkenator/elapi
55a85edf6fcadd89e390a682404c79bab93282b0
[ "Artistic-2.0" ]
null
null
null
defmodule Elapi.ExAdmin.UserProperties do use ExAdmin.Register register_resource Elapi.UserProperties do end end
13.555556
43
0.811475
e82bb720ec8e323de39b39d3bfcb9b45f00062dd
4,640
ex
Elixir
clients/blogger/lib/google_api/blogger/v3/model/post.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
1
2018-12-03T23:43:10.000Z
2018-12-03T23:43:10.000Z
clients/blogger/lib/google_api/blogger/v3/model/post.ex
matehat/elixir-google-api
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
[ "Apache-2.0" ]
null
null
null
clients/blogger/lib/google_api/blogger/v3/model/post.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.Blogger.V3.Model.Post do @moduledoc """ ## Attributes * `author` (*type:* `GoogleApi.Blogger.V3.Model.PostAuthor.t`, *default:* `nil`) - The author of this Post. * `blog` (*type:* `GoogleApi.Blogger.V3.Model.PostBlog.t`, *default:* `nil`) - Data about the blog containing this Post. * `content` (*type:* `String.t`, *default:* `nil`) - The content of the Post. May contain HTML markup. * `customMetaData` (*type:* `String.t`, *default:* `nil`) - The JSON meta-data for the Post. * `etag` (*type:* `String.t`, *default:* `nil`) - Etag of the resource. * `id` (*type:* `String.t`, *default:* `nil`) - The identifier of this Post. * `images` (*type:* `list(GoogleApi.Blogger.V3.Model.PostImages.t)`, *default:* `nil`) - Display image for the Post. * `kind` (*type:* `String.t`, *default:* `blogger#post`) - The kind of this entity. Always blogger#post * `labels` (*type:* `list(String.t)`, *default:* `nil`) - The list of labels this Post was tagged with. * `location` (*type:* `GoogleApi.Blogger.V3.Model.PostLocation.t`, *default:* `nil`) - The location for geotagged posts. * `published` (*type:* `DateTime.t`, *default:* `nil`) - RFC 3339 date-time when this Post was published. * `readerComments` (*type:* `String.t`, *default:* `nil`) - Comment control and display setting for readers of this post. * `replies` (*type:* `GoogleApi.Blogger.V3.Model.PostReplies.t`, *default:* `nil`) - The container of comments on this Post. * `selfLink` (*type:* `String.t`, *default:* `nil`) - The API REST URL to fetch this resource from. * `status` (*type:* `String.t`, *default:* `nil`) - Status of the post. Only set for admin-level requests * `title` (*type:* `String.t`, *default:* `nil`) - The title of the Post. * `titleLink` (*type:* `String.t`, *default:* `nil`) - The title link URL, similar to atom's related link. * `updated` (*type:* `DateTime.t`, *default:* `nil`) - RFC 3339 date-time when this Post was last updated. * `url` (*type:* `String.t`, *default:* `nil`) - The URL where this Post is displayed. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :author => GoogleApi.Blogger.V3.Model.PostAuthor.t(), :blog => GoogleApi.Blogger.V3.Model.PostBlog.t(), :content => String.t(), :customMetaData => String.t(), :etag => String.t(), :id => String.t(), :images => list(GoogleApi.Blogger.V3.Model.PostImages.t()), :kind => String.t(), :labels => list(String.t()), :location => GoogleApi.Blogger.V3.Model.PostLocation.t(), :published => DateTime.t(), :readerComments => String.t(), :replies => GoogleApi.Blogger.V3.Model.PostReplies.t(), :selfLink => String.t(), :status => String.t(), :title => String.t(), :titleLink => String.t(), :updated => DateTime.t(), :url => String.t() } field(:author, as: GoogleApi.Blogger.V3.Model.PostAuthor) field(:blog, as: GoogleApi.Blogger.V3.Model.PostBlog) field(:content) field(:customMetaData) field(:etag) field(:id) field(:images, as: GoogleApi.Blogger.V3.Model.PostImages, type: :list) field(:kind) field(:labels, type: :list) field(:location, as: GoogleApi.Blogger.V3.Model.PostLocation) field(:published, as: DateTime) field(:readerComments) field(:replies, as: GoogleApi.Blogger.V3.Model.PostReplies) field(:selfLink) field(:status) field(:title) field(:titleLink) field(:updated, as: DateTime) field(:url) end defimpl Poison.Decoder, for: GoogleApi.Blogger.V3.Model.Post do def decode(value, options) do GoogleApi.Blogger.V3.Model.Post.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Blogger.V3.Model.Post do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
45.940594
128
0.651078
e82bbe40887868b2b236d558472011cc92c7e9d1
725
ex
Elixir
lib/perspective/reactor/state/backup_state.ex
backmath/perspective
a0a577d0ffb06805b64e4dcb171a093e051884b0
[ "MIT" ]
2
2020-04-24T19:43:06.000Z
2020-04-24T19:52:27.000Z
lib/perspective/reactor/state/backup_state.ex
backmath/perspective
a0a577d0ffb06805b64e4dcb171a093e051884b0
[ "MIT" ]
null
null
null
lib/perspective/reactor/state/backup_state.ex
backmath/perspective
a0a577d0ffb06805b64e4dcb171a093e051884b0
[ "MIT" ]
null
null
null
defmodule Perspective.Reactor.BackupState do def save_state(reactor_name, state) do state |> Perspective.Serialize.to_json() |> Perspective.SaveLocalFile.save(backup_filename(reactor_name)) end def load_state(reactor_name) do try do reactor_name |> backup_filename() |> Perspective.LoadLocalFile.load!() |> Perspective.Deserialize.deserialize() rescue Perspective.LocalFileNotFound -> raise Perspective.Reactor.BackupStateMissing, reactor_name end end defp backup_filename(reactor_name) do reactor_name |> to_string() |> String.replace(~r/^Elixir\./, "") |> String.replace_suffix("", ".json") |> Perspective.StorageConfig.path() end end
26.851852
97
0.69931
e82bca8c1f0a37f57b34393991e5e889cefa0fe6
622
ex
Elixir
apps/tcp_server/lib/tcp_server/workflows/gmsg_heartbeat.ex
Alezrik/game_services_umbrella
9b9dd6707c200b10c5a73568913deb4d5d8320be
[ "MIT" ]
4
2018-11-09T16:57:06.000Z
2021-03-02T22:57:17.000Z
apps/tcp_server/lib/tcp_server/workflows/gmsg_heartbeat.ex
Alezrik/game_services_umbrella
9b9dd6707c200b10c5a73568913deb4d5d8320be
[ "MIT" ]
29
2018-10-26T08:29:37.000Z
2018-12-09T21:02:05.000Z
apps/tcp_server/lib/tcp_server/workflows/gmsg_heartbeat.ex
Alezrik/game_services_umbrella
9b9dd6707c200b10c5a73568913deb4d5d8320be
[ "MIT" ]
null
null
null
defmodule TcpServer.Workflows.GmsgHeartbeat do @moduledoc false require Logger def process_msg(%{type: "GMSG_HEARTBEAT"} = params, opts \\ []) do Task.Supervisor.async_nolink(TcpServer.TaskSupervisor, fn -> execute(params, opts) end) end defp execute(params, opts) do Logger.info(fn -> "Processing Heartbeat request" end) response_message = %{type: "SMSG_HEARTBEAT", type_id: 101} {:ok, message_len, message} = TcpServer.CommandSerializer.serialize(response_message) GenServer.cast( ClusterManager.get_tcp_client(), {:send_msg, 101, message_len, message, opts} ) end end
31.1
91
0.717042
e82bcf2a9062abac0e74fe30a43e5f0b8d5eb34d
4,038
exs
Elixir
test/exfile/ecto/file_template_test.exs
sreecodeslayer/exfile
c88288563d688fb47a6fcae190dbe1b8eb64bf9b
[ "MIT" ]
100
2015-12-25T12:38:41.000Z
2021-12-31T11:41:20.000Z
test/exfile/ecto/file_template_test.exs
sreecodeslayer/exfile
c88288563d688fb47a6fcae190dbe1b8eb64bf9b
[ "MIT" ]
62
2015-12-26T01:43:54.000Z
2019-09-15T16:16:35.000Z
test/exfile/ecto/file_template_test.exs
sreecodeslayer/exfile
c88288563d688fb47a6fcae190dbe1b8eb64bf9b
[ "MIT" ]
22
2016-04-19T11:54:38.000Z
2021-09-29T14:48:46.000Z
defmodule Exfile.Ecto.FileTemplateTest do use ExUnit.Case, async: true defmodule TestFile do use Exfile.Ecto.FileTemplate, backend: "store", cache_backend: "cache" end import Ecto.Type def backend(), do: Exfile.Config.get_backend("cache") def store_backend(), do: Exfile.Config.get_backend("store") def store2_backend(), do: Exfile.Config.get_backend("store2") def file_contents_equal(file, contents) do {:ok, local_file} = Exfile.File.open(file) {:ok, io} = Exfile.LocalFile.open(local_file) IO.binread(io, :all) == contents end setup do file_contents = "hello there" {:ok, io} = File.open(file_contents, [:ram, :binary, :read]) local_file = %Exfile.LocalFile{io: io} {:ok, file} = Exfile.Backend.upload(backend(), local_file) # rewind the io because it's been read in the upload process above :file.position(io, :bof) {:ok, store_file} = Exfile.Backend.upload(store_backend(), local_file) # rewind the io because it's been read in the upload process above :file.position(io, :bof) {:ok, store2_file} = Exfile.Backend.upload(store2_backend(), local_file) # rewind the io because it's been read in the upload process above :file.position(io, :bof) {:ok, %{ file_contents: file_contents, cache_file: file, store_file: store_file, store2_file: store2_file, local_file: local_file }} end test "casting a Exfile.File returns a new Exfile.File", %{store2_file: file, file_contents: file_contents} do {:ok, new_file} = cast(TestFile, file) assert %Exfile.File{} = new_file assert new_file.id != file.id assert file_contents_equal(new_file, file_contents) end test "casting a Exfile.LocalFile returns a new Exfile.File", %{local_file: local_file, file_contents: file_contents} do {:ok, new_file} = cast(TestFile, local_file) assert %Exfile.File{} = new_file assert file_contents_equal(new_file, file_contents) end test "casting a Plug.Upload returns a new Exfile.File", _ do file_contents = "hello there contents" path = Plug.Upload.random_file!("exfile") :ok = File.write!(path, file_contents) upload = %Plug.Upload{path: path} {:ok, new_file} = cast(TestFile, upload) assert %Exfile.File{} = new_file assert file_contents_equal(new_file, file_contents) end test "casting a string binary representing an existing file works", %{cache_file: file, file_contents: file_contents} do {:ok, new_file} = cast(TestFile, "exfile://cache/" <> file.id) assert %Exfile.File{} = new_file assert new_file.backend == file.backend assert new_file.id == file.id assert file_contents_equal(new_file, file_contents) end test "casting a string binary representing an existing file on a different backend works" do file_contents = "hello there" {:ok, io} = File.open(file_contents, [:ram, :binary, :read]) local_file = %Exfile.LocalFile{io: io} {:ok, file} = Exfile.Backend.upload(store2_backend(), local_file) # rewind the io because it's been read in the upload process above :file.position(io, :bof) {:ok, new_file} = cast(TestFile, "exfile://store2/" <> file.id) assert %Exfile.File{} = new_file assert new_file.backend == backend() refute new_file.id == file.id assert file_contents_equal(new_file, file_contents) end test "loading a binary from the database returns a valid Exfile.File", %{store_file: file} do assert {:ok, ^file} = load(TestFile, file.id) end test "dumping an Exfile.File returns the correct file URI", %{cache_file: file} do assert {:ok, Exfile.File.uri(file)} == dump(TestFile, file) end test "the type is :string", _ do assert TestFile.type == :string end test "upload!/1 takes an Exfile.File in the cache backend and uploads it to the store backend", %{cache_file: file} do assert file.backend == backend() assert {:ok, store_file} = TestFile.upload!(file) assert store_file.backend == store_backend() end end
35.421053
122
0.694156
e82c06bb6d0953c6adf78c11a179c42249f6b456
1,054
ex
Elixir
flights/test/support/conn_case.ex
sifxtreme/phoenix-flights
afc8724e9a9d6f9158305d57df8132327943894d
[ "MIT" ]
null
null
null
flights/test/support/conn_case.ex
sifxtreme/phoenix-flights
afc8724e9a9d6f9158305d57df8132327943894d
[ "MIT" ]
null
null
null
flights/test/support/conn_case.ex
sifxtreme/phoenix-flights
afc8724e9a9d6f9158305d57df8132327943894d
[ "MIT" ]
null
null
null
defmodule Flights.ConnCase do @moduledoc """ This module defines the test case to be used by tests that require setting up a connection. Such tests rely on `Phoenix.ConnTest` and also imports other functionality to make it easier to build and query models. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do # Import conveniences for testing with connections use Phoenix.ConnTest alias Flights.Repo import Ecto import Ecto.Changeset import Ecto.Query, only: [from: 1, from: 2] import Flights.Router.Helpers # The default endpoint for testing @endpoint Flights.Endpoint end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(Flights.Repo, []) end {:ok, conn: Phoenix.ConnTest.conn()} end end
24.511628
66
0.703036
e82c2794b6093e1714a7d2c456e160ec56e6d30b
1,806
exs
Elixir
test/astarte_core/device_test.exs
Pavinati/astarte_core
dd37ddd2b1bdcef0b1474be9c81d9a0efa4cda81
[ "Apache-2.0" ]
16
2018-02-02T14:07:10.000Z
2021-02-03T13:57:30.000Z
test/astarte_core/device_test.exs
Pavinati/astarte_core
dd37ddd2b1bdcef0b1474be9c81d9a0efa4cda81
[ "Apache-2.0" ]
62
2019-03-14T15:52:12.000Z
2022-03-22T10:34:56.000Z
test/astarte_core/device_test.exs
Pavinati/astarte_core
dd37ddd2b1bdcef0b1474be9c81d9a0efa4cda81
[ "Apache-2.0" ]
9
2018-02-02T09:55:06.000Z
2021-03-04T15:15:08.000Z
defmodule Astarte.Core.DeviceTest do use ExUnit.Case alias Astarte.Core.Device @invalid_characters_device_id "notbase64§" @short_device_id "uTSXEtcgQ3" @regular_device_id "74Zp9OoNRc-Vsi5RcsIf4A" @long_device_id "uTSXEtcgQ3qczX3ixpZeFrWgx0kxk0bfrUzkqTIhCck" test "invalid device ids decoding fails" do assert {:error, :invalid_device_id} = Device.decode_device_id(@invalid_characters_device_id) assert {:error, :invalid_device_id} = Device.decode_device_id(@short_device_id) end test "long device ids decoding fails with no options" do assert {:error, :extended_id_not_allowed} = Device.decode_device_id(@long_device_id) end test "regular device id decoding succeeds" do assert {:ok, _device_id} = Device.decode_device_id(@regular_device_id) end test "long device id decoding succeeds with allow_extended_id" do assert {:ok, _device_id} = Device.decode_device_id(@long_device_id, allow_extended_id: true) end test "extended device id decoding succeeds with long id" do assert {:ok, _device_id, _extended_device_id} = Device.decode_extended_device_id(@long_device_id) end test "extended device id decoding gives an empty extended id on regular id" do assert {:ok, _device_id, ""} = Device.decode_extended_device_id(@regular_device_id) end test "encoding fails with device id not 128 bit long" do assert {:ok, device_id, extended_id} = Device.decode_extended_device_id(@long_device_id) long_id = device_id <> extended_id assert_raise FunctionClauseError, fn -> Device.encode_device_id(long_id) end end test "encoding/decoding roundtrip" do assert {:ok, device_id} = Device.decode_device_id(@regular_device_id) assert Device.encode_device_id(device_id) == @regular_device_id end end
35.411765
96
0.762458
e82c2d49642e7a7553cf596225a1ce33e0280093
613
ex
Elixir
lib/bex/application.ex
ckampfe/bex
cfbfdd600e03ebb9ef60c3f2f8cb61b0640455ff
[ "BSD-3-Clause" ]
null
null
null
lib/bex/application.ex
ckampfe/bex
cfbfdd600e03ebb9ef60c3f2f8cb61b0640455ff
[ "BSD-3-Clause" ]
null
null
null
lib/bex/application.ex
ckampfe/bex
cfbfdd600e03ebb9ef60c3f2f8cb61b0640455ff
[ "BSD-3-Clause" ]
null
null
null
defmodule Bex.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application @impl true def start(_type, _args) do children = [ # Starts a worker by calling: Bex.Worker.start_link(arg) # {Bex.Worker, arg} {Registry, keys: :unique, name: Bex.Registry}, {Bex.AllSupervisor, []} ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Bex.Supervisor] Supervisor.start_link(children, opts) end end
26.652174
62
0.683524
e82c6e20013c2554bd10dbea74ca557c7bee43d8
61
ex
Elixir
lib/hnlive_web/views/layout_view.ex
josefrichter/hnlive
5c9953835e447c98e65e9690655f6d602bd18d32
[ "MIT" ]
4
2020-05-31T11:53:17.000Z
2021-05-25T11:30:24.000Z
lib/hnlive_web/views/layout_view.ex
josefrichter/hnlive
5c9953835e447c98e65e9690655f6d602bd18d32
[ "MIT" ]
1
2020-05-31T13:08:02.000Z
2020-05-31T13:08:02.000Z
lib/hnlive_web/views/layout_view.ex
josefrichter/hnlive
5c9953835e447c98e65e9690655f6d602bd18d32
[ "MIT" ]
1
2020-05-31T11:53:43.000Z
2020-05-31T11:53:43.000Z
defmodule HNLiveWeb.LayoutView do use HNLiveWeb, :view end
15.25
33
0.803279
e82c81d91622e29e1de60cba813d3a7fee231945
2,490
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/disk.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/disk.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/disk.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.Dataflow.V1b3.Model.Disk do @moduledoc """ Describes the data disk used by a workflow job. ## Attributes - diskType (String): Disk storage type, as defined by Google Compute Engine. This must be a disk type appropriate to the project and zone in which the workers will run. If unknown or unspecified, the service will attempt to choose a reasonable default. For example, the standard persistent disk type is a resource name typically ending in \&quot;pd-standard\&quot;. If SSD persistent disks are available, the resource name typically ends with \&quot;pd-ssd\&quot;. The actual valid values are defined the Google Compute Engine API, not by the Cloud Dataflow API; consult the Google Compute Engine documentation for more information about determining the set of available disk types for a particular project and zone. Google Compute Engine Disk types are local to a particular project in a particular zone, and so the resource name will typically look something like this: compute.googleapis.com/projects/project-id/zones/zone/diskTypes/pd-standard Defaults to: `null`. - mountPoint (String): Directory in a VM where disk is mounted. Defaults to: `null`. - sizeGb (Integer): Size of disk in GB. If zero or unspecified, the service will attempt to choose a reasonable default. Defaults to: `null`. """ defstruct [ :"diskType", :"mountPoint", :"sizeGb" ] end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.Disk do def decode(value, _options) do value end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.Disk do def encode(value, options) do GoogleApi.Dataflow.V1b3.Deserializer.serialize_non_nil(value, options) end end
49.8
977
0.763454
e82cd83ee8166bcaa4feffc0a0b1e22144662982
9,494
ex
Elixir
lib/aws/generated/transcribe.ex
benmmari/aws-elixir
b97477498a9e8ba0d46a09255302d88c6a1c8573
[ "Apache-2.0" ]
null
null
null
lib/aws/generated/transcribe.ex
benmmari/aws-elixir
b97477498a9e8ba0d46a09255302d88c6a1c8573
[ "Apache-2.0" ]
null
null
null
lib/aws/generated/transcribe.ex
benmmari/aws-elixir
b97477498a9e8ba0d46a09255302d88c6a1c8573
[ "Apache-2.0" ]
null
null
null
# WARNING: DO NOT EDIT, AUTO-GENERATED CODE! # See https://github.com/aws-beam/aws-codegen for more details. defmodule AWS.Transcribe do @moduledoc """ Operations and objects for transcribing speech to text. """ @doc """ Creates a new custom language model. Use Amazon S3 prefixes to provide the location of your input files. The time it takes to create your model depends on the size of your training data. """ def create_language_model(client, input, options \\ []) do request(client, "CreateLanguageModel", input, options) end @doc """ Creates a new custom vocabulary that you can use to change how Amazon Transcribe Medical transcribes your audio file. """ def create_medical_vocabulary(client, input, options \\ []) do request(client, "CreateMedicalVocabulary", input, options) end @doc """ Creates a new custom vocabulary that you can use to change the way Amazon Transcribe handles transcription of an audio file. """ def create_vocabulary(client, input, options \\ []) do request(client, "CreateVocabulary", input, options) end @doc """ Creates a new vocabulary filter that you can use to filter words, such as profane words, from the output of a transcription job. """ def create_vocabulary_filter(client, input, options \\ []) do request(client, "CreateVocabularyFilter", input, options) end @doc """ Deletes a custom language model using its name. """ def delete_language_model(client, input, options \\ []) do request(client, "DeleteLanguageModel", input, options) end @doc """ Deletes a transcription job generated by Amazon Transcribe Medical and any related information. """ def delete_medical_transcription_job(client, input, options \\ []) do request(client, "DeleteMedicalTranscriptionJob", input, options) end @doc """ Deletes a vocabulary from Amazon Transcribe Medical. """ def delete_medical_vocabulary(client, input, options \\ []) do request(client, "DeleteMedicalVocabulary", input, options) end @doc """ Deletes a previously submitted transcription job along with any other generated results such as the transcription, models, and so on. """ def delete_transcription_job(client, input, options \\ []) do request(client, "DeleteTranscriptionJob", input, options) end @doc """ Deletes a vocabulary from Amazon Transcribe. """ def delete_vocabulary(client, input, options \\ []) do request(client, "DeleteVocabulary", input, options) end @doc """ Removes a vocabulary filter. """ def delete_vocabulary_filter(client, input, options \\ []) do request(client, "DeleteVocabularyFilter", input, options) end @doc """ Gets information about a single custom language model. Use this information to see details about the language model in your AWS account. You can also see whether the base language model used to create your custom language model has been updated. If Amazon Transcribe has updated the base model, you can create a new custom language model using the updated base model. If the language model wasn't created, you can use this operation to understand why Amazon Transcribe couldn't create it. """ def describe_language_model(client, input, options \\ []) do request(client, "DescribeLanguageModel", input, options) end @doc """ Returns information about a transcription job from Amazon Transcribe Medical. To see the status of the job, check the `TranscriptionJobStatus` field. If the status is `COMPLETED`, the job is finished. You find the results of the completed job in the `TranscriptFileUri` field. """ def get_medical_transcription_job(client, input, options \\ []) do request(client, "GetMedicalTranscriptionJob", input, options) end @doc """ Retrieves information about a medical vocabulary. """ def get_medical_vocabulary(client, input, options \\ []) do request(client, "GetMedicalVocabulary", input, options) end @doc """ Returns information about a transcription job. To see the status of the job, check the `TranscriptionJobStatus` field. If the status is `COMPLETED`, the job is finished and you can find the results at the location specified in the `TranscriptFileUri` field. If you enable content redaction, the redacted transcript appears in `RedactedTranscriptFileUri`. """ def get_transcription_job(client, input, options \\ []) do request(client, "GetTranscriptionJob", input, options) end @doc """ Gets information about a vocabulary. """ def get_vocabulary(client, input, options \\ []) do request(client, "GetVocabulary", input, options) end @doc """ Returns information about a vocabulary filter. """ def get_vocabulary_filter(client, input, options \\ []) do request(client, "GetVocabularyFilter", input, options) end @doc """ Provides more information about the custom language models you've created. You can use the information in this list to find a specific custom language model. You can then use the operation to get more information about it. """ def list_language_models(client, input, options \\ []) do request(client, "ListLanguageModels", input, options) end @doc """ Lists medical transcription jobs with a specified status or substring that matches their names. """ def list_medical_transcription_jobs(client, input, options \\ []) do request(client, "ListMedicalTranscriptionJobs", input, options) end @doc """ Returns a list of vocabularies that match the specified criteria. If you don't enter a value in any of the request parameters, returns the entire list of vocabularies. """ def list_medical_vocabularies(client, input, options \\ []) do request(client, "ListMedicalVocabularies", input, options) end @doc """ Lists transcription jobs with the specified status. """ def list_transcription_jobs(client, input, options \\ []) do request(client, "ListTranscriptionJobs", input, options) end @doc """ Returns a list of vocabularies that match the specified criteria. If no criteria are specified, returns the entire list of vocabularies. """ def list_vocabularies(client, input, options \\ []) do request(client, "ListVocabularies", input, options) end @doc """ Gets information about vocabulary filters. """ def list_vocabulary_filters(client, input, options \\ []) do request(client, "ListVocabularyFilters", input, options) end @doc """ Starts a batch job to transcribe medical speech to text. """ def start_medical_transcription_job(client, input, options \\ []) do request(client, "StartMedicalTranscriptionJob", input, options) end @doc """ Starts an asynchronous job to transcribe speech to text. """ def start_transcription_job(client, input, options \\ []) do request(client, "StartTranscriptionJob", input, options) end @doc """ Updates a vocabulary with new values that you provide in a different text file from the one you used to create the vocabulary. The `UpdateMedicalVocabulary` operation overwrites all of the existing information with the values that you provide in the request. """ def update_medical_vocabulary(client, input, options \\ []) do request(client, "UpdateMedicalVocabulary", input, options) end @doc """ Updates an existing vocabulary with new values. The `UpdateVocabulary` operation overwrites all of the existing information with the values that you provide in the request. """ def update_vocabulary(client, input, options \\ []) do request(client, "UpdateVocabulary", input, options) end @doc """ Updates a vocabulary filter with a new list of filtered words. """ def update_vocabulary_filter(client, input, options \\ []) do request(client, "UpdateVocabularyFilter", input, options) end @spec request(AWS.Client.t(), binary(), map(), list()) :: {:ok, map() | nil, map()} | {:error, term()} defp request(client, action, input, options) do client = %{client | service: "transcribe"} host = build_host("transcribe", client) url = build_url(host, client) headers = [ {"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}, {"X-Amz-Target", "Transcribe.#{action}"} ] payload = encode!(client, input) headers = AWS.Request.sign_v4(client, "POST", url, headers, payload) post(client, url, payload, headers, options) end defp post(client, url, payload, headers, options) do case AWS.Client.request(client, :post, url, payload, headers, options) do {:ok, %{status_code: 200, body: body} = response} -> body = if body != "", do: decode!(client, body) {:ok, body, response} {:ok, response} -> {:error, {:unexpected_response, response}} error = {:error, _reason} -> error end end defp build_host(_endpoint_prefix, %{region: "local", endpoint: endpoint}) do endpoint end defp build_host(_endpoint_prefix, %{region: "local"}) do "localhost" end defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do "#{endpoint_prefix}.#{region}.#{endpoint}" end defp build_url(host, %{:proto => proto, :port => port}) do "#{proto}://#{host}:#{port}/" end defp encode!(client, payload) do AWS.Client.encode!(client, payload, :json) end defp decode!(client, payload) do AWS.Client.decode!(client, payload, :json) end end
33.547703
78
0.706341
e82ce380f05ab3b44f5371977621fdfd866165a9
2,146
exs
Elixir
test/type/type_bitstring/subtype_test.exs
kianmeng/mavis
6ba154efdfadcce1aca92ac735dadb209380c25b
[ "MIT" ]
null
null
null
test/type/type_bitstring/subtype_test.exs
kianmeng/mavis
6ba154efdfadcce1aca92ac735dadb209380c25b
[ "MIT" ]
null
null
null
test/type/type_bitstring/subtype_test.exs
kianmeng/mavis
6ba154efdfadcce1aca92ac735dadb209380c25b
[ "MIT" ]
null
null
null
defmodule TypeTest.TypeBitstring.SubtypeTest do use ExUnit.Case, async: true @moduletag :subtype import Type, only: [builtin: 1] use Type.Operators alias Type.Bitstring @empty_bitstring %Bitstring{size: 0, unit: 0} @basic_bitstring %Bitstring{size: 0, unit: 1} @basic_binary %Bitstring{size: 0, unit: 8} describe "the empty bitstring" do test "is a subtype of itself and any" do assert @empty_bitstring in @empty_bitstring assert @empty_bitstring in builtin(:any) end test "is a subtype of any bitstring with size 0" do assert @empty_bitstring in @basic_bitstring assert @empty_bitstring in @basic_binary end test "is a subtype of appropriate unions" do assert @empty_bitstring in (@empty_bitstring <|> builtin(:atom)) assert @empty_bitstring in (@basic_bitstring <|> builtin(:atom)) assert @empty_bitstring in (@basic_binary <|> builtin(:atom)) end test "is not a subtype of orthogonal types" do refute @empty_bitstring in (builtin(:atom) <|> builtin(:integer)) end test "is not a subtype of any bitstring that has size" do refute @empty_bitstring in %Bitstring{size: 1, unit: 0} refute @empty_bitstring in %Bitstring{size: 1, unit: 1} refute @empty_bitstring in %Bitstring{size: 8, unit: 8} end end describe "the basic binary" do test "is a subtype of itself, basic bitstring, and more granular bitstrings" do assert @basic_binary in @basic_binary assert @basic_binary in @basic_bitstring assert @basic_binary in %Bitstring{size: 0, unit: 4} end end describe "a binary with a size" do test "is a subtype of basic binary, and basic bitstring" do assert %Bitstring{size: 64, unit: 0} in @basic_binary ## <- binary constant assert %Bitstring{size: 32, unit: 8} in @basic_binary assert %Bitstring{size: 7, unit: 3} in @basic_bitstring ## <- YOLO end test "is not a subtype when there is a strange size" do refute %Bitstring{size: 31, unit: 0} in @basic_binary refute %Bitstring{size: 4, unit: 8} in @basic_binary end end end
32.515152
83
0.685461
e82cfe0cc01c394319529b4ea68e935abd5545f1
1,975
ex
Elixir
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/account_permission_groups_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/account_permission_groups_list_response.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/dfa_reporting/lib/google_api/dfa_reporting/v33/model/account_permission_groups_list_response.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.DFAReporting.V33.Model.AccountPermissionGroupsListResponse do @moduledoc """ Account Permission Group List Response ## Attributes * `accountPermissionGroups` (*type:* `list(GoogleApi.DFAReporting.V33.Model.AccountPermissionGroup.t)`, *default:* `nil`) - Account permission group collection. * `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermissionGroupsListResponse". """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accountPermissionGroups => list(GoogleApi.DFAReporting.V33.Model.AccountPermissionGroup.t()), :kind => String.t() } field(:accountPermissionGroups, as: GoogleApi.DFAReporting.V33.Model.AccountPermissionGroup, type: :list ) field(:kind) end defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V33.Model.AccountPermissionGroupsListResponse do def decode(value, options) do GoogleApi.DFAReporting.V33.Model.AccountPermissionGroupsListResponse.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V33.Model.AccountPermissionGroupsListResponse do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.909091
171
0.752405
e82d3915c44e03d1f72d7f9b25ae50959fc0fa3d
1,605
exs
Elixir
api_user/config/dev.exs
roberttgt/Elixir-Course
39a0bfc37125703d08114b54a6efac07f7ab7488
[ "MIT" ]
null
null
null
api_user/config/dev.exs
roberttgt/Elixir-Course
39a0bfc37125703d08114b54a6efac07f7ab7488
[ "MIT" ]
null
null
null
api_user/config/dev.exs
roberttgt/Elixir-Course
39a0bfc37125703d08114b54a6efac07f7ab7488
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :api_user, ApiUserWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime # Configure your database config :api_user, ApiUser.Repo, username: "postgres", password: "postgres", database: "user_api_dev", hostname: "localhost", pool_size: 10
28.157895
68
0.722118
e82d4faca9d09f4762a7d120b3e5d38f20972a29
746
ex
Elixir
lib/wishlist/wishlists/gift.ex
egutter/wishlist
af7b71c96ef9efded708c5ecfe3bab5a00c0761e
[ "MIT" ]
null
null
null
lib/wishlist/wishlists/gift.ex
egutter/wishlist
af7b71c96ef9efded708c5ecfe3bab5a00c0761e
[ "MIT" ]
null
null
null
lib/wishlist/wishlists/gift.ex
egutter/wishlist
af7b71c96ef9efded708c5ecfe3bab5a00c0761e
[ "MIT" ]
null
null
null
defmodule Wishlist.Wishlists.Gift do use Ecto.Schema import Ecto.Changeset alias Wishlist.Wishlists.Event alias Wishlist.Wishlists.Assignment schema "gifts" do field :image, :string field :link, :string field :link_2, :string field :link_3, :string field :name, :string field :description, :string field :price, :decimal belongs_to :event, Event has_one :assignment, Assignment timestamps() end @doc false def changeset(gift, attrs) do gift |> cast(attrs, [:name, :price, :image, :link, :link_2, :link_3, :description, :event_id]) |> validate_required([:name, :price, :image, :description, :event_id]) end def assigned?(a_gift) do a_gift.assignment != nil end end
23.3125
93
0.676944
e82dc683ee57ddcfe6f33b2486f603426d1d5e58
651
ex
Elixir
apps/summoner_web/lib/summoner_web_web/controllers/tags_controller.ex
making3/summoner_alerts
fda7a43cab0e2022a90e8fe3d766f95628d9ac00
[ "MIT" ]
null
null
null
apps/summoner_web/lib/summoner_web_web/controllers/tags_controller.ex
making3/summoner_alerts
fda7a43cab0e2022a90e8fe3d766f95628d9ac00
[ "MIT" ]
null
null
null
apps/summoner_web/lib/summoner_web_web/controllers/tags_controller.ex
making3/summoner_alerts
fda7a43cab0e2022a90e8fe3d766f95628d9ac00
[ "MIT" ]
null
null
null
defmodule SummonerWebWeb.TagsController do use SummonerWebWeb, :controller import Ecto.Query alias SummonerBackend.Tag alias SummonerBackend.TagGroup alias SummonerBackend.Repo def create(conn, params) do tag_group = Repo.get(TagGroup, params["group_id"]) tag_changeset = Ecto.build_assoc(tag_group, :tags, name: params["name"]) {:ok, tag} = Repo.insert(tag_changeset) IO.inspect tag render(conn, tag: tag) end def delete(conn, params) do # TODO: Delete tag_threads first (or cascade delete? idk) {:ok, _ } = Tag |> Repo.get(params["id"]) |> Repo.delete() send_resp(conn, :ok, "") end end
25.038462
76
0.6851
e82e10f09019df794df9a62587c9803e489969d3
1,064
exs
Elixir
mix.exs
exredorg/exred_node_trigger
f4c87aeb15e11bf2700e7c767b1a0d4caba3ec31
[ "MIT" ]
null
null
null
mix.exs
exredorg/exred_node_trigger
f4c87aeb15e11bf2700e7c767b1a0d4caba3ec31
[ "MIT" ]
null
null
null
mix.exs
exredorg/exred_node_trigger
f4c87aeb15e11bf2700e7c767b1a0d4caba3ec31
[ "MIT" ]
null
null
null
defmodule Exred.Node.Trigger.Mixfile do use Mix.Project @description "Triggers execution of other nodes by sending a configurable message" @version File.read!("VERSION") |> String.trim() def project do [ app: :exred_node_trigger, version: @version, elixir: "~> 1.5", start_permanent: Mix.env() == :prod, description: @description, package: package(), deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:exred_nodeprototype, "~> 0.2"}, {:ex_doc, "~> 0.19.0", only: :dev, runtime: false} ] end defp package do %{ licenses: ["MIT"], maintainers: ["Zsolt Keszthelyi"], links: %{ "GitHub" => "https://github.com/exredorg/exred_node_trigger.git", "Exred" => "http://exred.org" }, files: ["lib", "mix.exs", "README.md", "LICENSE", "VERSION"] } end end
23.130435
84
0.588346
e82e1756432e4400fd174937e162969b0c703815
11,230
ex
Elixir
deps/ex_doc/lib/ex_doc/formatter/html/autolink.ex
londoed/cards
915a259073067c6e35ebe68d11313d2a78a62a10
[ "Apache-2.0" ]
null
null
null
deps/ex_doc/lib/ex_doc/formatter/html/autolink.ex
londoed/cards
915a259073067c6e35ebe68d11313d2a78a62a10
[ "Apache-2.0" ]
null
null
null
deps/ex_doc/lib/ex_doc/formatter/html/autolink.ex
londoed/cards
915a259073067c6e35ebe68d11313d2a78a62a10
[ "Apache-2.0" ]
null
null
null
defmodule ExDoc.Formatter.HTML.Autolink do import ExDoc.Formatter.HTML.Templates, only: [h: 1, enc_h: 1] @moduledoc """ Conveniences for autolinking locals, types and more. """ @elixir_docs "http://elixir-lang.org/docs/stable/" @erlang_docs "http://www.erlang.org/doc/man/" @doc """ Receives a list of module nodes and autolink all docs and typespecs. """ def all(modules) do aliases = Enum.map modules, &(&1.module) modules |> Enum.map(&Task.async(fn -> process_module(&1, modules, aliases) end)) |> Enum.map(&Task.await(&1, :infinity)) end defp process_module(module, modules, aliases) do module |> all_docs(modules) |> all_typespecs(aliases) end defp module_to_string(module) do inspect module.module end defp all_docs(module, modules) do locals = Enum.map module.docs, &(doc_prefix(&1) <> &1.id) moduledoc = if module.moduledoc do module.moduledoc |> local_doc(locals) |> project_doc(modules, module.id) end docs = for node <- module.docs do doc = if node.doc do node.doc |> local_doc(locals) |> project_doc(modules, module.id) end %{node | doc: doc} end typedocs = for node <- module.typespecs do doc = if node.doc do node.doc |> local_doc(locals) |> project_doc(modules, module.id) end %{node | doc: doc} end %{module | moduledoc: moduledoc, docs: docs, typespecs: typedocs} end defp all_typespecs(module, aliases) do locals = Enum.map module.typespecs, fn %ExDoc.TypeNode{name: name, arity: arity} -> { name, arity } end typespecs = for typespec <- module.typespecs do %{typespec | spec: typespec(typespec.spec, locals, aliases)} end docs = for node <- module.docs do %{node | specs: Enum.map(node.specs, &typespec(&1, locals, aliases))} end %{module | typespecs: typespecs, docs: docs} end @doc """ Converts the given `ast` to string while linking the locals given by `typespecs` as HTML. """ def typespec({:when, _, [{:::, _, [left, {:|, _, _} = center]}, right]} = ast, typespecs, aliases) do if short_typespec?(ast) do typespec_to_string(ast, typespecs, aliases) else typespec_to_string(left, typespecs, aliases) <> " ::\n " <> typespec_with_new_line(center, typespecs, aliases) <> " when " <> String.slice(typespec_to_string(right, typespecs, aliases), 1..-2) end end def typespec({:::, _, [left, {:|, _, _} = center]} = ast, typespecs, aliases) do if short_typespec?(ast) do typespec_to_string(ast, typespecs, aliases) else typespec_to_string(left, typespecs, aliases) <> " ::\n " <> typespec_with_new_line(center, typespecs, aliases) end end def typespec(other, typespecs, aliases) do typespec_to_string(other, typespecs, aliases) end defp typespec_with_new_line({:|, _, [left, right]}, typespecs, aliases) do typespec_to_string(left, typespecs, aliases) <> " |\n " <> typespec_with_new_line(right, typespecs, aliases) end defp typespec_with_new_line(other, typespecs, aliases) do typespec_to_string(other, typespecs, aliases) end defp typespec_to_string(ast, typespecs, aliases) do Macro.to_string(ast, fn {name, _, args}, string when is_atom(name) and is_list(args) -> string = strip_parens(string, args) arity = length(args) if { name, arity } in typespecs do n = enc_h("#{name}") ~s[<a href="#t:#{n}/#{arity}">#{h(string)}</a>] else string end {{ :., _, [alias, name] }, _, args}, string when is_atom(name) and is_list(args) -> string = strip_parens(string, args) alias = expand_alias(alias) if source = get_source(alias, aliases) do n = enc_h("#{name}") ~s[<a href="#{source}#{enc_h(inspect alias)}.html#t:#{n}/#{length(args)}">#{h(string)}</a>] else string end _, string -> string end) end defp short_typespec?(ast) do byte_size(Macro.to_string(ast)) < 60 end defp strip_parens(string, []) do if :binary.last(string) == ?) do :binary.part(string, 0, byte_size(string)-2) else string end end defp strip_parens(string, _), do: string defp expand_alias({:__aliases__, _, [h|t]}) when is_atom(h), do: Module.concat([h|t]) defp expand_alias(atom) when is_atom(atom), do: atom defp expand_alias(_), do: nil defp get_source(alias, aliases) do cond do is_nil(alias) -> nil alias in aliases -> "" dir = from_elixir(alias) -> @elixir_docs <> dir <> "/" true -> nil end end defp from_elixir(alias) do alias_ebin = alias_ebin(alias) if String.starts_with?(alias_ebin, elixir_ebin()) do alias_ebin |> Path.dirname() |> Path.dirname() |> Path.basename() end end defp alias_ebin(alias) do case :code.where_is_file('#{alias}.beam') do :non_existing -> "" path -> List.to_string(path) end end defp elixir_ebin do case :code.where_is_file('Elixir.Kernel.beam') do :non_existing -> [0] path -> path |> Path.dirname() |> Path.dirname() |> Path.dirname() end end @doc """ Create links to locally defined functions, specified in `locals` as a list of `fun/arity` strings. Ignores functions which are already wrapped in markdown url syntax, e.g. `[test/1](url)`. If the function doesn't touch the leading or trailing `]`, e.g. `[my link link/1 is here](url)`, the fun/arity will get translated to the new href of the function. """ def local_doc(bin, locals) when is_binary(bin) do ~r{(?<!\[)`\s*(([a-z\d_!\\?>\\|=&<!~+\\.\\+*^@-]+)/\d+)\s*`(?!\])} |> Regex.scan(bin) |> Enum.uniq() |> List.flatten() |> Enum.filter(&(&1 in locals)) |> Enum.reduce(bin, fn (x, acc) -> {prefix, _, function_name, arity} = split_function(x) escaped = Regex.escape(x) Regex.replace(~r/(?<!\[)`(\s*#{escaped}\s*)`(?!\])/, acc, "[`#{function_name}/#{arity}`](##{prefix}#{enc_h function_name}/#{arity})") end) end @doc """ Creates links to modules and functions defined in the project. """ def project_doc(bin, modules, module_id \\ nil) when is_binary(bin) do project_funs = for m <- modules, d <- m.docs, do: doc_prefix(d) <> m.id <> "." <> d.id project_modules = modules |> Enum.map(&module_to_string/1) |> Enum.uniq() bin |> project_functions(project_funs) |> project_modules(project_modules, module_id) |> erlang_functions() end defp doc_prefix(%{type: c}) when c in [:callback, :macrocallback], do: "c:" defp doc_prefix(%{type: _}), do: "" @doc """ Create links to functions defined in the project, specified in `project_funs` as a list of `Module.fun/arity` tuples. Ignores functions which are already wrapped in markdown url syntax, e.g. `[Module.test/1](url)`. If the function doesn't touch the leading or trailing `]`, e.g. `[my link Module.link/1 is here](url)`, the Module.fun/arity will get translated to the new href of the function. """ def project_functions(bin, project_funs) when is_binary(bin) do ~r{(?<!\[)`\s*((c:)?(([A-Z][A-Za-z]+)\.)+([a-z_!\?>\|=&<!~+\.\+*^@-]+)/\d+)\s*`(?!\])} |> Regex.scan(bin) |> Enum.uniq() |> List.flatten() |> Enum.filter(&(&1 in project_funs)) |> Enum.reduce(bin, fn (x, acc) -> {prefix, mod_str, function_name, arity} = split_function(x) escaped = Regex.escape(x) Regex.replace(~r/(?<!\[)`(\s*#{escaped}\s*)`(?!\])/, acc, "[`#{mod_str}.#{function_name}/#{arity}`](#{mod_str}.html##{prefix}#{enc_h function_name}/#{arity})") end) end @doc """ Create links to modules defined in the project, specified in `modules` as a list. Ignores modules which are already wrapped in markdown url syntax, e.g. `[Module](url)`. If the module name doesn't touch the leading or trailing `]`, e.g. `[my link Module is here](url)`, the Module will get translated to the new href of the module. """ def project_modules(bin, modules, module_id \\ nil) when is_binary(bin) do ~r{(?<!\[)`\s*(([A-Z][A-Za-z]+\.?)+)\s*`(?!\])} |> Regex.scan(bin) |> Enum.uniq() |> List.flatten() |> Enum.filter(&(&1 in modules)) |> Enum.reduce(bin, fn (x, acc) -> escaped = Regex.escape(x) suffix = if module_id && x == module_id do ".html#content" else ".html" end Regex.replace(~r/(?<!\[)`(\s*#{escaped}\s*)`(?!\])/, acc, "[`\\1`](\\1" <> suffix <> ")") end) end defp split_function("c:" <> bin) do {"", mod, fun, arity} = split_function(bin) {"c:", mod, fun, arity} end defp split_function(bin) do [modules, arity] = String.split(bin, "/") {mod, name} = modules |> String.replace(~r{([^\.])\.}, "\\1 ") # this handles the case of the ".." function |> String.split(" ") |> Enum.split(-1) {"", Enum.join(mod, "."), hd(name), arity} end @doc """ Create links to Erlang functions in code blocks. Only links modules that are in the Erlang distribution `lib_dir` and only link functions in those modules that export a function of the same name and arity. Ignores functions which are already wrapped in markdown url syntax, e.g. `[:module.test/1](url)`. If the function doesn't touch the leading or trailing `]`, e.g. `[my link :module.link/1 is here](url)`, the :module.fun/arity will get translated to the new href of the function. """ def erlang_functions(bin) when is_binary(bin) do lib_dir = erlang_lib_dir() ~r{(?<!\[)`\s*:([a-z_]+\.[0-9a-zA-Z_!\\?]+/\d+)\s*`(?!\])} |> Regex.scan(bin) |> Enum.uniq() |> List.flatten() |> Enum.filter(&valid_erlang_beam?(&1, lib_dir)) |> Enum.filter(&module_exports_function?/1) |> Enum.reduce(bin, fn (x, acc) -> {_, mod_str, function_name, arity} = split_function(x) escaped = Regex.escape(x) Regex.replace(~r/(?<!\[)`(\s*:#{escaped}\s*)`(?!\])/, acc, "[`\\1`](#{@erlang_docs}#{mod_str}.html##{function_name}-#{arity})") end) end defp valid_erlang_beam?(function_str, lib_dir) do { _, mod_str, _function_name, _arity } = split_function(function_str) '#{mod_str}.beam' |> :code.where_is_file |> on_lib_path?(lib_dir) end defp on_lib_path?(:non_existing, _base_path), do: false defp on_lib_path?(beam_path, base_path) do beam_path |> Path.expand() |> String.starts_with?(base_path) end defp erlang_lib_dir do :code.lib_dir |> Path.expand() end defp module_exports_function?(function_str) do {_, mod_str, function_name, arity_str} = split_function(function_str) module = String.to_atom(mod_str) function_name = String.to_atom(function_name) {arity, _} = Integer.parse(arity_str) exports = module.module_info(:exports) Enum.member? exports, {function_name, arity} end end
31.368715
112
0.602315
e82e1ed0af2c7d758da5472126dea1fbab184f05
725
ex
Elixir
lib/blog_post_api_web/gettext.ex
dannielb/blog-post-api
214520beb57164375bc6596e85cbc42be67c0fb9
[ "MIT" ]
null
null
null
lib/blog_post_api_web/gettext.ex
dannielb/blog-post-api
214520beb57164375bc6596e85cbc42be67c0fb9
[ "MIT" ]
null
null
null
lib/blog_post_api_web/gettext.ex
dannielb/blog-post-api
214520beb57164375bc6596e85cbc42be67c0fb9
[ "MIT" ]
null
null
null
defmodule BlogPostApiWeb.Gettext do @moduledoc """ A module providing Internationalization with a gettext-based API. By using [Gettext](https://hexdocs.pm/gettext), your module gains a set of macros for translations, for example: import BlogPostApiWeb.Gettext # Simple translation gettext("Here is the string to translate") # Plural translation ngettext("Here is the string to translate", "Here are the strings to translate", 3) # Domain-based translation dgettext("errors", "Here is the error message to translate") See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage. """ use Gettext, otp_app: :blog_post_api end
29
72
0.684138
e82e26964ee281a4861c9af9d77717eadec0045e
1,197
exs
Elixir
mix.exs
MatthewNielsen27/memo_generator
d11f6a7d6c2da3bbc21895c7ee8849f089b05492
[ "MIT" ]
null
null
null
mix.exs
MatthewNielsen27/memo_generator
d11f6a7d6c2da3bbc21895c7ee8849f089b05492
[ "MIT" ]
null
null
null
mix.exs
MatthewNielsen27/memo_generator
d11f6a7d6c2da3bbc21895c7ee8849f089b05492
[ "MIT" ]
null
null
null
defmodule MemoGenerator.MixProject do use Mix.Project def project do [ app: :memo_generator, version: "0.1.4", elixir: "~> 1.7", start_permanent: Mix.env() == :prod, deps: deps(), package: package(), description: description(), source_url: "https://github.com/azohra/memo_generator", test_coverage: [tool: ExCoveralls] ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger], applications: [:httpoison], applications: [:timex] ] end defp description() do "Generates a memo in Markdown format based on your team's trello boards" end # Run "mix help deps" to learn about dependencies. defp deps do [ {:ex_doc, ">= 0.0.0", only: :dev}, {:httpoison, "~> 1.3"}, {:poison, "~> 3.0"}, {:excoveralls, "~> 0.10.1"}, {:tesla, "~> 1.1"}, {:timex, "~> 3.0"}, {:credo, "~> 0.10.2"} ] end defp package() do [ licenses: ["MIT"], links: %{ "GitHub" => "https://github.com/azohra/memo_generator", "Org" => "https://azohra.com/" } ] end end
22.166667
76
0.548872
e82e5850ae5c130bd8d08523139dd4846878281c
2,568
exs
Elixir
apps/andi/runtime.exs
msomji/smartcitiesdata
fc96abc1ef1306f7af6bd42bbcb4ed041a6d922c
[ "Apache-2.0" ]
null
null
null
apps/andi/runtime.exs
msomji/smartcitiesdata
fc96abc1ef1306f7af6bd42bbcb4ed041a6d922c
[ "Apache-2.0" ]
null
null
null
apps/andi/runtime.exs
msomji/smartcitiesdata
fc96abc1ef1306f7af6bd42bbcb4ed041a6d922c
[ "Apache-2.0" ]
null
null
null
use Mix.Config kafka_brokers = System.get_env("KAFKA_BROKERS") live_view_salt = System.get_env("LIVEVIEW_SALT") get_redix_args = fn host, password -> [host: host, password: password] |> Enum.filter(fn {_, nil} -> false {_, ""} -> false _ -> true end) end redix_args = get_redix_args.(System.get_env("REDIS_HOST"), System.get_env("REDIS_PASSWORD")) endpoint = kafka_brokers |> String.split(",") |> Enum.map(&String.trim/1) |> Enum.map(fn entry -> String.split(entry, ":") end) |> Enum.map(fn [host, port] -> {String.to_atom(host), String.to_integer(port)} end) config :andi, :brook, instance: :andi, driver: [ module: Brook.Driver.Kafka, init_arg: [ endpoints: endpoint, topic: "event-stream", group: "andi-event-stream", config: [ begin_offset: :earliest ] ] ], handlers: [Andi.Event.EventHandler], storage: [ module: Brook.Storage.Redis, init_arg: [redix_args: redix_args, namespace: "andi:view"] ] config :andi, AndiWeb.Endpoint, live_view: [ signing_salt: live_view_salt ] config :andi, secrets_endpoint: System.get_env("SECRETS_ENDPOINT"), dead_letter_topic: "streaming-dead-letters", kafka_endpoints: endpoint config :andi, Andi.Repo, database: System.get_env("POSTGRES_DBNAME"), username: System.get_env("POSTGRES_USER"), password: System.get_env("POSTGRES_PASSWORD"), hostname: System.get_env("POSTGRES_HOST"), port: System.get_env("POSTGRES_PORT"), ssl: true, ssl_opts: [ verify: :verify_peer, versions: [:"tlsv1.2"], cacertfile: System.get_env("CA_CERTFILE_PATH"), verify_fun: &:ssl_verify_hostname.verify_fun/3 ] config :telemetry_event, metrics_port: System.get_env("METRICS_PORT") |> String.to_integer(), add_poller: true, add_metrics: [:phoenix_endpoint_stop_duration, :dataset_total_count], metrics_options: [ [ metric_name: "dataset_info.gauge", tags: [:dataset_id, :dataset_title, :system_name, :source_type, :org_name], metric_type: :last_value ], [ metric_name: "andi_login_success.count", tags: [:app], metric_type: :counter ], [ metric_name: "andi_login_failure.count", tags: [:app], metric_type: :counter ] ] config :andi, Andi.Scheduler, jobs: [ {"0 0 1 * *", {Andi.Harvest.Harvester, :start_harvesting, []}} ] config :andi, AndiWeb.Auth.TokenHandler, issuer: System.get_env("AUTH_JWT_ISSUER"), allowed_algos: ["RS256"], verify_issuer: true config :guardian, Guardian.DB, repo: Andi.Repo
25.68
92
0.670561
e82ead543a701fd373b0a75fc9bbbe59ce011e70
9,493
exs
Elixir
test/parsersv2_test.exs
JustinTangg/ex_aws_elastic_load_balancing
e43871ecd07b12de49d42e7c4d1f442a32eaebae
[ "MIT" ]
4
2017-12-04T21:17:52.000Z
2018-08-08T20:44:53.000Z
test/parsersv2_test.exs
JustinTangg/ex_aws_elastic_load_balancing
e43871ecd07b12de49d42e7c4d1f442a32eaebae
[ "MIT" ]
4
2017-12-08T21:07:17.000Z
2021-08-31T19:50:02.000Z
test/parsersv2_test.exs
JustinTangg/ex_aws_elastic_load_balancing
e43871ecd07b12de49d42e7c4d1f442a32eaebae
[ "MIT" ]
6
2018-05-07T22:03:45.000Z
2022-01-10T18:13:37.000Z
defmodule ExAws.ElasticLoadBalancingV2.ParsersTest do use ExUnit.Case doctest ExAws.ElasticLoadBalancingV2.Parsers describe "describe_target_health parser" do test "parses DescribeTargetHealthResponse" do xml = """ <DescribeTargetHealthResponse xmlns="http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/"> <DescribeTargetHealthResult> <TargetHealthDescriptions> <member> <HealthCheckPort>80</HealthCheckPort> <TargetHealth> <State>healthy</State> </TargetHealth> <Target> <Port>80</Port> <Id>i-0376fadf</Id> </Target> </member> <member> <HealthCheckPort>80</HealthCheckPort> <TargetHealth> <State>healthy</State> </TargetHealth> <Target> <AvailabilityZone>all</AvailabilityZone> <Port>80</Port> <Id>i-0376fade</Id> </Target> </member> </TargetHealthDescriptions> </DescribeTargetHealthResult> <ResponseMetadata> <RequestId>c534f810-f389-11e5-9192-3fff33344cfa</RequestId> </ResponseMetadata> </DescribeTargetHealthResponse> """ expected = %{ request_id: "c534f810-f389-11e5-9192-3fff33344cfa", target_health_descriptions: [ %{ health_check_port: "80", target_health: "healthy", targets: [%{availability_zone: "", id: "i-0376fadf", port: "80"}] }, %{ health_check_port: "80", target_health: "healthy", targets: [%{availability_zone: "all", id: "i-0376fade", port: "80"}] } ] } {:ok, %{body: body}} = ExAws.ElasticLoadBalancingV2.Parsers.parse( {:ok, %{body: xml}}, :describe_target_health ) assert expected == body end end describe "describe_account_limits parser" do test "parses DescribeAccountLimitsResponse" do xml = """ <DescribeAccountLimitsResponse xmlns=\"http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/\">\n <DescribeAccountLimitsResult>\n <Limits>\n <member>\n <Name>application-load-balancers</Name>\n <Max>20</Max>\n </member>\n <member>\n <Name>target-groups</Name>\n <Max>3000</Max>\n </member>\n <member>\n <Name>targets-per-application-load-balancer</Name>\n <Max>1000</Max>\n </member>\n <member>\n <Name>listeners-per-application-load-balancer</Name>\n <Max>50</Max>\n </member>\n <member>\n <Name>rules-per-application-load-balancer</Name>\n <Max>100</Max>\n </member>\n <member>\n <Name>network-load-balancers</Name>\n <Max>20</Max>\n </member>\n <member>\n <Name>targets-per-network-load-balancer</Name>\n <Max>3000</Max>\n </member>\n <member>\n <Name>targets-per-availability-zone-per-network-load-balancer</Name>\n <Max>500</Max>\n </member>\n <member>\n <Name>listeners-per-network-load-balancer</Name>\n <Max>50</Max>\n </member>\n </Limits>\n </DescribeAccountLimitsResult>\n <ResponseMetadata>\n <RequestId>0dcbefb0-a719-11e8-a030-d79884c70fa3</RequestId>\n </ResponseMetadata>\n</DescribeAccountLimitsResponse>\n """ expected = %{ account_limits: [ %{max: "20", name: "application-load-balancers"}, %{max: "3000", name: "target-groups"}, %{max: "1000", name: "targets-per-application-load-balancer"}, %{max: "50", name: "listeners-per-application-load-balancer"}, %{max: "100", name: "rules-per-application-load-balancer"}, %{max: "20", name: "network-load-balancers"}, %{max: "3000", name: "targets-per-network-load-balancer"}, %{ max: "500", name: "targets-per-availability-zone-per-network-load-balancer" }, %{max: "50", name: "listeners-per-network-load-balancer"} ], request_id: "0dcbefb0-a719-11e8-a030-d79884c70fa3" } {:ok, %{body: body}} = ExAws.ElasticLoadBalancingV2.Parsers.parse( {:ok, %{body: xml}}, :describe_account_limits ) assert expected == body end end describe "describe_load_balancer_attributes parser" do test "parses DescribeLoadBalancerAttributesResponse" do xml = """ <DescribeLoadBalancerAttributesResponse xmlns=\"http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/\">\n <DescribeLoadBalancerAttributesResult>\n <Attributes>\n <member>\n <Value>false</Value>\n <Key>access_logs.s3.enabled</Key>\n </member>\n <member>\n <Value/>\n <Key>access_logs.s3.prefix</Key>\n </member>\n <member>\n <Value>true</Value>\n <Key>deletion_protection.enabled</Key>\n </member>\n <member>\n <Value>true</Value>\n <Key>routing.http2.enabled</Key>\n </member>\n <member>\n <Value/>\n <Key>access_logs.s3.bucket</Key>\n </member>\n <member>\n <Value>60</Value>\n <Key>idle_timeout.timeout_seconds</Key>\n </member>\n </Attributes>\n </DescribeLoadBalancerAttributesResult>\n <ResponseMetadata>\n <RequestId>fee66ea4-a71b-11e8-91ad-81230b665630</RequestId>\n </ResponseMetadata>\n</DescribeLoadBalancerAttributesResponse>\n """ expected = %{ request_id: "fee66ea4-a71b-11e8-91ad-81230b665630", attributes: [ %{key: "access_logs.s3.enabled", value: "false"}, %{key: "access_logs.s3.prefix", value: ""}, %{key: "deletion_protection.enabled", value: "true"}, %{key: "routing.http2.enabled", value: "true"}, %{key: "access_logs.s3.bucket", value: ""}, %{key: "idle_timeout.timeout_seconds", value: "60"} ] } {:ok, %{body: body}} = ExAws.ElasticLoadBalancingV2.Parsers.parse( {:ok, %{body: xml}}, :describe_load_balancer_attributes ) assert expected == body end end describe "modify_load_balancer_attributes parser" do test "parses ModifyLoadBalancerAttributesResponse" do xml = """ <ModifyLoadBalancerAttributesResponse xmlns=\"http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/\">\n <ModifyLoadBalancerAttributesResult>\n <Attributes>\n <member>\n <Value>61</Value>\n <Key>idle_timeout.timeout_seconds</Key>\n </member>\n <member>\n <Value/>\n <Key>access_logs.s3.bucket</Key>\n </member>\n <member>\n <Value>true</Value>\n <Key>deletion_protection.enabled</Key>\n </member>\n <member>\n <Value>true</Value>\n <Key>routing.http2.enabled</Key>\n </member>\n <member>\n <Value>false</Value>\n <Key>access_logs.s3.enabled</Key>\n </member>\n <member>\n <Value/>\n <Key>access_logs.s3.prefix</Key>\n </member>\n </Attributes>\n </ModifyLoadBalancerAttributesResult>\n <ResponseMetadata>\n <RequestId>dfc9d754-a7bb-11e8-9b83-879645239b41</RequestId>\n </ResponseMetadata>\n</ModifyLoadBalancerAttributesResponse>\n """ expected = %{ request_id: "dfc9d754-a7bb-11e8-9b83-879645239b41", attributes: [ %{key: "idle_timeout.timeout_seconds", value: "61"}, %{key: "access_logs.s3.bucket", value: ""}, %{key: "deletion_protection.enabled", value: "true"}, %{key: "routing.http2.enabled", value: "true"}, %{key: "access_logs.s3.enabled", value: "false"}, %{key: "access_logs.s3.prefix", value: ""} ] } {:ok, %{body: body}} = ExAws.ElasticLoadBalancingV2.Parsers.parse( {:ok, %{body: xml}}, :modify_load_balancer_attributes ) assert expected == body end end describe "register_targets parser" do test "parses RegisterTargetsResponse" do xml = """ <RegisterTargetsResponse xmlns=\"http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/\">\n <RegisterTargetsResult/>\n <ResponseMetadata>\n <RequestId>2f8a12e4-a7bf-11e8-b126-a7ebc8b8f129</RequestId>\n </ResponseMetadata>\n</RegisterTargetsResponse>\n """ expected = %{ request_id: "2f8a12e4-a7bf-11e8-b126-a7ebc8b8f129" } {:ok, %{body: body}} = ExAws.ElasticLoadBalancingV2.Parsers.parse( {:ok, %{body: xml}}, :register_targets ) assert expected == body end end describe "deregister_targets parser" do test "parses DeregisterTargetsResponse" do xml = """ <DeregisterTargetsResponse xmlns=\"http://elasticloadbalancing.amazonaws.com/doc/2015-12-01/\">\n <DeregisterTargetsResult/>\n <ResponseMetadata>\n <RequestId>6e3ddc79-a7bf-11e8-89ee-bf5fc4f54dab</RequestId>\n </ResponseMetadata>\n</DeregisterTargetsResponse>\n """ expected = %{ request_id: "6e3ddc79-a7bf-11e8-89ee-bf5fc4f54dab" } {:ok, %{body: body}} = ExAws.ElasticLoadBalancingV2.Parsers.parse( {:ok, %{body: xml}}, :deregister_targets ) assert expected == body end end end
48.433673
1,361
0.58875
e82ece222878950c51b8e42f4562a94e1f3b4a7c
2,135
ex
Elixir
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_device_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_device_metadata.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/sas_portal/lib/google_api/sas_portal/v1alpha1/model/sas_portal_device_metadata.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.SASPortal.V1alpha1.Model.SasPortalDeviceMetadata do @moduledoc """ Device data overridable by both SAS Portal and registration requests. ## Attributes * `antennaModel` (*type:* `String.t`, *default:* `nil`) - If populated, the Antenna Model Pattern to use. Format is: RecordCreatorId:PatternId * `commonChannelGroup` (*type:* `String.t`, *default:* `nil`) - CCG. A group of CBSDs in the same ICG requesting a common primary channel assignment. See CBRSA-TS-2001 V3.0.0 for more details. * `interferenceCoordinationGroup` (*type:* `String.t`, *default:* `nil`) - ICG. A group of CBSDs that manage their own interference with the group. See CBRSA-TS-2001 V3.0.0 for more details. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :antennaModel => String.t() | nil, :commonChannelGroup => String.t() | nil, :interferenceCoordinationGroup => String.t() | nil } field(:antennaModel) field(:commonChannelGroup) field(:interferenceCoordinationGroup) end defimpl Poison.Decoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeviceMetadata do def decode(value, options) do GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeviceMetadata.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.SASPortal.V1alpha1.Model.SasPortalDeviceMetadata do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
40.283019
196
0.739578
e82ecefa9ebedfc5cba85f0c854f7e31046b2cc9
2,012
ex
Elixir
clients/display_video/lib/google_api/display_video/v1/model/url_assigned_targeting_option_details.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/display_video/lib/google_api/display_video/v1/model/url_assigned_targeting_option_details.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/display_video/lib/google_api/display_video/v1/model/url_assigned_targeting_option_details.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.DisplayVideo.V1.Model.UrlAssignedTargetingOptionDetails do @moduledoc """ Details for assigned URL targeting option. This will be populated in the details field of an AssignedTargetingOption when targeting_type is `TARGETING_TYPE_URL`. ## Attributes * `negative` (*type:* `boolean()`, *default:* `nil`) - Indicates if this option is being negatively targeted. * `url` (*type:* `String.t`, *default:* `nil`) - Required. The URL, for example `example.com`. DV360 supports two levels of subdirectory targeting, for example `www.example.com/one-subdirectory-level/second-level`, and five levels of subdomain targeting, for example `five.four.three.two.one.example.com`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :negative => boolean(), :url => String.t() } field(:negative) field(:url) end defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.UrlAssignedTargetingOptionDetails do def decode(value, options) do GoogleApi.DisplayVideo.V1.Model.UrlAssignedTargetingOptionDetails.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.UrlAssignedTargetingOptionDetails do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.298246
113
0.74006
e82eecbfa1cf02d1896dab57aebe531c786db47e
3,000
exs
Elixir
.credo.exs
chaseconey/slash
f5d21f992b5ee7bbe2d3079b2e1057be32e935bb
[ "MIT" ]
5
2019-03-28T06:56:51.000Z
2021-03-17T11:05:00.000Z
.credo.exs
chaseconey/slash
f5d21f992b5ee7bbe2d3079b2e1057be32e935bb
[ "MIT" ]
6
2019-03-28T07:06:12.000Z
2019-05-15T17:04:10.000Z
.credo.exs
chaseconey/slash
f5d21f992b5ee7bbe2d3079b2e1057be32e935bb
[ "MIT" ]
2
2019-04-24T01:12:02.000Z
2019-09-20T00:26:00.000Z
%{ configs: [ %{ name: "default", color: true, strict: false, check_for_updates: true, files: %{ included: ["lib/", "config/", "test/"], excluded: [] }, checks: [ {Credo.Check.Consistency.ExceptionNames}, {Credo.Check.Consistency.LineEndings}, {Credo.Check.Consistency.ParameterPatternMatching}, {Credo.Check.Consistency.SpaceAroundOperators}, {Credo.Check.Consistency.SpaceInParentheses}, {Credo.Check.Consistency.TabsOrSpaces, priority: :higher}, {Credo.Check.Design.TagTODO}, {Credo.Check.Design.TagFIXME}, {Credo.Check.Design.DuplicatedCode, excluded_macros: []}, {Credo.Check.Design.AliasUsage, priority: :low}, {Credo.Check.Readability.FunctionNames}, {Credo.Check.Readability.LargeNumbers}, {Credo.Check.Readability.MaxLineLength, priority: :normal, max_length: 100}, {Credo.Check.Readability.ModuleAttributeNames}, {Credo.Check.Readability.ModuleDoc}, {Credo.Check.Readability.ModuleNames}, {Credo.Check.Readability.ParenthesesOnZeroArityDefs}, {Credo.Check.Readability.ParenthesesInCondition}, {Credo.Check.Readability.PredicateFunctionNames}, {Credo.Check.Readability.PreferImplicitTry}, {Credo.Check.Readability.RedundantBlankLines}, {Credo.Check.Readability.StringSigils}, {Credo.Check.Readability.TrailingBlankLine}, {Credo.Check.Readability.TrailingWhiteSpace}, {Credo.Check.Readability.VariableNames}, {Credo.Check.Readability.Semicolons}, {Credo.Check.Readability.SpaceAfterCommas}, {Credo.Check.Refactor.DoubleBooleanNegation}, {Credo.Check.Refactor.CondStatements}, {Credo.Check.Refactor.CyclomaticComplexity}, {Credo.Check.Refactor.FunctionArity}, {Credo.Check.Refactor.LongQuoteBlocks}, {Credo.Check.Refactor.MatchInCondition}, {Credo.Check.Refactor.NegatedConditionsInUnless}, {Credo.Check.Refactor.NegatedConditionsWithElse}, {Credo.Check.Refactor.Nesting}, {Credo.Check.Refactor.PipeChainStart}, {Credo.Check.Refactor.UnlessWithElse}, {Credo.Check.Warning.BoolOperationOnSameValues}, {Credo.Check.Warning.IExPry}, {Credo.Check.Warning.IoInspect}, {Credo.Check.Warning.LazyLogging}, {Credo.Check.Warning.OperationOnSameValues}, {Credo.Check.Warning.OperationWithConstantResult}, {Credo.Check.Warning.UnusedEnumOperation}, {Credo.Check.Warning.UnusedFileOperation}, {Credo.Check.Warning.UnusedKeywordOperation}, {Credo.Check.Warning.UnusedListOperation}, {Credo.Check.Warning.UnusedPathOperation}, {Credo.Check.Warning.UnusedRegexOperation}, {Credo.Check.Warning.UnusedStringOperation}, {Credo.Check.Warning.UnusedTupleOperation}, {Credo.Check.Warning.RaiseInsideRescue} ] } ] }
42.857143
84
0.677667
e82ef2449ed9963bda7d734026b817fe08896edd
1,750
ex
Elixir
lib/stash/macros.ex
Dimakoua/stash
037ae43c8b9b45b2d6849840558d347d3ed99184
[ "MIT" ]
34
2016-02-11T11:42:30.000Z
2017-05-06T20:07:34.000Z
lib/stash/macros.ex
Dimakoua/stash
037ae43c8b9b45b2d6849840558d347d3ed99184
[ "MIT" ]
4
2017-08-24T10:45:45.000Z
2019-04-10T16:41:06.000Z
lib/stash/macros.ex
Dimakoua/stash
037ae43c8b9b45b2d6849840558d347d3ed99184
[ "MIT" ]
6
2017-08-22T16:39:14.000Z
2021-06-27T22:26:42.000Z
defmodule Stash.Macros do @moduledoc false # A collection of Macros used to define internal function headers # and should not be used from outside this library (because they # make a lot of assumptions) defmacro deft(args, do: body) do { args, func_name, ctx, guards } = parse_args(args) cache = { :cache, ctx, nil } body = quote do cache = unquote(cache) if :ets.info(cache) == :undefined do :ets.new(cache, [ { :read_concurrency, true }, { :write_concurrency, true }, :public, :set, :named_table ]) end unquote(body) end remainder = args |> Enum.reverse |> Enum.reduce([], fn({ name, ctx, other }, state) -> case name do :cache -> state nvalue -> [{ "_" <> to_string(nvalue) |> String.to_atom, ctx, other } | state] end end) quote do def unquote(func_name)(unquote_splicing([cache|remainder])) when not is_atom(unquote(cache)) do raise ArgumentError, message: "Invalid ETS table name provided, got: #{inspect unquote(cache)}" end if unquote(guards != nil) do def unquote(func_name)(unquote_splicing(args)) when unquote(guards) do unquote(body) end else def unquote(func_name)(unquote_splicing(args)) do unquote(body) end end end end defmacro __using__(_opts) do quote do import unquote(__MODULE__) end end defp parse_args(args) do case args do { :when, _, [ { func_name, ctx, args }, guards ] } -> { args, func_name, ctx, guards } { func_name, ctx, args } -> { args, func_name, ctx, nil } end end end
25.735294
103
0.577714
e82f756d2d0b4deecc332e5cf380230554a410c5
8,490
ex
Elixir
lib/bamboo/adapters/send_grid_helper.ex
hostalerye/bamboo
b7aea2a6761062a62e5bdcf27ae07c6bcb374bc5
[ "MIT" ]
1
2021-12-01T13:37:19.000Z
2021-12-01T13:37:19.000Z
lib/bamboo/adapters/send_grid_helper.ex
hostalerye/bamboo
b7aea2a6761062a62e5bdcf27ae07c6bcb374bc5
[ "MIT" ]
1
2021-02-23T18:44:13.000Z
2021-02-23T18:44:13.000Z
lib/bamboo/adapters/send_grid_helper.ex
hostalerye/bamboo
b7aea2a6761062a62e5bdcf27ae07c6bcb374bc5
[ "MIT" ]
1
2021-03-29T17:43:54.000Z
2021-03-29T17:43:54.000Z
defmodule Bamboo.SendGridHelper do @moduledoc """ Functions for using features specific to Sendgrid. ## Example email |> with_template("80509523-83de-42b6-a2bf-54b7513bd2aa") |> substitute("%name%", "Jon Snow") |> substitute("%location%", "Westeros") """ alias Bamboo.Email @field_name :send_grid_template @categories :categories @asm_group_id :asm_group_id @bypass_list_management :bypass_list_management @google_analytics_enabled :google_analytics_enabled @google_analytics_utm_params :google_analytics_utm_params @additional_personalizations :additional_personalizations @allowed_google_analytics_utm_params ~w(utm_source utm_medium utm_campaign utm_term utm_content)a @send_at_field :sendgrid_send_at @ip_pool_name_field :ip_pool_name @doc """ Specify the template for SendGrid to use for the context of the substitution tags. ## Example email |> with_template("80509523-83de-42b6-a2bf-54b7513bd2aa") """ def with_template(email, template_id) do template = Map.get(email.private, @field_name, %{}) email |> Email.put_private(@field_name, set_template(template, template_id)) end @doc """ Add a tag to the list of substitutions in the SendGrid template. The tag must be a `String.t` due to SendGrid using special characters to wrap tags in the template. ## Example email |> substitute("%name%", "Jon Snow") """ def substitute(email, tag, value) do if is_binary(tag) do template = Map.get(email.private, @field_name, %{}) email |> Email.put_private(@field_name, add_substitution(template, tag, value)) else raise "expected the tag parameter to be of type binary, got #{tag}" end end @doc """ An array of category names for this email. A maximum of 10 categories can be assigned to an email. Duplicate categories will be ignored and only unique entries will be sent. ## Example email |> with_categories("campaign-12345") """ def with_categories(email, categories) when is_list(categories) do categories = (Map.get(email.private, @categories, []) ++ categories) |> MapSet.new() |> MapSet.to_list() email |> Email.put_private(@categories, Enum.slice(categories, 0, 10)) end def with_categories(_email, _categories) do raise "expected a list of category strings" end @doc """ Add a property to the list of dynamic template data in the SendGrid template. This will be added to the request as: ``` "personalizations":[ { "to":[ { "email":"example@sendgrid.net" } ], "dynamic_template_data":{ "total":"$ 239.85", } } ], ``` The tag can be of any type since SendGrid allows you to use Handlebars in its templates ## Example email |> add_dynamic_field("name", "Jon Snow") """ def add_dynamic_field(email, field, value) when is_atom(field), do: add_dynamic_field(email, Atom.to_string(field), value) def add_dynamic_field(email, field, value) when is_binary(field) do template = Map.get(email.private, @field_name, %{}) email |> Email.put_private(@field_name, add_dynamic_field_to_template(template, field, value)) end def add_dynamic_field(_email, field, _value), do: raise("expected the name parameter to be of type binary or atom, got #{field}") @doc """ An integer id for an ASM (Advanced Suppression Manager) group that this email should belong to. This can be used to let recipients unsubscribe from only a certain type of communication. ## Example email |> with_asm_group_id(1234) """ def with_asm_group_id(email, asm_group_id) when is_integer(asm_group_id) do email |> Email.put_private(@asm_group_id, asm_group_id) end def with_asm_group_id(_email, asm_group_id) do raise "expected the asm_group_id parameter to be an integer, got #{asm_group_id}" end @doc """ A boolean setting to instruct SendGrid to bypass list management for this email. If enabled, SendGrid will ignore any email supression (such as unsubscriptions, bounces, spam filters) for this email. This is useful for emails that all users must receive, such as Terms of Service updates, or password resets. ## Example email |> with_bypass_list_management(true) """ def with_bypass_list_management(email, enabled) when is_boolean(enabled) do email |> Email.put_private(@bypass_list_management, enabled) end def with_bypass_list_management(_email, enabled) do raise "expected bypass_list_management parameter to be a boolean, got #{enabled}" end @doc """ Instruct SendGrid to enable or disable Google Analytics tracking, and optionally set the UTM parameters for it. This is useful if you need to control UTM tracking parameters on an individual email basis. ## Example email |> with_google_analytics(true, %{utm_source: "email", utm_campaign: "campaign"}) email |> with_google_analytics(false) """ def with_google_analytics(email, enabled, utm_params \\ %{}) def with_google_analytics(email, enabled, utm_params) when is_boolean(enabled) do utm_params = utm_params |> Map.take(@allowed_google_analytics_utm_params) email |> Email.put_private(@google_analytics_enabled, enabled) |> Email.put_private(@google_analytics_utm_params, utm_params) end def with_google_analytics(_email, _enabled, _utm_params) do raise "expected with_google_analytics enabled parameter to be a boolean" end @doc """ Schedule a time for SendGrid to deliver the email. Note that if the time is in the past, SendGrid will immediately deliver the email. ## Example {:ok, delivery_time, _} = DateTime.from_iso8601("2020-01-01T00:00:00Z") email |> with_send_at(delivery_time) """ @spec with_send_at(%Email{}, %DateTime{} | integer()) :: %Email{} def with_send_at(email, %DateTime{} = time) do timestamp = DateTime.to_unix(time) email |> Email.put_private(@send_at_field, timestamp) end def with_send_at(email, unix_timestamp) when is_integer(unix_timestamp) do email |> Email.put_private(@send_at_field, unix_timestamp) end def with_send_at(_email, _time) do raise "expected with_send_at time parameter to be a DateTime or unix timestamp" end @doc """ Add SendGrid personalizations Each personalization can have the following fields: `to`, `cc`, `bcc`, `subject`, `headers`, `substitutions`, `custom_args`, or `send_at`. Settings from the top level of the email (e.g., `Email |> with_send_at`) will not be applied to each personalization. If you want multiple personalizations with common properties, it is recommended to generate the list from a common base value and simply do not set the corresponding top-level fields. ## Example: base_personalization = %{ bcc: [%{"email" => "bcc@bar.com", "name" => "BCC"}], subject: "Here is your email" } personalizations = Enum.map( [ %{to: "one@test.com"}, %{to: "two@test.com", send_at: 1_580_485_560} ], &Map.merge(base_personalization, &1) ) email = new_email() |> Email.put_header("Reply-To", "reply@foo.com") |> Bamboo.SendGridHelper.add_personalizations(personalizations) """ @spec add_personalizations(Bamboo.Email.t(), [map]) :: Bamboo.Email.t() def add_personalizations(email, personalizations) when is_list(personalizations) do email |> Email.put_private(@additional_personalizations, personalizations) end defp set_template(template, template_id) do template |> Map.merge(%{template_id: template_id}) end defp add_substitution(template, tag, value) do template |> Map.update(:substitutions, %{tag => value}, fn substitutions -> Map.merge(substitutions, %{tag => value}) end) end defp add_dynamic_field_to_template(template, field, value) do template |> Map.update(:dynamic_template_data, %{field => value}, fn dynamic_data -> Map.merge(dynamic_data, %{field => value}) end) end @doc """ Specify the ip pool name. ## Example email |> with_ip_pool_name("my-ip-pool-name") """ def with_ip_pool_name(email, ip_pool_name) do email |> Email.put_private(@ip_pool_name_field, ip_pool_name) end end
28.489933
100
0.689988
e82f86ca3bbc47ec11a44cdebde56521522d7868
878
ex
Elixir
lib/tus/application.ex
infatuAI/tus
0c8d509f4cb1d3d91fa6cd8cf7dc611f346168ad
[ "BSD-3-Clause" ]
null
null
null
lib/tus/application.ex
infatuAI/tus
0c8d509f4cb1d3d91fa6cd8cf7dc611f346168ad
[ "BSD-3-Clause" ]
null
null
null
lib/tus/application.ex
infatuAI/tus
0c8d509f4cb1d3d91fa6cd8cf7dc611f346168ad
[ "BSD-3-Clause" ]
null
null
null
defmodule Tus.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application import Supervisor.Spec, only: [worker: 3] def start(_type, _args) do # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Tus.Supervisor] Supervisor.start_link(get_children(), opts) end defp get_children do Application.get_env(:tus, :controllers, []) |> Enum.map(&get_worker/1) end defp get_worker(controller) do # Starts a worker by calling: Tus.Worker.start_link(arg) # {Tus.Worker, arg}, config = Application.get_env(:tus, controller) |> Enum.into(%{}) |> Map.put(:cache_name, Module.concat(controller, TusCache)) worker(config.cache, [config], []) end end
26.606061
66
0.686788
e82f8728d6342a35fccb4b7b2b21f182ffbe9c17
2,330
ex
Elixir
clients/cloud_kms/lib/google_api/cloud_kms/v1/model/public_key.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_kms/lib/google_api/cloud_kms/v1/model/public_key.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
clients/cloud_kms/lib/google_api/cloud_kms/v1/model/public_key.ex
mocknen/elixir-google-api
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
[ "Apache-2.0" ]
null
null
null
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.CloudKMS.V1.Model.PublicKey do @moduledoc """ The public key for a given CryptoKeyVersion. Obtained via GetPublicKey. ## Attributes - algorithm (String.t): The Algorithm associated with this key. Defaults to: `null`. - Enum - one of [CRYPTO_KEY_VERSION_ALGORITHM_UNSPECIFIED, GOOGLE_SYMMETRIC_ENCRYPTION, RSA_SIGN_PSS_2048_SHA256, RSA_SIGN_PSS_3072_SHA256, RSA_SIGN_PSS_4096_SHA256, RSA_SIGN_PSS_4096_SHA512, RSA_SIGN_PKCS1_2048_SHA256, RSA_SIGN_PKCS1_3072_SHA256, RSA_SIGN_PKCS1_4096_SHA256, RSA_SIGN_PKCS1_4096_SHA512, RSA_DECRYPT_OAEP_2048_SHA256, RSA_DECRYPT_OAEP_3072_SHA256, RSA_DECRYPT_OAEP_4096_SHA256, RSA_DECRYPT_OAEP_4096_SHA512, EC_SIGN_P256_SHA256, EC_SIGN_P384_SHA384] - pem (String.t): The public key, encoded in PEM format. For more information, see the [RFC 7468](https://tools.ietf.org/html/rfc7468) sections for [General Considerations](https://tools.ietf.org/html/rfc7468#section-2) and [Textual Encoding of Subject Public Key Info] (https://tools.ietf.org/html/rfc7468#section-13). Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :algorithm => any(), :pem => any() } field(:algorithm) field(:pem) end defimpl Poison.Decoder, for: GoogleApi.CloudKMS.V1.Model.PublicKey do def decode(value, options) do GoogleApi.CloudKMS.V1.Model.PublicKey.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudKMS.V1.Model.PublicKey do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
44.807692
469
0.770815
e82fb18aa1c056c98fa61dee2c61b90c0abdb80f
7,602
ex
Elixir
elixir/codes-from-books/little-elixir/cap8/blitzy/deps/timex/lib/parse/datetime/parsers/iso8601_extended.ex
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
1
2017-10-16T03:00:50.000Z
2017-10-16T03:00:50.000Z
elixir/codes-from-books/little-elixir/cap8/blitzy/deps/timex/lib/parse/datetime/parsers/iso8601_extended.ex
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
null
null
null
elixir/codes-from-books/little-elixir/cap8/blitzy/deps/timex/lib/parse/datetime/parsers/iso8601_extended.ex
trxeste/wrk
3e05e50ff621866f0361cc8494ce8f6bb4d97fae
[ "BSD-3-Clause" ]
1
2019-11-23T12:09:14.000Z
2019-11-23T12:09:14.000Z
defmodule Timex.Parse.DateTime.Parsers.ISO8601Extended do use Combine.Helpers alias Combine.ParserState defparser parse(%ParserState{status: :ok, column: col, input: input, results: results} = state) do case parse_extended(input) do {:ok, parts, len, remaining} -> %{state | :column => col + len, :input => remaining, :results => [Enum.reverse(parts)|results]} {:error, reason, count} -> %{state | :status => :error, :column => col + count, :error => reason} end end def parse_extended(<<>>), do: {:error, "Expected year, but got end of input."} def parse_extended(input), do: parse_extended(input, :year, [], 0) def parse_extended(<<y1::utf8,y2::utf8,y3::utf8,y4::utf8,"-",rest::binary>>, :year, acc, count) when y1 >= ?0 and y1 <= ?9 and y2 >= ?0 and y2 <= ?9 and y3 >= ?0 and y3 <= ?9 and y4 >= ?0 and y4 <= ?9 do year = String.to_integer(<<y1::utf8,y2::utf8,y3::utf8,y4::utf8>>) parse_extended(rest, :month, [{:year4, year}|acc], count+4) end def parse_extended(<<h::utf8,_::binary>>, :year, _acc, count), do: {:error, "Expected 4 digit year, but got `#{<<h::utf8>>}` instead.", count} def parse_extended(<<m1::utf8,m2::utf8,"-",rest::binary>>, :month, acc, count) when m1 >= ?0 and m1 < ?2 and m2 >= ?0 and m2 <= ?9 do month = String.to_integer(<<m1::utf8,m2::utf8>>) cond do month > 0 and month < 13 -> parse_extended(rest, :day, [{:month, month}|acc], count+2) :else -> {:error, "Expected month between 1-12, but got `#{month}` instead.", count} end end def parse_extended(<<h::utf8,_::binary>>, :month, _acc, count), do: {:error, "Expected 2 digit month, but got `#{<<h::utf8>>}` instead.", count} def parse_extended(<<d1::utf8,d2::utf8,sep::utf8,rest::binary>>, :day, acc, count) when d1 >= ?0 and d1 <= ?3 and d2 >= ?0 and d2 <= ?9 do cond do sep in [?T,?\s] -> day = String.to_integer(<<d1::utf8,d2::utf8>>) cond do day > 0 and day < 32 -> parse_extended(rest, :hour, [{:day, day}|acc], count+3) :else -> {:error, "Expected day between 1-31, but got `#{day}` instead.", count} end :else -> {:error, "Expected valid date/time separator (T or space), but got `#{<<sep::utf8>>}` instead.", count+2} end end def parse_extended(<<h::utf8,_::binary>>, :day, _acc, count), do: {:error, "Expected 2 digit day, but got `#{<<h::utf8>>}` instead.", count} def parse_extended(<<h1::utf8,h2::utf8,rest::binary>>, :hour, acc, count) when h1 >= ?0 and h1 < ?3 and h2 >= ?0 and h2 <= ?9 do hour = String.to_integer(<<h1::utf8,h2::utf8>>) cond do hour >= 0 and hour <= 24 -> case rest do <<":",rest::binary>> -> parse_extended(rest, :minute, [{:hour24, hour}|acc], count+3) _ -> parse_offset(rest, [{:hour24, hour}|acc], count+2) end :else -> {:error, "Expected hour between 0-24, but got `#{hour}` instead.", count} end end def parse_extended(<<h::utf8,_::binary>>, :hour, _acc, count), do: {:error, "Expected 2 digit hour, but got `#{<<h::utf8>>}` instead.", count} # Minutes are optional def parse_extended(<<m1::utf8,m2::utf8,rest::binary>>, :minute, acc, count) when m1 >= ?0 and m1 < ?6 and m2 >= ?0 and m2 <= ?9 do minute = String.to_integer(<<m1::utf8,m2::utf8>>) cond do minute >= 0 and minute <= 60 -> case rest do <<":",rest::binary>> -> parse_extended(rest, :second, [{:min, minute}|acc], count+3) _ -> parse_offset(rest, [{:min, minute}|acc], count+2) end :else -> {:error, "Expected minute between 0-60, but got `#{minute}` instead.", count} end end def parse_extended(<<h::utf8,_::binary>>, :minute, _acc, count), do: {:error, "Expected 2 digit minute, but got `#{<<h::utf8>>}` instead.", count} # Seconds are optional def parse_extended(<<s1::utf8,s2::utf8,".",rest::binary>>, :second, acc, count) when # Has fractional seconds s1 >= ?0 and s1 < ?6 and s2 >= ?0 and s2 <= ?9 do case parse_fractional_seconds(rest, count, <<>>) do {:ok, fraction, count, rest} -> seconds = String.to_integer(<<s1::utf8,s2::utf8>>) precision = byte_size(fraction) fractional = String.to_integer(fraction) fractional = fractional * div(1_000_000, trunc(:math.pow(10, precision))) cond do seconds >= 0 and seconds <= 60 -> parse_offset(rest, [{:sec_fractional, {fractional, precision}}, {:sec, seconds}|acc], count+2) :else -> {:error, "Expected second between 0-60, but got `#{seconds}` instead.", count} end {:error, _reason, _count} = err -> err end end def parse_extended(<<s1::utf8,s2::utf8,rest::binary>>, :second, acc, count) when # No fractional seconds s1 >= ?0 and s1 < ?6 and s2 >= ?0 and s2 <= ?9 do second = String.to_integer(<<s1::utf8,s2::utf8>>) cond do second >= 0 and second <= 60 -> parse_offset(rest, [{:sec, second}|acc], count+2) :else -> {:error, "Expected second between 0-60, but got `#{second}` instead.", count} end end def parse_extended(<<h::utf8,_::binary>>, :second, _acc, count), do: {:error, "Expected valid value for seconds, but got `#{<<h::utf8>>}` instead.", count} def parse_fractional_seconds(<<digit::utf8,rest::binary>>, count, acc) when digit >= ?0 and digit <= ?9 do parse_fractional_seconds(rest, count+1, <<acc::binary,digit::utf8>>) end def parse_fractional_seconds(rest, count, acc) do {:ok, acc, count, rest} end def parse_offset(<<"Z",rest::binary>>, acc, count), do: {:ok, [{:zname, "Etc/UTC"}|acc], count+1, rest} def parse_offset(<<dir::utf8,rest::binary>>, acc, count) when dir in [?+,?-] do parse_offset(dir, rest, acc, count+1) end # +/-HH:MM:SS (seconds are currently unhandled in offsets) def parse_offset(dir, <<h1::utf8,h2::utf8,":",m1::utf8,m2::utf8,":",s1::utf8,s2::utf8,rest::binary>>, acc, count) when h1 >= ?0 and h1 < ?2 and h2 >= ?0 and h2 <= ?9 and m1 >= ?0 and m1 < ?6 and m2 >= ?0 and m2 <= ?9 and s1 >= ?0 and s1 < ?6 and s2 >= ?0 and s2 <= ?9 do {:ok, [{:zname, <<dir::utf8,h1::utf8,h2::utf8,":",m1::utf8,m2::utf8>>}|acc], count+7, rest} end # +/-HH:MM def parse_offset(dir, <<h1::utf8,h2::utf8,":",m1::utf8,m2::utf8,rest::binary>>, acc, count) when h1 >= ?0 and h1 < ?2 and h2 >= ?0 and h2 <= ?9 and m1 >= ?0 and m1 < ?6 and m2 >= ?0 and m2 <= ?9 do {:ok, [{:zname, <<dir::utf8,h1::utf8,h2::utf8,":",m1::utf8,m2::utf8>>}|acc], count+5, rest} end # +/-HHMM def parse_offset(dir, <<h1::utf8,h2::utf8,m1::utf8,m2::utf8,rest::binary>>, acc, count) when h1 >= ?0 and h1 < ?2 and h2 >= ?0 and h2 <= ?9 and m1 >= ?0 and m1 < ?6 and m2 >= ?0 and m2 <= ?9 do {:ok, [{:zname, <<dir::utf8,h1::utf8,h2::utf8,":",m1::utf8,m2::utf8>>}|acc], count+5, rest} end # +/-HH def parse_offset(dir, <<h1::utf8,h2::utf8,rest::binary>>, acc, count) when h1 >= ?0 and h1 < ?2 and h2 >= ?0 and h2 <= ?9 do {:ok, [{:zname, <<dir::utf8,h1::utf8,h2::utf8,":00">>}|acc], count+2, rest} end def parse_offset(_, <<h::utf8,_rest::binary>>, _acc, count), do: {:error, "Expected valid offset, but got `#{<<h::utf8>>}` instead.", count} end
43.193182
157
0.558274
e82fbef64297cb9ab388401db54323f62e813cec
1,865
ex
Elixir
clients/games/lib/google_api/games/v1/model/event_update_request.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/event_update_request.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/model/event_update_request.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an &quot;AS IS&quot; BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This class is auto generated by the swagger code generator program. # https://github.com/swagger-api/swagger-codegen.git # Do not edit the class manually. defmodule GoogleApi.Games.V1.Model.EventUpdateRequest do @moduledoc """ This is a JSON template for an event period update resource. ## Attributes - definitionId (String.t): The ID of the event being modified in this update. Defaults to: `null`. - kind (String.t): Uniquely identifies the type of this resource. Value is always the fixed string games#eventUpdateRequest. Defaults to: `null`. - updateCount (String.t): The number of times this event occurred in this time period. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :definitionId => any(), :kind => any(), :updateCount => any() } field(:definitionId) field(:kind) field(:updateCount) end defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.EventUpdateRequest do def decode(value, options) do GoogleApi.Games.V1.Model.EventUpdateRequest.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.EventUpdateRequest do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.537037
147
0.733512
e82fd6bf3e8560e87a39dcadf3b2f2097b4ccf19
852
ex
Elixir
test/support/live_views/layout.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/layout.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
test/support/live_views/layout.ex
gaslight/live_element
78d4ab0a2daab470f2ffd25d446fbabb0d746afe
[ "MIT" ]
null
null
null
defmodule LiveElementTest.ParentLayoutLive do use LiveElement def render(assigns) do ~H""" <%= live_render @socket, LiveElementTest.LayoutLive, session: @session, id: "layout" %> """ end def mount(_params, session, socket) do {:ok, assign(socket, session: session)} end end defmodule LiveElementTest.LayoutLive do use LiveElement, layout: {LiveElementTest.LayoutView, "live.html"} def render(assigns), do: ~H|The value is: <%= @val %>| def mount(_params, session, socket) do socket |> assign(val: 123) |> maybe_put_layout(session) end def handle_event("double", _, socket) do {:noreply, update(socket, :val, &(&1 * 2))} end defp maybe_put_layout(socket, %{"live_layout" => value}) do {:ok, socket, layout: value} end defp maybe_put_layout(socket, _session), do: {:ok, socket} end
23.666667
91
0.670188
e82feccfc79aea3c4d4c97bae75ab2a50c6fb645
410
ex
Elixir
test/support/file_loader.ex
kianmeng/xema
a990d64fb4bcd708249514daa55426ee003da25d
[ "MIT" ]
49
2018-06-05T09:42:19.000Z
2022-02-15T12:50:51.000Z
test/support/file_loader.ex
kianmeng/xema
a990d64fb4bcd708249514daa55426ee003da25d
[ "MIT" ]
152
2017-06-11T13:43:06.000Z
2022-01-09T17:13:45.000Z
test/support/file_loader.ex
kianmeng/xema
a990d64fb4bcd708249514daa55426ee003da25d
[ "MIT" ]
6
2019-05-31T05:41:47.000Z
2021-12-14T08:09:36.000Z
defmodule Test.FileLoader do @moduledoc false @behaviour Xema.Loader @spec fetch(binary) :: {:ok, map} | {:error, any} def fetch(uri), do: "test/fixtures/remote" |> Path.join(uri.path) |> File.read!() |> eval(uri) defp eval(str, uri) do {data, _} = Code.eval_string(str) {:ok, data} rescue error -> {:error, %{error | file: URI.to_string(uri)}} end end
19.52381
58
0.580488
e83006e7aee898f7c6f213a19bacabdb51c3e8da
52,119
ex
Elixir
lib/phoenix_live_view/test/live_view_test.ex
jowrjowr/phoenix_live_view
d52da3b41292f9488e4a5c210aa1110c3f6420b0
[ "MIT" ]
null
null
null
lib/phoenix_live_view/test/live_view_test.ex
jowrjowr/phoenix_live_view
d52da3b41292f9488e4a5c210aa1110c3f6420b0
[ "MIT" ]
null
null
null
lib/phoenix_live_view/test/live_view_test.ex
jowrjowr/phoenix_live_view
d52da3b41292f9488e4a5c210aa1110c3f6420b0
[ "MIT" ]
null
null
null
defmodule Phoenix.LiveViewTest do @moduledoc """ Conveniences for testing Phoenix LiveViews. In LiveView tests, we interact with views via process communication in substitution of a browser. Like a browser, our test process receives messages about the rendered updates from the view which can be asserted against to test the life-cycle and behavior of LiveViews and their children. ## LiveView Testing The life-cycle of a LiveView as outlined in the `Phoenix.LiveView` docs details how a view starts as a stateless HTML render in a disconnected socket state. Once the browser receives the HTML, it connects to the server and a new LiveView process is started, remounted in a connected socket state, and the view continues statefully. The LiveView test functions support testing both disconnected and connected mounts separately, for example: import Plug.Conn import Phoenix.ConnTest import Phoenix.LiveViewTest @endpoint MyEndpoint test "disconnected and connected mount", %{conn: conn} do conn = get(conn, "/my-path") assert html_response(conn, 200) =~ "<h1>My Disconnected View</h1>" {:ok, view, html} = live(conn) end test "redirected mount", %{conn: conn} do assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "my-path") end Here, we start by using the familiar `Phoenix.ConnTest` function, `get/2` to test the regular HTTP GET request which invokes mount with a disconnected socket. Next, `live/1` is called with our sent connection to mount the view in a connected state, which starts our stateful LiveView process. In general, it's often more convenient to test the mounting of a view in a single step, provided you don't need the result of the stateless HTTP render. This is done with a single call to `live/2`, which performs the `get` step for us: test "connected mount", %{conn: conn} do {:ok, _view, html} = live(conn, "/my-path") assert html =~ "<h1>My Connected View</h1>" end ## Testing Events The browser can send a variety of events to a LiveView via `phx-` bindings, which are sent to the `handle_event/3` callback. To test events sent by the browser and assert on the rendered side effect of the event, use the `render_*` functions: * `render_click/1` - sends a phx-click event and value, returning the rendered result of the `handle_event/3` callback. * `render_focus/2` - sends a phx-focus event and value, returning the rendered result of the `handle_event/3` callback. * `render_blur/1` - sends a phx-blur event and value, returning the rendered result of the `handle_event/3` callback. * `render_submit/1` - sends a form phx-submit event and value, returning the rendered result of the `handle_event/3` callback. * `render_change/1` - sends a form phx-change event and value, returning the rendered result of the `handle_event/3` callback. * `render_keydown/1` - sends a form phx-keydown event and value, returning the rendered result of the `handle_event/3` callback. * `render_keyup/1` - sends a form phx-keyup event and value, returning the rendered result of the `handle_event/3` callback. * `render_hook/3` - sends a hook event and value, returning the rendered result of the `handle_event/3` callback. For example: {:ok, view, _html} = live(conn, "/thermo") assert view |> element("button#inc") |> render_click() =~ "The temperature is: 31℉" In the example above, we are looking for a particular element on the page and triggering its phx-click event. LiveView takes care of making sure the element has a phx-click and automatically sends its values to the server. You can also bypass the element lookup and directly trigger the LiveView event in most functions: assert render_click(view, :inc, %{}) =~ "The temperature is: 31℉" The `element` style is preferred as much as possible, as it helps LiveView perform validations and ensure the events in the HTML actually matches the event names on the server. ## Testing regular messages LiveViews are `GenServer`'s under the hood, and can send and receive messages just like any other server. To test the side effects of sending or receiving messages, simply message the view and use the `render` function to test the result: send(view.pid, {:set_temp, 50}) assert render(view) =~ "The temperature is: 50℉" ## Testing components There are two main mechanisms for testing components. To test stateless components or just a regular rendering of a component, one can use `render_component/2`: assert render_component(MyComponent, id: 123, user: %User{}) =~ "some markup in component" If you want to test how components are mounted by a LiveView and interact with DOM events, you can use the regular `live/2` macro to build the LiveView with the component and then scope events by passing the view and a **DOM selector** in a list: {:ok, view, html} = live(conn, "/users") html = view |> element("#user-13 a", "Delete") |> render_click() refute html =~ "user-13" refute view |> element("#user-13") |> has_element?() In the example above, LiveView will lookup for an element with ID=user-13 and retrieve its `phx-target`. If `phx-target` points to a component, that will be the component used, otherwise it will fallback to the view. """ @flash_cookie "__phoenix_flash__" require Phoenix.ConnTest require Phoenix.ChannelTest alias Phoenix.LiveView.{Diff, Socket} alias Phoenix.LiveViewTest.{ClientProxy, DOM, Element, View, Upload, UploadClient} @doc """ Puts connect params to be used on LiveView connections. See `Phoenix.LiveView.get_connect_params/1`. """ def put_connect_params(conn, params) when is_map(params) do Plug.Conn.put_private(conn, :live_view_connect_params, params) end @doc """ Puts connect info to be used on LiveView connections. See `Phoenix.LiveView.get_connect_info/1`. """ def put_connect_info(conn, params) when is_map(params) do Plug.Conn.put_private(conn, :live_view_connect_info, params) end @doc """ Spawns a connected LiveView process. If a `path` is given, then a regular `get(conn, path)` is done and the page is upgraded to a `LiveView`. If no path is given, it assumes a previously rendered `%Plug.Conn{}` is given, which will be converted to a `LiveView` immediately. ## Examples {:ok, view, html} = live(conn, "/path") assert view.module = MyLive assert html =~ "the count is 3" assert {:error, {:redirect, %{to: "/somewhere"}}} = live(conn, "/path") """ defmacro live(conn, path \\ nil) do quote bind_quoted: binding(), generated: true do cond do is_binary(path) -> Phoenix.LiveViewTest.__live__(get(conn, path), path) is_nil(path) -> Phoenix.LiveViewTest.__live__(conn) true -> raise RuntimeError, "path must be nil or a binary, got: #{inspect(path)}" end end end @doc """ Spawns a connected LiveView process mounted in isolation as the sole rendered element. Useful for testing LiveViews that are not directly routable, such as those built as small components to be re-used in multiple parents. Testing routable LiveViews is still recommended whenever possible since features such as live navigation require routable LiveViews. ## Options * `:session` - the session to be given to the LiveView All other options are forwarded to the LiveView for rendering. Refer to `Phoenix.LiveView.Helpers.live_render/3` for a list of supported render options. ## Examples {:ok, view, html} = live_isolated(conn, AppWeb.ClockLive, session: %{"tz" => "EST"}) Use `put_connect_params/2` to put connect params for a call to `Phoenix.LiveView.get_connect_params/1` in `c:Phoenix.LiveView.mount/3`: {:ok, view, html} = conn |> put_connect_params(%{"param" => "value"}) |> live_isolated(AppWeb.ClockLive, session: %{"tz" => "EST"}) """ defmacro live_isolated(conn, live_view, opts \\ []) do quote bind_quoted: binding(), unquote: true do unquote(__MODULE__).__isolated__(conn, @endpoint, live_view, opts) end end @doc false def __isolated__(conn, endpoint, live_view, opts) do put_in(conn.private[:phoenix_endpoint], endpoint || raise("no @endpoint set in test case")) |> Plug.Test.init_test_session(%{}) |> Phoenix.LiveView.Router.fetch_live_flash([]) |> Phoenix.LiveView.Controller.live_render(live_view, opts) |> connect_from_static_token(nil) end @doc false def __live__(%Plug.Conn{state: state, status: status} = conn) do path = rebuild_path(conn) case {state, status} do {:sent, 200} -> connect_from_static_token(conn, path) {:sent, 302} -> error_redirect_conn(conn) {:sent, _} -> raise ArgumentError, "request to #{conn.request_path} received unexpected #{status} response" {_, _} -> raise ArgumentError, """ a request has not yet been sent. live/1 must use a connection with a sent response. Either call get/2 prior to live/1, or use live/2 while providing a path to have a get request issued for you. For example issuing a get yourself: {:ok, view, _html} = conn |> get("#{path}") |> live() or performing the GET and live connect in a single step: {:ok, view, _html} = live(conn, "#{path}") """ end end @doc false def __live__(conn, path) do connect_from_static_token(conn, path) end defp connect_from_static_token( %Plug.Conn{status: 200, assigns: %{live_module: live_module}} = conn, path ) do DOM.ensure_loaded!() router = try do Phoenix.Controller.router_module(conn) rescue KeyError -> nil end start_proxy(path, %{ html: Phoenix.ConnTest.html_response(conn, 200), connect_params: conn.private[:live_view_connect_params] || %{}, connect_info: conn.private[:live_view_connect_info] || %{}, live_module: live_module, router: router, endpoint: Phoenix.Controller.endpoint_module(conn), session: maybe_get_session(conn), url: Plug.Conn.request_url(conn) }) end defp connect_from_static_token(%Plug.Conn{status: 200}, _path) do {:error, :nosession} end defp connect_from_static_token(%Plug.Conn{status: redir} = conn, _path) when redir in [301, 302] do error_redirect_conn(conn) end defp error_redirect_conn(conn) do to = hd(Plug.Conn.get_resp_header(conn, "location")) opts = if flash = conn.private[:phoenix_flash] do endpoint = Phoenix.Controller.endpoint_module(conn) %{to: to, flash: Phoenix.LiveView.Utils.sign_flash(endpoint, flash)} else %{to: to} end {:error, {error_redirect_key(conn), opts}} end defp error_redirect_key(%{private: %{phoenix_live_redirect: true}}), do: :live_redirect defp error_redirect_key(_), do: :redirect defp start_proxy(path, %{} = opts) do ref = make_ref() opts = Map.merge(opts, %{ caller: {self(), ref}, html: opts.html, connect_params: opts.connect_params, connect_info: opts.connect_info, live_module: opts.live_module, endpoint: opts.endpoint, session: opts.session, url: opts.url, test_supervisor: fetch_test_supervisor!() }) case ClientProxy.start_link(opts) do {:ok, _} -> receive do {^ref, {:ok, view, html}} -> {:ok, view, html} end {:error, reason} -> exit({reason, {__MODULE__, :live, [path]}}) :ignore -> receive do {^ref, {:error, reason}} -> {:error, reason} end end end # TODO: replace with ExUnit.Case.fetch_test_supervisor!() when we require Elixir v1.11. defp fetch_test_supervisor!() do case ExUnit.OnExitHandler.get_supervisor(self()) do {:ok, nil} -> opts = [strategy: :one_for_one, max_restarts: 1_000_000, max_seconds: 1] {:ok, sup} = Supervisor.start_link([], opts) ExUnit.OnExitHandler.put_supervisor(self(), sup) sup {:ok, sup} -> sup :error -> raise ArgumentError, "fetch_test_supervisor!/0 can only be invoked from the test process" end end defp maybe_get_session(%Plug.Conn{} = conn) do try do Plug.Conn.get_session(conn) rescue _ -> %{} end end defp rebuild_path(%Plug.Conn{request_path: request_path, query_string: ""}), do: request_path defp rebuild_path(%Plug.Conn{request_path: request_path, query_string: query_string}), do: request_path <> "?" <> query_string @doc """ Mounts, updates, and renders a component. If the component uses the `@myself` assigns, then an `id` must be given to it is marked as stateful. ## Examples assert render_component(MyComponent, id: 123, user: %User{}) =~ "some markup in component" assert render_component(MyComponent, %{id: 123, user: %User{}}, router: SomeRouter) =~ "some markup in component" """ defmacro render_component(component, assigns, opts \\ []) do endpoint = Module.get_attribute(__CALLER__.module, :endpoint) || raise ArgumentError, "the module attribute @endpoint is not set for #{inspect(__MODULE__)}" quote do Phoenix.LiveViewTest.__render_component__( unquote(endpoint), unquote(component).__live__(), unquote(assigns), unquote(opts) ) end end @doc false def __render_component__(endpoint, %{module: component}, assigns, opts) do socket = %Socket{endpoint: endpoint, router: opts[:router]} assigns = Map.new(assigns) # TODO: Make the ID required once we support only stateful module components as live_component mount_assigns = if assigns[:id], do: %{myself: %Phoenix.LiveComponent.CID{cid: -1}}, else: %{} rendered = Diff.component_to_rendered(socket, component, assigns, mount_assigns) {_, diff, _} = Diff.render(socket, rendered, Diff.new_components()) diff |> Diff.to_iodata() |> IO.iodata_to_binary() end @doc """ Sends a click event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-click` attribute in it. The event name given set on `phx-click` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument. If the element is does not have a `phx-click` attribute but it is a link (the `<a>` tag), the link will be followed accordingly: * if the link is a `live_patch`, the current view will be patched * if the link is a `live_redirect`, this function will return `{:error, {:live_redirect, %{to: url}}}`, which can be followed with `follow_redirect/2` * if the link is a regular link, this function will return `{:error, {:redirect, %{to: url}}}`, which can be followed with `follow_redirect/2` It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert view |> element("buttons", "Increment") |> render_click() =~ "The temperature is: 30℉" """ def render_click(element, value \\ %{}) def render_click(%Element{} = element, value), do: render_event(element, :click, value) def render_click(view, event), do: render_click(view, event, %{}) @doc """ Sends a click `event` to the `view` with `value` and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temperature is: 30℉" assert render_click(view, :inc) =~ "The temperature is: 31℉" """ def render_click(view, event, value) do render_event(view, :click, event, value) end @doc """ Sends a form submit event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-submit` attribute in it. The event name given set on `phx-submit` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values, including hidden input fields, can be given with the `value` argument. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert view |> element("form") |> render_submit(%{deg: 123, avatar: upload}) =~ "123 exceeds limits" To submit a form along with some with hidden input values: assert view |> form("#term", user: %{name: "hello"}) |> render_submit(%{user: %{"hidden_field" => "example"}}) =~ "Name updated" """ def render_submit(element, value \\ %{}) def render_submit(%Element{} = element, value), do: render_event(element, :submit, value) def render_submit(view, event), do: render_submit(view, event, %{}) @doc """ Sends a form submit event to the view and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_submit(view, :refresh, %{deg: 32}) =~ "The temp is: 32℉" """ def render_submit(view, event, value) do render_event(view, :submit, event, value) end @doc """ Sends a form change event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-change` attribute in it. The event name given set on `phx-change` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. If you need to pass any extra values or metadata, such as the "_target" parameter, you can do so by giving a map under the `value` argument. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert view |> element("form") |> render_change(%{deg: 123}) =~ "123 exceeds limits" # Passing metadata {:ok, view, html} = live(conn, "/thermo") assert view |> element("form") |> render_change(%{_target: ["deg"], deg: 123}) =~ "123 exceeds limits" As with `render_submit/2`, hidden input field values can be provided like so: refute view |> form("#term", user: %{name: "hello"}) |> render_change(%{user: %{"hidden_field" => "example"}}) =~ "can't be blank" """ def render_change(element, value \\ %{}) def render_change(%Element{} = element, value), do: render_event(element, :change, value) def render_change(view, event), do: render_change(view, event, %{}) @doc """ Sends a form change event to the view and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_change(view, :validate, %{deg: 123}) =~ "123 exceeds limits" """ def render_change(view, event, value) do render_event(view, :change, event, value) end @doc """ Sends a keydown event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-keydown` or `phx-window-keydown` attribute in it. The event name given set on `phx-keydown` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert view |> element("#inc") |> render_keydown() =~ "The temp is: 31℉" """ def render_keydown(element, value \\ %{}) def render_keydown(%Element{} = element, value), do: render_event(element, :keydown, value) def render_keydown(view, event), do: render_keydown(view, event, %{}) @doc """ Sends a keydown event to the view and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_keydown(view, :inc) =~ "The temp is: 31℉" """ def render_keydown(view, event, value) do render_event(view, :keydown, event, value) end @doc """ Sends a keyup event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-keyup` or `phx-window-keyup` attribute in it. The event name given set on `phx-keyup` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert view |> element("#inc") |> render_keyup() =~ "The temp is: 31℉" """ def render_keyup(element, value \\ %{}) def render_keyup(%Element{} = element, value), do: render_event(element, :keyup, value) def render_keyup(view, event), do: render_keyup(view, event, %{}) @doc """ Sends a keyup event to the view and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_keyup(view, :inc) =~ "The temp is: 31℉" """ def render_keyup(view, event, value) do render_event(view, :keyup, event, value) end @doc """ Sends a blur event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-blur` attribute in it. The event name given set on `phx-blur` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert view |> element("#inactive") |> render_blur() =~ "Tap to wake" """ def render_blur(element, value \\ %{}) def render_blur(%Element{} = element, value), do: render_event(element, :blur, value) def render_blur(view, event), do: render_blur(view, event, %{}) @doc """ Sends a blur event to the view and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_blur(view, :inactive) =~ "Tap to wake" """ def render_blur(view, event, value) do render_event(view, :blur, event, value) end @doc """ Sends a focus event given by `element` and returns the rendered result. The `element` is created with `element/3` and must point to a single element on the page with a `phx-focus` attribute in it. The event name given set on `phx-focus` is then sent to the appropriate LiveView (or component if `phx-target` is set accordingly). All `phx-value-*` entries in the element are sent as values. Extra values can be given with the `value` argument. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert view |> element("#inactive") |> render_focus() =~ "Tap to wake" """ def render_focus(element, value \\ %{}) def render_focus(%Element{} = element, value), do: render_event(element, :focus, value) def render_focus(view, event), do: render_focus(view, event, %{}) @doc """ Sends a focus event to the view and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_focus(view, :inactive) =~ "Tap to wake" """ def render_focus(view, event, value) do render_event(view, :focus, event, value) end @doc """ Sends a hook event to the view or an element and returns the rendered result. It returns the contents of the whole LiveView or an `{:error, redirect}` tuple. ## Examples {:ok, view, html} = live(conn, "/thermo") assert html =~ "The temp is: 30℉" assert render_hook(view, :refresh, %{deg: 32}) =~ "The temp is: 32℉" If you are pushing events from a hook to a component, then you must pass an `element`, created with `element/3`, as first argument and it must point to a single element on the page with a `phx-target` attribute in it: {:ok, view, _html} = live(conn, "/thermo") assert view |> element("#thermo-component") |> render_hook(:refresh, %{deg: 32}) =~ "The temp is: 32℉" """ def render_hook(view_or_element, event, value \\ %{}) def render_hook(%Element{} = element, event, value) do render_event(%{element | event: to_string(event)}, :hook, value) end def render_hook(view, event, value) do render_event(view, :hook, event, value) end defp render_event(%Element{} = element, type, value) when is_map(value) or is_list(value) do call(element, {:render_event, element, type, value}) end defp render_event(%View{} = view, type, event, value) when is_map(value) or is_list(value) do call(view, {:render_event, {proxy_topic(view), to_string(event), view.target}, type, value}) end @doc """ Simulates a `live_patch` to the given `path` and returns the rendered result. """ def render_patch(%View{} = view, path) when is_binary(path) do call(view, {:render_patch, proxy_topic(view), path}) end @doc """ Returns the current list of LiveView children for the `parent` LiveView. Children are returned in the order they appear in the rendered HTML. ## Examples {:ok, view, _html} = live(conn, "/thermo") assert [clock_view] = live_children(view) assert render_click(clock_view, :snooze) =~ "snoozing" """ def live_children(%View{} = parent) do call(parent, {:live_children, proxy_topic(parent)}) end @doc """ Gets the nested LiveView child by `child_id` from the `parent` LiveView. ## Examples {:ok, view, _html} = live(conn, "/thermo") assert clock_view = find_live_child(view, "clock") assert render_click(clock_view, :snooze) =~ "snoozing" """ def find_live_child(%View{} = parent, child_id) do parent |> live_children() |> Enum.find(fn %View{id: id} -> id == child_id end) end @doc """ Checks if the given element exists on the page. ## Examples assert view |> element("#some-element") |> has_element?() """ def has_element?(%Element{} = element) do call(element, {:render_element, :has_element?, element}) end @doc """ Checks if the given `selector` with `text_filter` is on `view`. See `element/3` for more information. ## Examples assert has_element?(view, "#some-element") """ def has_element?(%View{} = view, selector, text_filter \\ nil) do has_element?(element(view, selector, text_filter)) end @doc """ Returns the HTML string of the rendered view or element. If a view is provided, the entire LiveView is rendered. If a view after calling `with_target/2` or an element are given, only that particular context is returned. ## Examples {:ok, view, _html} = live(conn, "/thermo") assert render(view) =~ ~s|<button id="alarm">Snooze</div>| assert view |> element("#alarm") |> render() == "Snooze" """ def render(view_or_element) do view_or_element |> render_tree() |> DOM.to_html() end @doc """ Sets the target of the view for events. This emulates `phx-target` directly in tests, without having to dispatch the event to a specific element. This can be useful for invoking events to one or multiple components at the same time: view |> with_target("#user-1,#user-2") |> render_click("Hide", %{}) """ def with_target(%View{} = view, target) do %{view | target: target} end defp render_tree(%View{} = view) do render_tree(view, {proxy_topic(view), "render", view.target}) end defp render_tree(%Element{} = element) do render_tree(element, element) end defp render_tree(view_or_element, topic_or_element) do call(view_or_element, {:render_element, :find_element, topic_or_element}) end defp call(view_or_element, tuple) do try do GenServer.call(proxy_pid(view_or_element), tuple, 30_000) catch :exit, {{:shutdown, {kind, opts}}, _} when kind in [:redirect, :live_redirect] -> {:error, {kind, opts}} :exit, {{exception, stack}, _} -> exit({{exception, stack}, {__MODULE__, :call, [view_or_element]}}) else :ok -> :ok {:ok, result} -> result {:raise, exception} -> raise exception end end @doc """ Returns an element to scope a function to. It expects the current LiveView, a query selector, and a text filter. An optional text filter may be given to filter the results by the query selector. If the text filter is a string or a regex, it will match any element that contains the string or matches the regex. After the text filter is applied, only one element must remain, otherwise an error is raised. If no text filter is given, then the query selector itself must return a single element. assert view |> element("#term a:first-child()", "Increment") |> render() =~ "Increment</a>" Attribute selectors are also supported, and may be used on special cases like ids which contain periods: assert view |> element(~s{[href="/foo"][id="foo.bar.baz"]}) |> render() =~ "Increment</a>" """ def element(%View{proxy: proxy}, selector, text_filter \\ nil) when is_binary(selector) do %Element{proxy: proxy, selector: selector, text_filter: text_filter} end @doc """ Returns a form element to scope a function to. It expects the current LiveView, a query selector, and the form data. The query selector must return a single element. The form data will be validated directly against the form markup and make sure the data you are changing/submitting actually exists, failing otherwise. ## Examples assert view |> form("#term", user: %{name: "hello"}) |> render_submit() =~ "Name updated" This function is meant to mimic what the user can actually do, so you cannot set hidden input values. However, hidden values can be given when calling `render_submit/2` or `render_change/2`, see their docs for examples. """ def form(%View{proxy: proxy}, selector, form_data \\ %{}) when is_binary(selector) do %Element{proxy: proxy, selector: selector, form_data: form_data} end @doc """ Builds a file input for testing uploads within a form. Given the form DOM selector, the upload name, and a list of maps of client metadata for the upload, the returned file input can be passed to `render_upload/2`. Client metadata takes the following form: * `:last_modified` - the last modified timestamp * `:name` - the name of the file * `:content` - the binary content of the file * `:size` - the byte size of the content * `:type` - the MIME type of the file ## Examples avatar = file_input(lv, "#my-form-id", :avatar, [%{ last_modified: 1_594_171_879_000, name: "myfile.jpeg", content: File.read!("myfile.jpg"), size: 1_396_009, type: "image/jpeg" }]) assert render_upload(avatar, "foo.jpeg") =~ "100%" """ defmacro file_input(view, form_selector, name, entries) do quote bind_quoted: [view: view, selector: form_selector, name: name, entries: entries] do require Phoenix.ChannelTest builder = fn -> Phoenix.ChannelTest.connect(Phoenix.LiveView.Socket, %{}, %{}) end Phoenix.LiveViewTest.__file_input__(view, selector, name, entries, builder) end end @doc false def __file_input__(view, selector, name, entries, builder) do cid = find_cid!(view, selector) case Phoenix.LiveView.Channel.fetch_upload_config(view.pid, name, cid) do {:ok, %{external: false}} -> start_upload_client(builder, view, selector, name, entries, cid) {:ok, %{external: func}} when is_function(func) -> start_external_upload_client(view, selector, name, entries, cid) :error -> raise "no uploads allowed for #{name}" end end defp find_cid!(view, selector) do html_tree = view |> render() |> DOM.parse() with {:ok, form} <- DOM.maybe_one(html_tree, selector) do [cid | _] = DOM.targets_from_node(html_tree, form) cid else {:error, _reason, msg} -> raise ArgumentError, msg end end defp start_upload_client(socket_builder, view, form_selector, name, entries, cid) do spec = %{ id: make_ref(), start: {UploadClient, :start_link, [[socket_builder: socket_builder, cid: cid]]}, restart: :temporary } {:ok, pid} = Supervisor.start_child(fetch_test_supervisor!(), spec) Upload.new(pid, view, form_selector, name, entries, cid) end defp start_external_upload_client(view, form_selector, name, entries, cid) do spec = %{ id: make_ref(), start: {UploadClient, :start_link, [[cid: cid]]}, restart: :temporary } {:ok, pid} = Supervisor.start_child(fetch_test_supervisor!(), spec) Upload.new(pid, view, form_selector, name, entries, cid) end @doc """ Returns the most recent title that was updated via a `page_title` assign. ## Examples render_click(view, :event_that_triggers_page_title_update) assert page_title(view) =~ "my title" """ def page_title(view) do call(view, :page_title) end @doc """ Asserts a live patch will happen within `timeout` milliseconds. The default `timeout` is 100. It returns the new path. To assert on the flash message, you can assert on the result of the rendered LiveView. ## Examples render_click(view, :event_that_triggers_patch) assert_patch view render_click(view, :event_that_triggers_patch) assert_patch view, 30 render_click(view, :event_that_triggers_patch) path = assert_patch view assert path =~ ~r/path/\d+/ """ def assert_patch(view, timeout \\ 100) def assert_patch(view, timeout) when is_integer(timeout) do {path, _flash} = assert_navigation(view, :patch, nil, timeout) path end def assert_patch(view, to) when is_binary(to), do: assert_patch(view, to, 100) @doc """ Asserts a live patch will to a given path within `timeout` milliseconds. The default `timeout` is 100. It always returns `:ok`. To assert on the flash message, you can assert on the result of the rendered LiveView. ## Examples render_click(view, :event_that_triggers_patch) assert_patch view, "/path" render_click(view, :event_that_triggers_patch) assert_patch view, "/path", 30 """ def assert_patch(view, to, timeout) when is_binary(to) and is_integer(timeout) do assert_navigation(view, :patch, to, timeout) :ok end @doc """ Asserts a live patch was performed, and returns the new path. To assert on the flash message, you can assert on the result of the rendered LiveView. ## Examples render_click(view, :event_that_triggers_redirect) assert_patched view, "/path" render_click(view, :event_that_triggers_redirect) path = assert_patched view assert path =~ ~r/path/\d+/ """ def assert_patched(view, to) do assert_patch(view, to, 0) end @doc """ Asserts a redirect will happen within `timeout` milliseconds. The default `timeout` is 100. It returns a tuple containing the new path and the flash messages from said redirect, if any. Note the flash will contain string keys. ## Examples render_click(view, :event_that_triggers_redirect) {_path, flash} = assert_redirect view assert flash["info"] == "Welcome" assert path =~ ~r/path\/\d+/ render_click(view, :event_that_triggers_redirect) assert_redirect view, 30 """ def assert_redirect(view, timeout \\ 100) def assert_redirect(view, timeout) when is_integer(timeout) do assert_navigation(view, :redirect, nil, timeout) end def assert_redirect(view, to) when is_binary(to), do: assert_redirect(view, to, 100) @doc """ Asserts a redirect will happen to a given path within `timeout` milliseconds. The default `timeout` is 100. It returns the flash messages from said redirect, if any. Note the flash will contain string keys. ## Examples render_click(view, :event_that_triggers_redirect) flash = assert_redirect view, "/path" assert flash["info"] == "Welcome" render_click(view, :event_that_triggers_redirect) assert_redirect view, "/path", 30 """ def assert_redirect(view, to, timeout) when is_binary(to) and is_integer(timeout) do {_path, flash} = assert_navigation(view, :redirect, to, timeout) flash end @doc """ Asserts a redirect was performed. It returns a tuple containing the new path and the flash messages from said redirect, if any. Note the flash will contain string keys. ## Examples render_click(view, :event_that_triggers_redirect) {_path, flash} = assert_redirected view, "/path" assert flash["info"] == "Welcome" render_click(view, :event_that_triggers_redirect) {path, flash} = assert_redirected view assert flash["info"] == "Welcome" assert path =~ ~r/path\/\d+/ """ def assert_redirected(view, to \\ nil) do assert_redirect(view, to, 0) end defp assert_navigation(view, kind, to, timeout) do %{proxy: {ref, topic, _}, endpoint: endpoint} = view receive do {^ref, {^kind, ^topic, %{to: new_to} = opts}} when new_to == to or to == nil -> {new_to, Phoenix.LiveView.Utils.verify_flash(endpoint, opts[:flash])} after timeout -> message = if to do "expected #{inspect(view.module)} to #{kind} to #{inspect(to)}, " else "expected #{inspect(view.module)} to #{kind}, " end case flush_navigation(ref, topic, nil) do nil -> raise ArgumentError, message <> "but got none" {kind, to} -> raise ArgumentError, message <> "but got a #{kind} to #{inspect(to)}" end end end defp flush_navigation(ref, topic, last) do receive do {^ref, {kind, ^topic, %{to: to}}} when kind in [:patch, :redirect] -> flush_navigation(ref, topic, {kind, to}) after 0 -> last end end @doc """ Open the default browser to display current HTML of `view_or_element`. ## Examples view |> element("#term a:first-child()", "Increment") |> open_browser() assert view |> form("#term", user: %{name: "hello"}) |> open_browser() |> render_submit() =~ "Name updated" """ def open_browser(view_or_element, open_fun \\ &open_with_system_cmd/1) def open_browser(view_or_element, open_fun) when is_function(open_fun, 1) do html = render_tree(view_or_element) view_or_element |> maybe_wrap_html(html) |> write_tmp_html_file() |> open_fun.() view_or_element end defp maybe_wrap_html(view_or_element, content) do {html, static_path} = call(view_or_element, :html) head = case DOM.maybe_one(html, "head") do {:ok, head} -> head _ -> {"head", [], []} end case Floki.attribute(content, "data-phx-main") do ["true" | _] -> # If we are rendering the main LiveView, # we return the full page html. html _ -> # Otherwise we build a basic html structure around the # view_or_element content. [ {"html", [], [ head, {"body", [], [ content ]} ]} ] end |> Floki.traverse_and_update(fn {"script", _, _} -> nil {"a", _, _} = link -> link {el, attrs, children} -> {el, maybe_prefix_static_path(attrs, static_path), children} el -> el end) end defp maybe_prefix_static_path(attrs, nil), do: attrs defp maybe_prefix_static_path(attrs, static_path) do Enum.map(attrs, fn {"src", path} -> {"src", prefix_static_path(path, static_path)} {"href", path} -> {"href", prefix_static_path(path, static_path)} attr -> attr end) end defp prefix_static_path(<<"//" <> _::binary>> = url, _prefix), do: url defp prefix_static_path(<<"/" <> _::binary>> = path, prefix), do: "file://#{Path.join([prefix, path])}" defp prefix_static_path(url, _), do: url defp write_tmp_html_file(html) do html = Floki.raw_html(html) path = Path.join([System.tmp_dir!(), "#{Phoenix.LiveView.Utils.random_id()}.html"]) File.write!(path, html) path end defp open_with_system_cmd(path) do cmd = case :os.type() do {:unix, :darwin} -> "open" {:unix, _} -> "xdg-open" {:win32, _} -> "start" end System.cmd(cmd, [path]) end @doc """ Asserts an event will be pushed within `timeout`. ## Examples assert_push_event view, "scores", %{points: 100, user: "josé"} """ defmacro assert_push_event(view, event, payload, timeout \\ 100) do quote do %{proxy: {ref, _topic, _}} = unquote(view) assert_receive {^ref, {:push_event, unquote(event), unquote(payload)}}, unquote(timeout) end end @doc """ Asserts a hook reply was returned from a `handle_event` callback. ## Examples assert_reply view, %{result: "ok", transaction_id: _} """ defmacro assert_reply(view, payload, timeout \\ 100) do quote do %{proxy: {ref, _topic, _}} = unquote(view) assert_receive {^ref, {:reply, unquote(payload)}}, unquote(timeout) end end @doc """ Follows the redirect from a `render_*` action or an `{:error, redirect}` tuple. Imagine you have a LiveView that redirects on a `render_click` event. You can make it sure it immediately redirects after the `render_click` action by calling `follow_redirect/3`: live_view |> render_click("redirect") |> follow_redirect(conn) Or in the case of an error tuple: assert {:error, {:redirect, %{to: "/somewhere"}}} = result = live(conn, "my-path") {:ok, view, html} = follow_redirect(result, conn) `follow_redirect/3` expects a connection as second argument. This is the connection that will be used to perform the underlying request. If the LiveView redirects with a live redirect, this macro returns `{:ok, live_view, disconnected_html}` with the content of the new LiveView, the same as the `live/3` macro. If the LiveView redirects with a regular redirect, this macro returns `{:ok, conn}` with the rendered redirected page. In any other case, this macro raises. Finally, note that you can optionally assert on the path you are being redirected to by passing a third argument: live_view |> render_click("redirect") |> follow_redirect(conn, "/redirected/page") """ defmacro follow_redirect(reason, conn, to \\ nil) do quote bind_quoted: binding() do case reason do {:error, {:live_redirect, opts}} -> {conn, to} = Phoenix.LiveViewTest.__follow_redirect__(conn, to, opts) live(conn, to) {:error, {:redirect, opts}} -> {conn, to} = Phoenix.LiveViewTest.__follow_redirect__(conn, to, opts) {:ok, get(conn, to)} _ -> raise "LiveView did not redirect" end end end @doc false def __follow_redirect__(conn, expected_to, %{to: to} = opts) do if expected_to && expected_to != to do raise ArgumentError, "expected LiveView to redirect to #{inspect(expected_to)}, but got #{inspect(to)}" end conn = Phoenix.ConnTest.ensure_recycled(conn) if flash = opts[:flash] do {Phoenix.ConnTest.put_req_cookie(conn, @flash_cookie, flash), to} else {conn, to} end end @doc """ Performs a live redirect from one LiveView to another. When redirecting between two LiveViews of the same `live_session`, mounts the new LiveView and shutsdown the previous one, which mimicks general browser live navigation behaviour. When attempting to navigate from a LiveView of a different `live_session`, an error redirect condition is returned indicating a failed `live_redirect` from the client. ## Examples assert {:ok, page_live, _html} = live(conn, "/page/1") assert {:ok, page2_live, _html} = live(conn, "/page/2") assert {:error, {:redirect, _}} = live_redirect(page2_live, to: "/admin") """ def live_redirect(view, opts) do Phoenix.LiveViewTest.__live_redirect__(view, opts) end @doc false def __live_redirect__(%View{} = view, opts, token_func \\ &(&1)) do {session, %ClientProxy{} = root} = ClientProxy.root_view(proxy_pid(view)) url = case Keyword.fetch!(opts, :to) do "/" <> path -> URI.merge(root.uri, path) url -> url end live_module = case Phoenix.LiveView.Route.live_link_info(root.endpoint, root.router, url) do {:internal, route} -> route.view _ -> raise ArgumentError, """ attempted to live_redirect to a non-live route at #{inspect(url)} """ end html = render(view) ClientProxy.stop(proxy_pid(view), {:shutdown, :duplicate_topic}) root_token = token_func.(root.session_token) static_token = token_func.(root.static_token) start_proxy(url, %{ html: html, live_redirect: {root.id, root_token, static_token}, connect_params: root.connect_params, connect_info: root.connect_info, live_module: live_module, endpoint: root.endpoint, router: root.router, session: session, url: url }) end @doc """ Receives a `form_element` and asserts that `phx-trigger-action` has been set to true, following up on that request. Imagine you have a LiveView that sends an HTTP form submission. Say that it sets the `phx-trigger-action` to true, as a response to a submit event. You can follow the trigger action like this: form = form(live_view, selector, %{"form" => "data"}) # First we submit the form. Optionally verify that phx-trigger-action # is now part of the form. assert render_submit(form) =~ ~r/phx-trigger-action/ # Now follow the request made by the form conn = follow_trigger_action(form, conn) assert conn.method == "POST" assert conn.params == %{"form" => "data"} """ defmacro follow_trigger_action(form, conn) do quote bind_quoted: binding() do {method, path, form_data} = Phoenix.LiveViewTest.__render_trigger_event__(form) dispatch(conn, @endpoint, method, path, form_data) end end def __render_trigger_event__(%Element{} = form) do case render_tree(form) do {"form", attrs, _child_nodes} -> unless List.keymember?(attrs, "phx-trigger-action", 0) do raise ArgumentError, "could not follow trigger action because form #{inspect(form.selector)} " <> "does not have phx-trigger-action attribute, got: #{inspect(attrs)}" end {"action", path} = List.keyfind(attrs, "action", 0) || {"action", call(form, :url)} {"method", method} = List.keyfind(attrs, "method", 0) || {"method", "get"} {method, path, form.form_data || %{}} {tag, _, _} -> raise ArgumentError, "could not follow trigger action because given element did not return a form, " <> "got #{inspect(tag)} instead" end end defp proxy_pid(%{proxy: {_ref, _topic, pid}}), do: pid defp proxy_topic(%{proxy: {_ref, topic, _pid}}), do: topic @doc """ Performs an upload of a file input and renders the result. See `file_input/4` for details on building a file input. ## Examples Given the following LiveView template: <%= for entry <- @uploads.avatar.entries do %> <%= entry.name %>: <%= entry.progress %>% <% end %> Your test case can assert the uploaded content: avatar = file_input(lv, "#my-form-id", :avatar, [ %{ last_modified: 1_594_171_879_000, name: "myfile.jpeg", content: File.read!("myfile.jpg"), size: 1_396_009, type: "image/jpeg" } ]) assert render_upload(avatar, "foo.jpeg") =~ "100%" By default, the entire file is chunked to the server, but an optional percentage to chunk can be passed to test chunk-by-chunk uploads: assert render_upload(avatar, "foo.jpeg", 49) =~ "49%" assert render_upload(avatar, "foo.jpeg", 51) =~ "100%" """ def render_upload(%Upload{} = upload, entry_name, percent \\ 100) do if UploadClient.allow_acknowledged?(upload) do render_chunk(upload, entry_name, percent) else case preflight_upload(upload) do {:ok, %{ref: ref, config: config, entries: entries_resp}} -> case UploadClient.allowed_ack(upload, ref, config, entries_resp) do :ok -> render_chunk(upload, entry_name, percent) {:error, reason} -> {:error, reason} end {:error, reason} -> {:error, reason} end end end @doc """ Performs a preflight upload request. Useful for testing external uploaders to retrieve the `:external` entry metadata. ## Examples avatar = file_input(lv, "#my-form-id", :avatar, [%{name: ..., ...}, ...]) assert {:ok, %{ref: _ref, config: %{chunk_size: _}}} = preflight_upload(avatar) """ def preflight_upload(%Upload{} = upload) do # LiveView channel returns error conditions as error key in payload, ie `%{error: reason}` case call( upload.element, {:render_event, upload.element, :allow_upload, {upload.entries, upload.cid}} ) do %{error: reason} -> {:error, reason} %{ref: _ref} = resp -> {:ok, resp} end end defp render_chunk(upload, entry_name, percent) do {:ok, _} = UploadClient.chunk(upload, entry_name, percent, proxy_pid(upload.view)) render(upload.view) end end
31.72185
98
0.65243
e8300ce8eaa2edb175b1d950c16965a208ff8926
2,194
ex
Elixir
kousa/lib/beef/users.ex
Jawkx/dogehouse
eea5954aec56961a3c0144289e2ed4da739739c3
[ "MIT" ]
1
2021-04-19T19:32:51.000Z
2021-04-19T19:32:51.000Z
kousa/lib/beef/users.ex
Jawkx/dogehouse
eea5954aec56961a3c0144289e2ed4da739739c3
[ "MIT" ]
null
null
null
kousa/lib/beef/users.ex
Jawkx/dogehouse
eea5954aec56961a3c0144289e2ed4da739739c3
[ "MIT" ]
null
null
null
defmodule Beef.Users do @moduledoc """ Context module for Users. This module acts as a "gateway" module defining the "boundary" for Users database access. Consider Beef.Users.* modules to be "private modules". If in the future we would like to enforce these boundary conditions at compile time, consider using Sasa Juric's Boundary library: https://hex.pm/packages/boundary NB (5 Mar 2021): these functions are probably going to get streamlined =D """ # ACCESS functions defdelegate find_by_github_ids(ids), to: Beef.Access.Users defdelegate get_by_id(user_id), to: Beef.Access.Users defdelegate get_by_id_with_follow_info(me_id, them_id), to: Beef.Access.Users defdelegate get_by_username(username), to: Beef.Access.Users defdelegate search(query, offset), to: Beef.Access.Users defdelegate get_users_in_current_room(user_id), to: Beef.Access.Users defdelegate tuple_get_current_room_id(user_id), to: Beef.Access.Users defdelegate get_by_id_with_current_room(user_id), to: Beef.Access.Users defdelegate get_current_room(user_id), to: Beef.Access.Users defdelegate get_current_room_id(user_id), to: Beef.Access.Users # MUTATIONS defdelegate edit_profile(user_id, data), to: Beef.Mutations.Users defdelegate delete(user_id), to: Beef.Mutations.Users defdelegate bulk_insert(users), to: Beef.Mutations.Users defdelegate inc_num_following(user_id, n), to: Beef.Mutations.Users defdelegate set_reason_for_ban(user_id, reason_for_ban), to: Beef.Mutations.Users defdelegate set_online(user_id), to: Beef.Mutations.Users defdelegate set_user_left_current_room(user_id), to: Beef.Mutations.Users defdelegate set_offline(user_id), to: Beef.Mutations.Users defdelegate set_current_room(user_id, room_id), to: Beef.Mutations.Users # TODO: make can_speak, returning, a single keyword list defdelegate set_current_room(user_id, room_id, can_speak), to: Beef.Mutations.Users defdelegate set_current_room(user_id, room_id, can_speak, returning), to: Beef.Mutations.Users defdelegate twitter_find_or_create(user), to: Beef.Mutations.Users defdelegate github_find_or_create(user, github_access_token), to: Beef.Mutations.Users end
48.755556
96
0.793072
e8301e9644ee66bb4a1937f5615e96ee9a22d822
2,554
exs
Elixir
test/controllers/target_controller_test.exs
nsarno/winter
a65a6aa61d2b1af39277338277f8b3f479643939
[ "MIT" ]
3
2015-08-24T11:44:19.000Z
2016-10-01T21:37:05.000Z
test/controllers/target_controller_test.exs
nsarno/winter
a65a6aa61d2b1af39277338277f8b3f479643939
[ "MIT" ]
null
null
null
test/controllers/target_controller_test.exs
nsarno/winter
a65a6aa61d2b1af39277338277f8b3f479643939
[ "MIT" ]
null
null
null
defmodule Storm.TargetControllerTest do use Storm.ConnCase alias Storm.Target @valid_attrs %{url: "https://gist.github.com/", method: "GET"} @invalid_attrs %{url: nil, method: nil} setup do user = factory(%Storm.User{}, :insert) token = Storm.AuthToken.generate_token(user) project = factory(%Storm.Project{user_id: user.id}, :insert) mission = factory(%Storm.Mission{project_id: project.id}, :insert) target = factory(%Target{mission_id: mission.id}, :insert) conn = conn() |> put_req_header("accept", "application/json") |> put_req_header("authorization", "Bearer " <> token.jwt) {:ok, conn: conn, mission: mission, target: target} end test "lists all entries on index", %{conn: conn, mission: m} do conn = get conn, mission_target_path(conn, :index, m) assert [%{}] = json_response(conn, 200)["targets"] end test "shows chosen resource", %{conn: conn, target: t} do conn = get conn, target_path(conn, :show, t) assert json_response(conn, 200)["target"] == %{ "id" => t.id, "method" => t.method, "url" => t.url } end test "does not show resource and instead throw error when id is nonexistent", %{conn: conn} do assert_raise Ecto.NoResultsError, fn -> get conn, target_path(conn, :show, -1) end end test "creates and renders resource when data is valid", %{conn: conn, mission: m} do conn = post conn, mission_target_path(conn, :create, m.id), target: @valid_attrs assert json_response(conn, 200)["target"]["id"] assert Repo.get_by(Target, @valid_attrs) end test "does not create resource and renders errors when data is invalid", %{conn: conn, mission: m} do conn = post conn, mission_target_path(conn, :create, m.id), target: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "updates and renders chosen resource when data is valid", %{conn: conn, target: t} do conn = put conn, target_path(conn, :update, t), target: @valid_attrs assert json_response(conn, 200)["target"]["id"] assert Repo.get_by(Target, @valid_attrs) end test "does not update chosen resource and renders errors when data is invalid", %{conn: conn, target: t} do conn = put conn, target_path(conn, :update, t), target: @invalid_attrs assert json_response(conn, 422)["errors"] != %{} end test "deletes chosen resource", %{conn: conn, target: t} do conn = delete conn, target_path(conn, :delete, t) assert response(conn, 204) refute Repo.get(Target, t.id) end end
36.485714
109
0.668363
e830249147c26b84ab4d05833ad17ecc093883ce
850
exs
Elixir
test/plug/crypto_test.exs
gjaldon/plug
bfe88530b429c7b9b29b69b737772ef7c6aa2f6b
[ "Apache-2.0" ]
1
2019-05-07T15:05:52.000Z
2019-05-07T15:05:52.000Z
test/plug/crypto_test.exs
gjaldon/plug
bfe88530b429c7b9b29b69b737772ef7c6aa2f6b
[ "Apache-2.0" ]
null
null
null
test/plug/crypto_test.exs
gjaldon/plug
bfe88530b429c7b9b29b69b737772ef7c6aa2f6b
[ "Apache-2.0" ]
null
null
null
defmodule Plug.CryptoTest do use ExUnit.Case, async: true import Plug.Crypto test "masks tokens" do assert mask(<<0, 1, 0, 1>>, <<0, 1, 1, 0>>) == <<0, 0, 1, 1>> assert mask(<<0, 0, 1, 1>>, <<0, 1, 1, 0>>) == <<0, 1, 0, 1>> end test "compares binaries securely" do assert secure_compare(<<>>, <<>>) assert secure_compare(<<0>>, <<0>>) refute secure_compare(<<>>, <<1>>) refute secure_compare(<<1>>, <<>>) refute secure_compare(<<0>>, <<1>>) end test "compares masked binaries securely" do assert masked_compare(<<>>, <<>>, <<>>) assert masked_compare(<<0>>, <<0>>, <<0>>) assert masked_compare(<<0, 1, 0, 1>>, <<0, 0, 1, 1>>, <<0, 1, 1, 0>>) refute masked_compare(<<>>, <<1>>, <<0>>) refute masked_compare(<<1>>, <<>>, <<0>>) refute masked_compare(<<0>>, <<1>>, <<0>>) end end
29.310345
73
0.529412
e8302c3b9a5d4b99e19f674e6eecf1b3a7a60bd2
4,431
ex
Elixir
lib/sanbase/user_lists/settings.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
lib/sanbase/user_lists/settings.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
1
2021-07-24T16:26:03.000Z
2021-07-24T16:26:03.000Z
lib/sanbase/user_lists/settings.ex
sitedata/sanbase2
8da5e44a343288fbc41b68668c6c80ae8547d557
[ "MIT" ]
null
null
null
defmodule Sanbase.UserList.Settings do @moduledoc ~s""" Store and work with settings specific for a watchlist. The settings are stored per user. One watchlist can have many settings for many users. When a user requires the settings for a watchlist the resolution process is the first one that matches: 1. If the requesting user has defined settings - return them. 2. If the watchlist craetor has defined settings - return them. 3. Return the default settings """ defmodule WatchlistSettings do @moduledoc ~s""" Embeded schema that defines how the settings look like """ use Ecto.Schema import Ecto.Changeset @type t :: %{ page_size: non_neg_integer(), table_columns: map(), time_window: String.t() } @default_page_size 20 @default_time_window "180d" @default_table_columns %{} embedded_schema do field(:page_size, :integer, default: @default_page_size) field(:time_window, :string, default: @default_time_window) field(:table_columns, :map, default: @default_table_columns) end def changeset(%__MODULE__{} = settings, attrs \\ %{}) do settings |> cast(attrs, [:page_size, :time_window, :table_columns]) |> validate_number(:page_size, greater_than: 0) |> validate_change(:time_window, &valid_time_window?/2) end def default_settings() do %{ page_size: @default_page_size, time_window: @default_time_window, table_columns: @default_table_columns } end # Private functions defp valid_time_window?(:time_window, time_window) do case Sanbase.Validation.valid_time_window?(time_window) do :ok -> [] {:error, error} -> [time_window: error] end end end use Ecto.Schema import Ecto.Query import Ecto.Changeset alias Sanbase.Repo alias Sanbase.Auth.User alias Sanbase.UserList alias __MODULE__.WatchlistSettings @type t :: %__MODULE__{ user_id: non_neg_integer(), watchlist_id: non_neg_integer(), settings: WatchlistSettings.t() } @primary_key false schema "watchlist_settings" do belongs_to(:user, User, foreign_key: :user_id, primary_key: true) belongs_to(:watchlist, UserList, foreign_key: :watchlist_id, primary_key: true) embeds_one(:settings, WatchlistSettings, on_replace: :update) end def changeset(%__MODULE__{} = settings, attrs \\ %{}) do settings |> cast(attrs, [:user_id, :watchlist_id]) |> cast_embed(:settings, required: true, with: &WatchlistSettings.changeset/2 ) end @doc ~s""" Return the settings for a watchlist and a given user. Returns the first one that exists: 1. User's settings for that watchlist 2. The watchlist's creator's settings for that watchlist 3. Default settings """ @spec settings_for(%UserList{}, %User{} | nil) :: {:ok, WatchlistSettings.t()} def settings_for(%UserList{} = ul, %User{} = user) do settings = get_settings(ul.id, user.id) || get_settings(ul.id, ul.user_id) || WatchlistSettings.default_settings() {:ok, settings} end def settings_for(%UserList{} = ul, _) do settings = get_settings(ul.id, ul.user_id) || WatchlistSettings.default_settings() {:ok, settings} end @doc ~s""" Create or update settings for a given watchlist and user """ @spec update_or_create_settings(watchlist_id, user_id, settings) :: {:ok, t()} | {:error, Ecto.Changeset.t()} when watchlist_id: non_neg_integer, user_id: non_neg_integer, settings: WatchlistSettings.t() def update_or_create_settings(watchlist_id, user_id, settings) do case Repo.one(settings_query(watchlist_id, user_id)) do nil -> changeset(%__MODULE__{}, %{ user_id: user_id, watchlist_id: watchlist_id, settings: settings }) |> Repo.insert() %__MODULE__{} = ws -> changeset(ws, %{settings: settings}) |> Repo.update() end end # Private functions defp get_settings(watchlist_id, user_id) do from(s in settings_query(watchlist_id, user_id), select: s.settings) |> Repo.one() end defp settings_query(watchlist_id, user_id) do from(s in __MODULE__, where: s.watchlist_id == ^watchlist_id and s.user_id == ^user_id ) end end
28.403846
83
0.658993
e830916c4c9c0db0e3fe0a911ca8e144e9cf5e97
443
ex
Elixir
lib/guardian.ex
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
40
2018-07-04T19:13:45.000Z
2021-12-16T23:53:43.000Z
lib/guardian.ex
cesium/safira
07a02f54f9454db1cfb5a510da68f40c47dcd916
[ "MIT" ]
94
2018-07-25T13:13:39.000Z
2022-02-15T04:09:42.000Z
lib/guardian.ex
cesium/safira
10dd45357c20e8afc22563f114f49ccb74008114
[ "MIT" ]
5
2018-11-26T17:19:03.000Z
2021-02-23T08:09:37.000Z
defmodule Safira.Guardian do use Guardian, otp_app: :safira def subject_for_token(user, _claims) do sub = to_string(user.id) {:ok, sub} end def subject_for_token(_, _) do {:error, :reason_for_error} end def resource_from_claims(claims) do id = claims["sub"] resource = Safira.Accounts.get_user!(id) {:ok, resource} end def resource_from_claims(_claims) do {:error, :reason_for_error} end end
19.26087
44
0.681716
e830955c99c9138a0e015e03f435c720db1dcba8
849
ex
Elixir
lib/acme/resources/challenge.ex
sikanhe/acme
2c28818a2edea5c570dcb1ab09de695b5e0a4021
[ "MIT" ]
44
2017-03-31T15:55:48.000Z
2022-02-21T11:16:26.000Z
lib/acme/resources/challenge.ex
sikanhe/acme
2c28818a2edea5c570dcb1ab09de695b5e0a4021
[ "MIT" ]
7
2017-07-12T09:36:57.000Z
2018-01-18T21:30:43.000Z
lib/acme/resources/challenge.ex
sikanhe/acme
2c28818a2edea5c570dcb1ab09de695b5e0a4021
[ "MIT" ]
6
2017-11-20T05:04:10.000Z
2019-07-09T11:12:41.000Z
defmodule Acme.Challenge do defstruct [:token, :status, :type, :uri] def from_map(%{ "type" => type, "status" => status, "uri" => uri, "token" => token }) do %__MODULE__{ type: type, status: status, uri: uri, token: token } end @doc """ Creates a KeyAuthorization from a challenge token and a account key in jwk """ def create_key_authorization(%__MODULE__{token: token}, jwk) do create_key_authorization(token, jwk) end def create_key_authorization(token, jwk) do thumbprint = JOSE.JWK.thumbprint(jwk) "#{token}.#{thumbprint}" end def generate_dns_txt_record(%__MODULE__{type: "dns-01", token: token}, jwk) do ka = create_key_authorization(token, jwk) :crypto.hash(:sha256, ka) |> Base.url_encode64(padding: false) end end
22.342105
80
0.62662
e830aee7b275468d0bb132efb444ab2692b4a294
4,341
ex
Elixir
harbor/test/_support/ws_client.ex
miapolis/port7
7df1223f83d055eeb6ce8f61f4af8b4f2cf33e74
[ "MIT" ]
null
null
null
harbor/test/_support/ws_client.ex
miapolis/port7
7df1223f83d055eeb6ce8f61f4af8b4f2cf33e74
[ "MIT" ]
null
null
null
harbor/test/_support/ws_client.ex
miapolis/port7
7df1223f83d055eeb6ce8f61f4af8b4f2cf33e74
[ "MIT" ]
null
null
null
defmodule PierTest.WsClient do use WebSockex @api_url Application.compile_env!(:harbor, :api_url) def child_spec(info) do info |> super |> Map.put(:id, UUID.uuid4()) end def start_link(_opts) do ancestors = :"$ancestors" |> Process.get() |> :erlang.term_to_binary() |> Base.encode16() @api_url |> Path.join("socket") |> WebSockex.start_link(__MODULE__, nil, extra_headers: [{"user-agent", ancestors}, {"x-forwarded-for", "127.0.0.1"}] ) end def send_call(client_ws, op, payload) do call_ref = UUID.uuid4() WebSockex.cast( client_ws, {:send, %{"op" => op, "p" => payload, "ref" => call_ref}} ) call_ref end def do_call(ws, op, payload) do ref = send_call(ws, op, payload) reply_op = op <> ":reply" receive do {:text, %{"op" => ^reply_op, "ref" => ^ref, "p" => payload}, ^ws} -> payload after 100 -> raise "reply to `#{op}` not received" end end def send_msg(client_ws, op, payload) do WebSockex.cast(client_ws, {:send, %{"op" => op, "p" => payload}}) end defp send_msg_impl(map, test_pid) do {:reply, {:text, Jason.encode!(map)}, test_pid} end def forward_frames(client_ws), do: WebSockex.cast(client_ws, {:forward_frames, self()}) defp forward_frames_impl(test_pid, _state), do: {:ok, test_pid} defmacro assert_frame(op, payload, from \\ nil) do if from do quote do from = unquote(from) ExUnit.Assertions.assert_receive( {:text, %{"op" => unquote(op), "d" => unquote(payload)}, ^from} ) end else quote do ExUnit.Assertions.assert_receive( {:text, %{"op" => unquote(op), "d" => unquote(payload)}, _} ) end end end defmacro assert_reply(op, ref, payload, from \\ nil) do if from do quote do op = unquote(op) from = unquote(from) ref = unquote(ref) ExUnit.Assertions.assert_receive( {:text, %{"op" => ^op, "p" => unquote(payload), "ref" => ^ref}, ^from} ) end else quote do op = unquote(op) ref = unquote(ref) ExUnit.Assertions.assert_receive( {:text, %{"op" => ^op, "p" => unquote(payload), "ref" => ^ref}, _} ) end end end defmacro assert_error(op, ref, error, from \\ nil) do if from do quote do op = unquote(op) from = unquote(from) ref = unquote(ref) ExUnit.Assertions.assert_receive( {:text, %{"op" => ^op, "e" => unquote(error), "ref" => ^ref}, ^from} ) end else quote do op = unquote(op) ref = unquote(ref) ExUnit.Assertions.assert_receive( {:text, %{"op" => ^op, "e" => unquote(error), "ref" => ^ref}, _} ) end end end defmacro assert_dies(client_ws, fun, reason, timeout \\ 100) do quote bind_quoted: [client_ws: client_ws, fun: fun, reason: reason, timeout: timeout] do Process.flag(:trap_exit, true) Process.link(client_ws) fun.() ExUnit.Assertions.assert_receive({:EXIT, ^client_ws, ^reason}, timeout) end end defmacro refute_frame(op, from) do quote do from = unquote(from) ExUnit.Assertions.refute_receive({:text, %{"op" => unquote(op)}, ^from}) end end ### - ROUTER - ###################################################################### @impl true def handle_frame({type, data}, test_pid) do send(test_pid, {type, Jason.decode!(data), self()}) {:ok, test_pid} end @impl true def handle_cast({:send, map}, test_pid), do: send_msg_impl(map, test_pid) def handle_cast({:forward_frames, test_pid}, state), do: forward_frames_impl(test_pid, state) end defmodule PierTest.WsClientFactory do alias PierTest.WsClient require WsClient # import ExUnit.Assertions def create_client_for(user_id, _opts \\ []) do client_ws = ExUnit.Callbacks.start_supervised!(WsClient) WsClient.forward_frames(client_ws) WsClient.do_call(client_ws, "auth:request", %{ "userToken" => user_id, "nickname" => "TEST USER" }) [{usersession_pid, _}] = Registry.lookup(Anchorage.UserSessionRegistry, user_id) Process.link(usersession_pid) client_ws end end
24.805714
95
0.577747
e830b456005f5e45bd40239c571491604d1c70a3
1,273
exs
Elixir
config/config.exs
langens-jonathan/sparql
9bd4aa7d95fa860cae77f59a17c022771097c9b6
[ "MIT" ]
null
null
null
config/config.exs
langens-jonathan/sparql
9bd4aa7d95fa860cae77f59a17c022771097c9b6
[ "MIT" ]
null
null
null
config/config.exs
langens-jonathan/sparql
9bd4aa7d95fa860cae77f59a17c022771097c9b6
[ "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 your application as: # # config :sparqlex, key: :value config :sparqlex, author: :flowofcontrol # # and access this configuration in your application as: # # Application.get_env(:sparql, :key) # # You can also configure a 3rd-party app: # # config :logger, level: :info # # It is also possible to import configuration files, relative to this # directory. For example, you can emulate configuration per environment # by uncommenting the line below and defining dev.exs, test.exs and such. # Configuration from the imported file will override the ones defined # here (which is why it is important to import them last). # # import_config "#{Mix.env}.exs" if Mix.env == :test do config :junit_formatter, report_dir: "/tmp/repo-example-test-results/exunit" end
34.405405
73
0.750982
e830e0fd1c306e30f9ce62c17a4205805f4c3091
366
exs
Elixir
test/felix_http_serializer_test.exs
geonnave/felix
f770af9db656978450ae3cf75573559957f203c8
[ "MIT" ]
5
2019-02-10T03:33:23.000Z
2019-02-11T12:25:50.000Z
test/felix_http_serializer_test.exs
geonnave/felix
f770af9db656978450ae3cf75573559957f203c8
[ "MIT" ]
null
null
null
test/felix_http_serializer_test.exs
geonnave/felix
f770af9db656978450ae3cf75573559957f203c8
[ "MIT" ]
null
null
null
defmodule FelixHTTPSerializerTest do use ExUnit.Case doctest Felix alias Felix.{HTTPSerializer, Connection} test "build http response" do response = """ HTTP/1.1 200 Ok\r \r hola que tal """ connection = %Connection{status: "200 Ok", resp_body: "hola que tal"} assert ^response = HTTPSerializer.serialize(connection) end end
20.333333
73
0.68306
e83109ff92398bcf78b06c662fdcc48790f22c69
757
ex
Elixir
lib/scd4x/measurement.ex
mnishiguchi/scd4x
4ad57b3b45d0a6a8302ee6e4fc41e6202af2fed5
[ "MIT" ]
null
null
null
lib/scd4x/measurement.ex
mnishiguchi/scd4x
4ad57b3b45d0a6a8302ee6e4fc41e6202af2fed5
[ "MIT" ]
null
null
null
lib/scd4x/measurement.ex
mnishiguchi/scd4x
4ad57b3b45d0a6a8302ee6e4fc41e6202af2fed5
[ "MIT" ]
null
null
null
defmodule SCD4X.Measurement do @moduledoc """ One sensor measurement """ defstruct [:co2_ppm, :humidity_rh, :temperature_c, :timestamp_ms] @type t :: %{ required(:timestamp_ms) => non_neg_integer(), required(:co2_ppm) => number, required(:humidity_rh) => number, required(:temperature_c) => number, optional(:__struct__) => atom } @spec from_raw(<<_::72>>) :: t() def from_raw(<<co2_ppm::16, _crc1, raw_temp::16, _crc2, raw_rh::16, _crc3>>) do __struct__( co2_ppm: co2_ppm, humidity_rh: SCD4X.Calc.humidity_rh_from_raw(raw_rh), temperature_c: SCD4X.Calc.temperature_c_from_raw(raw_temp), timestamp_ms: System.monotonic_time(:millisecond) ) end end
29.115385
81
0.640687
e83161055e9a349dd7c88cee130132a488bff136
669
exs
Elixir
patterns/splitter/elixir/splitter/mix.exs
thetonymaster/thetonymaster.github.io
2e24d46dd377fed6ab6d1609e5afe24b4953a0f2
[ "MIT" ]
null
null
null
patterns/splitter/elixir/splitter/mix.exs
thetonymaster/thetonymaster.github.io
2e24d46dd377fed6ab6d1609e5afe24b4953a0f2
[ "MIT" ]
null
null
null
patterns/splitter/elixir/splitter/mix.exs
thetonymaster/thetonymaster.github.io
2e24d46dd377fed6ab6d1609e5afe24b4953a0f2
[ "MIT" ]
null
null
null
defmodule Splitter.Mixfile do use Mix.Project def project do [app: :splitter, version: "0.0.1", elixir: "~> 1.1", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, deps: deps] end # Configuration for the OTP application # # Type "mix help compile.app" for more information def application do [applications: [:logger]] end # Dependencies can be Hex packages: # # {:mydep, "~> 0.3.0"} # # Or git/path repositories: # # {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"} # # Type "mix help deps" for more examples and options defp deps do [] end end
20.272727
77
0.609865
e831a1d77248f3ddd023e95aa3ba91d15afc7958
97
exs
Elixir
test/zss_service/error_test.exs
nickve28/zss_service_suite_service
6474fe4656141e283360ce9bdec1f522651eb72f
[ "MIT" ]
null
null
null
test/zss_service/error_test.exs
nickve28/zss_service_suite_service
6474fe4656141e283360ce9bdec1f522651eb72f
[ "MIT" ]
13
2017-05-20T12:19:37.000Z
2017-07-16T10:31:34.000Z
test/zss_service/error_test.exs
nickve28/zss_service_suite_service_ex
6474fe4656141e283360ce9bdec1f522651eb72f
[ "MIT" ]
null
null
null
defmodule ZssService.ErrorTest do use ExUnit.Case alias ZssService.Error doctest Error end
16.166667
33
0.804124
e831e97c78eb5af51b8951ba08a82fa0c752904e
2,338
ex
Elixir
lib/surface/catalogue/layout_view.ex
RobertDober/surface_catalogue
05495b00573b4138a167812e33e8d441590e4c89
[ "MIT" ]
null
null
null
lib/surface/catalogue/layout_view.ex
RobertDober/surface_catalogue
05495b00573b4138a167812e33e8d441590e4c89
[ "MIT" ]
null
null
null
lib/surface/catalogue/layout_view.ex
RobertDober/surface_catalogue
05495b00573b4138a167812e33e8d441590e4c89
[ "MIT" ]
null
null
null
defmodule Surface.Catalogue.LayoutView do use Phoenix.View, namespace: Surface.Catalogue, root: "lib/surface/catalogue/templates" import Surface @makeup_css Makeup.stylesheet(Makeup.Styles.HTML.StyleMap.monokai_style(), "makeup-highlight") def render("makeup.css", _), do: @makeup_css def render(_, assigns) do ~F""" <html lang="en"> <head> {Phoenix.HTML.Tag.csrf_meta_tag()} <meta charset="utf-8"/> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <meta name="viewport" content="initial-scale=1, maximum-scale=1, minimum-scale=1"/> <title>Component Catalogue</title> <link rel="icon" href="data:,"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" /> <link phx-track-static rel="stylesheet" href={assets_file("app.css")}/> {Phoenix.HTML.raw("<style>" <> render("makeup.css") <> "</style>")} <script defer phx-track-static type="text/javascript" src={assets_file("app.js")}></script> </head> <body> <section class="hero is-info"> <div class="hero-body" style="padding: 1.5rem"> <div class="container"> <h1 class="title"> <span>{title()}</span> </h1> <h2 class="subtitle" style="margin-right: 30px"> {subtitle()} </h2> </div> </div> </section> {@inner_content} <footer class="footer" style="padding: 2rem 1.5rem 2rem; margin-top: 12px;"> <div class="content has-text-centered"> <p> <strong>Surface</strong> <i>v{surface_version()}</i> - <a href="http://github.com/msaraiva/surface">github.com/msaraiva/surface</a>. </p> </div> </footer> </body> </html> """ end defp assets_file(file) do path = Application.get_env(:surface_catalogue, :assets_path) || "/assets/catalogue/" Path.join(path, file) end defp surface_version() do Application.spec(:surface, :vsn) end defp title() do Application.get_env(:surface_catalogue, :title) || "Surface UI" end defp subtitle() do Application.get_env(:surface_catalogue, :subtitle) || "My Component Catalogue" end end
32.929577
115
0.586826
e8320c2d381b2488efcb1772661ff1dd0df876d8
727
exs
Elixir
test/feature_template_test.exs
TurtleAI/cabbage
a6a5b6b03c13231535d16eccad6d4bc343fb0763
[ "MIT" ]
113
2017-01-26T21:42:22.000Z
2022-02-15T02:19:25.000Z
test/feature_template_test.exs
TurtleAI/cabbage
a6a5b6b03c13231535d16eccad6d4bc343fb0763
[ "MIT" ]
76
2017-01-24T19:53:12.000Z
2021-11-17T13:23:51.000Z
test/feature_template_test.exs
civilcode/cabbage
bdb14a8efae86bcf437180ce2f7193a1f431742d
[ "MIT" ]
30
2017-01-22T21:43:35.000Z
2022-02-09T17:21:38.000Z
Code.require_file("test_helper.exs", __DIR__) defmodule Cabbage.FeatureTestTest do use ExUnit.Case test "can use custom template" do defmodule CustomTemplate do use ExUnit.CaseTemplate using do quote do setup_all do {:ok, %{case_template: unquote(__MODULE__)}} end end end end defmodule FeatureTimeoutTest do use Cabbage.Feature, file: "simplest.feature", template: CustomTemplate defthen ~r/^I provide Then$/, _vars, state do assert state.case_template == CustomTemplate end end {result, _output} = CabbageTestHelper.run() assert result == %{failures: 0, skipped: 0, total: 1, excluded: 0} end end
23.451613
77
0.646492
e8321f7050b7ca8d75ec4b9fd7707fe563172aa9
8,359
exs
Elixir
test/integration/kayrock/timestamp_test.exs
tigertext/kafka_ex_tc
1f03132d3635281483b323751a60efa3b87586ef
[ "MIT" ]
null
null
null
test/integration/kayrock/timestamp_test.exs
tigertext/kafka_ex_tc
1f03132d3635281483b323751a60efa3b87586ef
[ "MIT" ]
null
null
null
test/integration/kayrock/timestamp_test.exs
tigertext/kafka_ex_tc
1f03132d3635281483b323751a60efa3b87586ef
[ "MIT" ]
null
null
null
defmodule KafkaEx.KayrockTimestampTest do @moduledoc """ Tests for the timestamp functionality in messages """ use ExUnit.Case alias KafkaEx.TimestampNotSupportedError @moduletag :new_client setup do {:ok, pid} = KafkaEx.start_link_worker(:no_name, server_impl: KafkaEx.New.Client) {:ok, %{client: pid}} end test "fetch timestamp is nil by default on v0 messages", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 0 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == nil end test "fetch timestamp is -1 by default on v3 messages", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 3 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == -1 end test "fetch timestamp is -1 by default on v5 messages", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 5 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == -1 end test "log with append time - v0", %{client: client} do topic = "test_log_append_timestamp_#{:rand.uniform(2_000_000)}" {:ok, ^topic} = TestHelper.ensure_append_timestamp_topic( client, topic ) msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 0 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == nil end test "log with append time - v3", %{client: client} do topic = "test_log_append_timestamp_#{:rand.uniform(2_000_000)}" {:ok, ^topic} = TestHelper.ensure_append_timestamp_topic( client, topic ) msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 3 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset refute is_nil(message.timestamp) assert message.timestamp > 0 end test "log with append time - v5", %{client: client} do topic = "test_log_append_timestamp_#{:rand.uniform(2_000_000)}" {:ok, ^topic} = TestHelper.ensure_append_timestamp_topic( client, topic ) msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 5 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset refute is_nil(message.timestamp) assert message.timestamp > 0 end test "set timestamp with v0 throws an error", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() Process.flag(:trap_exit, true) catch_exit do KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1, timestamp: 12345, api_version: 0 ) end assert_received {:EXIT, ^client, {%TimestampNotSupportedError{}, _}} end test "set timestamp with v1 throws an error", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() Process.flag(:trap_exit, true) catch_exit do KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1, timestamp: 12345, api_version: 1 ) end assert_received {:EXIT, ^client, {%TimestampNotSupportedError{}, _}} end test "set timestamp for v3 message, fetch v0", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1, timestamp: 12345, api_version: 3 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 0 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == nil end test "set timestamp for v3 message, fetch v3", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1, timestamp: 12345, api_version: 3 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 3 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == 12345 end test "set timestamp for v3 message, fetch v5", %{client: client} do topic = "food" msg = TestHelper.generate_random_string() {:ok, offset} = KafkaEx.produce( topic, 0, msg, worker_name: client, required_acks: 1, timestamp: 12345, api_version: 3 ) fetch_responses = KafkaEx.fetch(topic, 0, offset: offset, auto_commit: false, worker_name: client, api_version: 5 ) [fetch_response | _] = fetch_responses [partition_response | _] = fetch_response.partitions message = List.last(partition_response.message_set) assert message.value == msg assert message.offset == offset assert message.timestamp == 12345 end end
23.09116
79
0.612394
e832236475b9cb554eee94d6568a8e44344151c0
2,290
ex
Elixir
web/controllers/home_controller.ex
kentcdodds/changelog.com
e1c0d7ee5d47dc83dd443d623adb0f07e4acb28d
[ "MIT" ]
null
null
null
web/controllers/home_controller.ex
kentcdodds/changelog.com
e1c0d7ee5d47dc83dd443d623adb0f07e4acb28d
[ "MIT" ]
null
null
null
web/controllers/home_controller.ex
kentcdodds/changelog.com
e1c0d7ee5d47dc83dd443d623adb0f07e4acb28d
[ "MIT" ]
null
null
null
defmodule Changelog.HomeController do use Changelog.Web, :controller alias Changelog.{Person, Slack} alias Craisin.Subscriber plug RequireUser def show(conn, _params) do render(conn, :show) end def edit(conn = %{assigns: %{current_user: current_user}}, _params) do render(conn, :edit, changeset: Person.changeset(current_user)) end def update(conn = %{assigns: %{current_user: current_user}}, %{"person" => person_params}) do changeset = Person.changeset(current_user, person_params) case Repo.update(changeset) do {:ok, _person} -> conn |> put_flash(:success, "Your profile has been updated! ✨") |> redirect(to: home_path(conn, :show)) {:error, changeset} -> conn |> put_flash(:error, "The was a problem updating your profile 😢") |> render(:edit, person: current_user, changeset: changeset) end end def subscribe(conn = %{assigns: %{current_user: current_user}}, %{"id" => newsletter_id}) do Subscriber.subscribe(newsletter_id, current_user) conn |> put_flash(:success, "One more step! Check your email to confirm your subscription. Then we'll hook you up 📥") |> render(:show) end def unsubscribe(conn = %{assigns: %{current_user: current_user}}, %{"id" => newsletter_id}) do Subscriber.unsubscribe(newsletter_id, current_user.email) conn |> put_flash(:success, "You're no longer subscribed. Come back any time 🤗") |> render(:show) end def slack(conn = %{assigns: %{current_user: current_user}}, _params) do {updated_user, flash} = case Slack.Client.invite(current_user.email) do %{"ok" => true} -> {set_slack_id(current_user), "Invite sent! Check your email 🎯"} %{"ok" => false, "error" => "already_in_team"} -> {set_slack_id(current_user), "You're on the team! We'll see you in there ✊"} %{"ok" => false, "error" => error} -> {current_user, "Hmm, Slack is saying '#{error}' 🤔"} end conn |> assign(:current_user, updated_user) |> put_flash(:success, flash) |> render(:show) end defp set_slack_id(person) do if person.slack_id do person else {:ok, person} = Repo.update(Person.slack_changeset(person, "pending")) person end end end
31.369863
116
0.646288