hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
735d2f2dd9f3a3ad908fc2dbb08e6f723ab3ca9b | 337 | exs | Elixir | priv/repo/migrations/20170102005126_create_parameter.exs | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | 2 | 2016-11-16T17:24:21.000Z | 2019-02-15T05:38:27.000Z | priv/repo/migrations/20170102005126_create_parameter.exs | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | null | null | null | priv/repo/migrations/20170102005126_create_parameter.exs | rob05c/tox | f54847ca058ad24b909341ad65d595a4069d2471 | [
"Apache-2.0"
] | null | null | null | defmodule Tox.Repo.Migrations.CreateParameter do
use Ecto.Migration
def change do
create table(:parameters) do
add :name, :text
add :config_file, :text
add :value, :text
add :secure, :boolean, default: false, null: false
timestamps()
end
create unique_index(:parameters, [:name])
end
end
| 22.466667 | 56 | 0.658754 |
735d44d62557f6ed0c1afa230fda938335c500e8 | 325 | exs | Elixir | apps/re_integrations/priv/repo/migrations/20190523214548_create_orulo_buildings.exs | ruby2elixir/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | 4 | 2019-11-01T16:29:31.000Z | 2020-10-10T21:20:12.000Z | apps/re_integrations/priv/repo/migrations/20190523214548_create_orulo_buildings.exs | eduardomartines/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | null | null | null | apps/re_integrations/priv/repo/migrations/20190523214548_create_orulo_buildings.exs | eduardomartines/emcasa-backend | 70d7f4f233555417941ffa6ada84cf8740c21dd2 | [
"MIT"
] | 5 | 2019-11-04T21:25:45.000Z | 2020-02-13T23:49:36.000Z | defmodule ReIntegrations.Repo.Migrations.CreateOruloBuildings do
use Ecto.Migration
def change do
create table(:orulo_buildings, primary_key: false) do
add :uuid, :uuid, primary_key: true
add :external_id, :integer
add :payload, :map, null: false, default: %{}
timestamps()
end
end
end
| 25 | 64 | 0.692308 |
735d6830624550c392742e145a57a4af9f35a662 | 19,008 | exs | Elixir | test/glimesh/channel_lookups_test.exs | mfaqiri/glimesh.tv | 59eeb56bb0a5574b7b6168d9487660f41a457fd4 | [
"MIT"
] | null | null | null | test/glimesh/channel_lookups_test.exs | mfaqiri/glimesh.tv | 59eeb56bb0a5574b7b6168d9487660f41a457fd4 | [
"MIT"
] | null | null | null | test/glimesh/channel_lookups_test.exs | mfaqiri/glimesh.tv | 59eeb56bb0a5574b7b6168d9487660f41a457fd4 | [
"MIT"
] | null | null | null | defmodule Glimesh.ChannelLookupsTest do
use Glimesh.DataCase
use Bamboo.Test
import Glimesh.AccountsFixtures
import Glimesh.StreamsFixtures
alias Glimesh.ChannelLookups
alias Glimesh.ChannelCategories
alias Glimesh.Streams
alias Glimesh.Streams.ChannelHosts
defp create_channel(_) do
gaming_id = ChannelCategories.get_category("gaming").id
{:ok, subcategory} =
ChannelCategories.create_subcategory(%{
name: "Testing",
category_id: gaming_id
})
streamer =
streamer_fixture(%{}, %{
# Force ourselves to have a gaming stream
category_id: gaming_id,
subcategory_id: subcategory.id,
language: "en"
})
tag = tag_fixture(%{name: "Some Tag", category_id: gaming_id})
{:ok, channel} =
streamer.channel
|> Ecto.Changeset.change()
|> Ecto.Changeset.put_assoc(:tags, [tag])
|> Glimesh.Repo.update()
{:ok, _} = Glimesh.Streams.start_stream(channel)
%{
subcategory: subcategory,
channel: channel,
streamer: streamer
}
end
describe "channel lookups" do
setup :create_channel
test "list_channels/0 lists all channels" do
assert length(ChannelLookups.list_channels()) == 1
end
test "channel_search/1 lists channels conditionally for category", %{channel: channel} do
random_streamer =
streamer_fixture(%{}, %{category_id: ChannelCategories.get_category("art").id})
{:ok, _} = Glimesh.Streams.start_stream(random_streamer.channel)
channels =
ChannelLookups.search_live_channels(%{
"category" => "gaming"
})
assert length(channels) == 1
assert hd(channels).id == channel.id
end
test "channel_search/1 lists channels conditionally for category and subcategory", %{
channel: channel
} do
gaming_id = ChannelCategories.get_category("gaming").id
{:ok, another_subcategory} =
ChannelCategories.create_subcategory(%{
name: "Not the one",
category_id: gaming_id
})
random_streamer =
streamer_fixture(%{}, %{category_id: gaming_id, subcategory_id: another_subcategory.id})
{:ok, _} = Glimesh.Streams.start_stream(random_streamer.channel)
channels =
ChannelLookups.search_live_channels(%{
"category" => "gaming",
"subcategory" => ["testing"]
})
assert length(channels) == 1
assert hd(channels).id == channel.id
end
test "channel_search/1 searches by tags", %{
channel: channel
} do
random_streamer =
streamer_fixture(%{}, %{category_id: ChannelCategories.get_category("gaming").id})
Glimesh.Streams.start_stream(random_streamer.channel)
channels =
ChannelLookups.search_live_channels(%{
"category" => "gaming",
"tags" => ["some-tag"]
})
assert length(channels) == 1
assert hd(channels).id == channel.id
end
test "channel_search/1 searches by languages", %{
channel: channel
} do
random_streamer =
streamer_fixture(%{}, %{
category_id: ChannelCategories.get_category("gaming").id,
language: "es_AR"
})
Glimesh.Streams.start_stream(random_streamer.channel)
channels =
ChannelLookups.search_live_channels(%{
"category" => "gaming",
"language" => ["en"]
})
assert length(channels) == 1
assert hd(channels).id == channel.id
channels =
ChannelLookups.search_live_channels(%{
"category" => "gaming",
"language" => "en"
})
assert length(channels) == 1
assert hd(channels).id == channel.id
end
test "list_live_channels/0 lists all live channels", %{} do
assert length(ChannelLookups.list_live_channels()) == 1
end
test "list_live_followed_channels/1 lists live followed channels", %{
streamer: streamer,
channel: channel
} do
user = user_fixture()
{:ok, _} = Glimesh.AccountFollows.follow(streamer, user)
assert length(ChannelLookups.list_live_followed_channels(user)) == 1
{:ok, _} = Glimesh.Streams.end_stream(channel)
assert length(ChannelLookups.list_live_followed_channels(user)) == 0
end
end
defp account_ages(_) do
%{
five_days_ago:
NaiveDateTime.add(NaiveDateTime.utc_now(), 86_400 * -5) |> NaiveDateTime.truncate(:second),
ten_days_from_now:
NaiveDateTime.add(NaiveDateTime.utc_now(), 86_400 * 10) |> NaiveDateTime.truncate(:second)
}
end
defp create_hosting_data(_) do
hosting_channel =
streamer_fixture(%{}, %{})
|> change_inserted_at_for_user(
NaiveDateTime.add(NaiveDateTime.utc_now(), 86_400 * -6)
|> NaiveDateTime.truncate(:second)
)
Streams.create_stream(hosting_channel.channel, %{
started_at:
NaiveDateTime.add(NaiveDateTime.utc_now(), 60 * 60 * -10)
|> NaiveDateTime.truncate(:second),
ended_at: NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
})
%{
target_allowed_hosting: streamer_fixture(%{}, %{allow_hosting: true}),
hosting_channel_five_days_old: hosting_channel
}
end
describe "Hosting Channels" do
setup [:account_ages, :create_hosting_data]
test "Banned user cannot be hosted", %{hosting_channel_five_days_old: hosting_channel} do
banned_user = streamer_fixture(%{is_banned: true}, %{allow_hosting: true})
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
banned_user.displayname
)
) == 0
end
test "Users without channels cannot be hosted", %{
hosting_channel_five_days_old: hosting_channel
} do
ordinary_user = user_fixture(%{})
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
ordinary_user.displayname
)
) == 0
end
test "Streamers banned from a channel cannot host channel", %{
target_allowed_hosting: target_channel,
hosting_channel_five_days_old: hosting_channel
} do
channel_banned_user_fixture(target_channel.channel, hosting_channel)
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
target_channel.displayname
)
) == 0
end
test "Streamers cannot host channels that don't allow hosting", %{
hosting_channel_five_days_old: hosting_channel
} do
target_channel = streamer_fixture(%{}, %{allow_hosting: false})
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
target_channel.displayname
)
) == 0
end
test "Streamers cannot host their own channel", %{
hosting_channel_five_days_old: hosting_channel
} do
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
hosting_channel.displayname
)
) == 0
end
test "Streamers CAN host a channel", %{
target_allowed_hosting: target_channel,
hosting_channel_five_days_old: hosting_channel
} do
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
target_channel.displayname
)
) == 1
end
test "Streamers timed out from a channel CAN host channel",
%{
target_allowed_hosting: target_channel,
hosting_channel_five_days_old: hosting_channel,
ten_days_from_now: ten_days_from_now
} do
channel_timed_out_user_fixture(target_channel.channel, hosting_channel, ten_days_from_now)
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
target_channel.displayname
)
) == 1
end
test "Streamers CAN find more than one channel to host",
%{
target_allowed_hosting: _target_channel,
hosting_channel_five_days_old: hosting_channel,
ten_days_from_now: ten_days_from_now
} do
_target_channel_one = streamer_fixture(%{}, %{allow_hosting: true})
_target_channel_two = streamer_fixture(%{}, %{allow_hosting: true})
target_channel_three = streamer_fixture(%{}, %{allow_hosting: true})
channel_timed_out_user_fixture(
target_channel_three.channel,
hosting_channel,
ten_days_from_now
)
# banned
_bad_target_one = streamer_fixture(%{is_banned: true}, %{allow_hosting: true})
# doesn't allow hosting
_bad_target_two = streamer_fixture(%{}, %{allow_hosting: false})
# ordinary user, no channel
_bad_target_three = user_fixture(%{})
bad_target_four = streamer_fixture(%{}, %{allow_hosting: true})
# hosting channel banned from target
channel_banned_user_fixture(bad_target_four.channel, hosting_channel)
# includes target_channel
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, "user")) == 4
end
test "Already hosted channels should be filtered out of search", %{
target_allowed_hosting: target_channel,
hosting_channel_five_days_old: hosting_channel
} do
case ChannelHosts.add_new_host(hosting_channel, hosting_channel.channel, %ChannelHosts{
hosting_channel_id: hosting_channel.channel.id,
target_channel_id: target_channel.channel.id
}) do
{:ok, _channel_hosts} ->
assert length(
ChannelLookups.search_hostable_channels_by_name(
hosting_channel,
target_channel.displayname
)
) == 0
{:error, _channel_hosts} ->
flunk("Unable to setup channel host")
end
end
test "Already hosted channels should show up in other users searches", %{
target_allowed_hosting: target_channel,
hosting_channel_five_days_old: hosting_channel
} do
%{hosting_channel_five_days_old: other_channel} = create_hosting_data(%{})
case ChannelHosts.add_new_host(hosting_channel, hosting_channel.channel, %ChannelHosts{
hosting_channel_id: hosting_channel.channel.id,
target_channel_id: target_channel.channel.id
}) do
{:ok, _channel_hosts} ->
assert length(
ChannelLookups.search_hostable_channels_by_name(
other_channel,
target_channel.displayname
)
) == 1
{:error, _channel_hosts} ->
flunk("Unable to setup channel host")
end
end
test "Search terms should be sanitized", %{hosting_channel_five_days_old: hosting_channel} do
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, "user_")) ==
0
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, "%user")) ==
0
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, "user%")) ==
0
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, "%user_%")) ==
0
end
test "Search terms must be less than username max size", %{
hosting_channel_five_days_old: hosting_channel
} do
bad_search = "0123456789012345678901234"
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, bad_search)) ==
0
bad_search = nil
assert length(ChannelLookups.search_hostable_channels_by_name(hosting_channel, bad_search)) ==
0
end
end
defp create_followed_hosting_data(_) do
user = user_fixture()
additional_follower = user_fixture()
non_followed_live_channel = streamer_fixture()
Ecto.Changeset.change(non_followed_live_channel.channel)
|> Ecto.Changeset.force_change(:status, "live")
|> Repo.update()
live_channel_hosted = streamer_fixture(%{}, %{status: "live"})
# make sure hosted channels have more than one follower
Glimesh.AccountFollows.follow(live_channel_hosted, additional_follower)
Ecto.Changeset.change(live_channel_hosted.channel)
|> Ecto.Changeset.force_change(:status, "live")
|> Repo.update()
host = streamer_fixture()
Ecto.Changeset.change(%Glimesh.Streams.ChannelHosts{
hosting_channel_id: host.channel.id,
target_channel_id: live_channel_hosted.channel.id,
status: "hosting"
})
|> Repo.insert()
Glimesh.AccountFollows.follow(host, user)
Glimesh.AccountFollows.follow(host, additional_follower)
live_channel_hosted_but_not_followed = streamer_fixture()
Ecto.Changeset.change(live_channel_hosted_but_not_followed.channel)
|> Ecto.Changeset.force_change(:status, "live")
|> Repo.update()
host_not_followed = streamer_fixture()
Ecto.Changeset.change(%Glimesh.Streams.ChannelHosts{
hosting_channel_id: host_not_followed.channel.id,
target_channel_id: live_channel_hosted_but_not_followed.channel.id,
status: "hosting"
})
|> Repo.insert()
live_channel_followed_but_not_hosted = streamer_fixture()
Ecto.Changeset.change(live_channel_followed_but_not_hosted.channel)
|> Ecto.Changeset.force_change(:status, "live")
|> Repo.update()
Glimesh.AccountFollows.follow(live_channel_followed_but_not_hosted, user)
Glimesh.AccountFollows.follow(live_channel_followed_but_not_hosted, additional_follower)
%{
user: user,
host: host,
live_channel_hosted: live_channel_hosted,
non_followed_live_channel: non_followed_live_channel,
live_channel_hosted_but_not_followed: live_channel_hosted_but_not_followed,
host_not_followed: host_not_followed,
live_channel_followed_but_not_hosted: live_channel_followed_but_not_hosted
}
end
describe "Followed hosting channels" do
setup [:create_followed_hosting_data]
test "should show up in the search when the followed channel is not live", %{
user: user,
live_channel_hosted: live_hosted,
live_channel_followed_but_not_hosted: live_followed
} do
results = ChannelLookups.list_live_followed_channels_and_hosts(user)
assert length(results) == 2
assert Enum.at(results, 0).id == live_followed.channel.id
assert Enum.at(results, 0).match_type == "live"
assert Enum.at(results, 1).id == live_hosted.channel.id
assert Enum.at(results, 1).match_type == "hosting"
end
test "should NOT show duplicates when followed channels host the same live channel", %{
user: user,
live_channel_hosted: live_hosted,
live_channel_followed_but_not_hosted: live_followed
} do
followed_channel_same_host_target = streamer_fixture()
Glimesh.AccountFollows.follow(followed_channel_same_host_target, user)
Ecto.Changeset.change(%Glimesh.Streams.ChannelHosts{
hosting_channel_id: followed_channel_same_host_target.channel.id,
target_channel_id: live_hosted.channel.id,
status: "hosting"
})
|> Repo.insert()
results = ChannelLookups.list_live_followed_channels_and_hosts(user)
assert length(results) == 2
assert Enum.at(results, 0).id == live_followed.channel.id
assert Enum.at(results, 0).match_type == "live"
assert Enum.at(results, 1).id == live_hosted.channel.id
assert Enum.at(results, 1).match_type == "hosting"
end
test "should show followed live channel without duplicating it when it is hosted by an offline channel that is followed",
%{
user: user,
live_channel_hosted: live_hosted,
live_channel_followed_but_not_hosted: live_followed
} do
followed_offline_channel_same_host_target = streamer_fixture()
Glimesh.AccountFollows.follow(followed_offline_channel_same_host_target, user)
Ecto.Changeset.change(%Glimesh.Streams.ChannelHosts{
hosting_channel_id: followed_offline_channel_same_host_target.channel.id,
target_channel_id: live_followed.channel.id,
status: "hosting"
})
|> Repo.insert()
results = ChannelLookups.list_live_followed_channels_and_hosts(user)
assert length(results) == 2
assert Enum.at(results, 0).id == live_followed.channel.id
assert Enum.at(results, 0).match_type == "live"
assert Enum.at(results, 1).id == live_hosted.channel.id
assert Enum.at(results, 1).match_type == "hosting"
end
test "should prefer live channels over hosted when duplicates occur", %{
user: user,
live_channel_hosted: live_hosted,
live_channel_followed_but_not_hosted: live_followed
} do
# sanity check
results = ChannelLookups.list_live_followed_channels_and_hosts(user)
assert length(results) == 2
assert Enum.at(results, 0).id == live_followed.channel.id
assert Enum.at(results, 0).match_type == "live"
assert Enum.at(results, 1).id == live_hosted.channel.id
assert Enum.at(results, 1).match_type == "hosting"
# if the user follows the channel being hosted, it should show up in the live section and not as a "hosted" stream.
Glimesh.AccountFollows.follow(live_hosted, user)
results = ChannelLookups.list_live_followed_channels_and_hosts(user)
assert length(results) == 2
# I don't do an ID check here as the results are not sorted and could be random
assert Enum.at(results, 0).match_type == "live"
assert Enum.at(results, 1).match_type == "live"
end
test "followed channels and followed hosted channels counts should be accurate", %{
user: user,
live_channel_hosted: live_hosted
} do
assert ChannelLookups.count_live_followed_channels_that_are_hosting(user) == 1
assert length(ChannelLookups.list_live_followed_channels(user)) == 1
Glimesh.AccountFollows.follow(live_hosted, user)
assert ChannelLookups.count_live_followed_channels_that_are_hosting(user) == 0
assert length(ChannelLookups.list_live_followed_channels(user)) == 2
end
test "a host who follows themselves should not see a channel they follow and are hosting duplicated on the following page",
%{
host: host,
live_channel_hosted: live_hosted
} do
Glimesh.AccountFollows.follow(host, host)
Glimesh.AccountFollows.follow(live_hosted, host)
results = ChannelLookups.list_live_followed_channels_and_hosts(host)
assert length(results) == 1
end
end
end
| 34.003578 | 127 | 0.667298 |
735d830fe3dcdd20c343aaf5a3fb1960fb9178ba | 714 | ex | Elixir | lib/converter/us.ex | mwmiller/exoddic | dd590668a84079fb2eb0bb89f4599165abed9b54 | [
"MIT"
] | 3 | 2016-05-13T16:52:46.000Z | 2021-02-05T23:00:16.000Z | lib/converter/us.ex | mwmiller/exoddic | dd590668a84079fb2eb0bb89f4599165abed9b54 | [
"MIT"
] | null | null | null | lib/converter/us.ex | mwmiller/exoddic | dd590668a84079fb2eb0bb89f4599165abed9b54 | [
"MIT"
] | null | null | null | defmodule Exoddic.Converter.Us do
@behaviour Exoddic.Converter
@moduledoc """
.us-style moneyline odds
"""
def from_prob(amount) when amount == 0.00, do: 0.0
def from_prob(amount) when amount <= 0.50, do: 100 * ((1 - amount) / amount)
def from_prob(amount) when amount > 0.50, do: -100 * (amount / (1 - amount))
def to_prob(amount) when amount == 0, do: 0.0
def to_prob(amount) when amount < 0, do: amount / (amount - 100)
def to_prob(amount) when amount > 0, do: 100 / (amount + 100)
@doc "Nearest integer; includes prepended '+' for non-negative"
def for_display(amount) when amount < 0, do: "#{round(amount)}"
def for_display(amount) when amount >= 0, do: "+#{round(amount)}"
end
| 37.578947 | 78 | 0.659664 |
735d9a1618412bbc9c2c555d3db9954e30660dad | 1,230 | exs | Elixir | apps/ello_stream/test/slop_test.exs | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 16 | 2017-06-21T21:31:20.000Z | 2021-05-09T03:23:26.000Z | apps/ello_stream/test/slop_test.exs | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 25 | 2017-06-07T12:18:28.000Z | 2018-06-08T13:27:43.000Z | apps/ello_stream/test/slop_test.exs | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 3 | 2018-06-14T15:34:07.000Z | 2022-02-28T21:06:13.000Z | defmodule Ello.SlopTest do
use ExUnit.Case
alias Ello.Stream.Slop
test "it calculates default slop_factor for anonymous user" do
factors = %{
base_slop_factor: 1,
nsfw_slop_factor: 2,
nudity_slop_factor: 3,
}
assert Slop.slop_factor(%{}, factors) == 6
end
test "it calculates slop_factor for allow_nudity, allow_nsfw true" do
factors = %{
base_slop_factor: 1,
nsfw_slop_factor: 2,
nudity_slop_factor: 3,
}
assert Slop.slop_factor(%{allow_nudity: true, allow_nsfw: true}, factors) == 1
end
test "it calculates slop_factor for blocked users" do
factors = %{
base_slop_factor: 0,
nsfw_slop_factor: 0,
nudity_slop_factor: 0,
block_slop_multiplier: 2,
max_block_slop_factor: 100,
}
assert Slop.slop_factor(%{current_user: %{all_blocked_ids: [1, 2, 3]}}, factors) == 6
end
test "it calculates default slop_factor when requiring cred" do
factors = %{
cred_slop_factor: 2,
base_slop_factor: 0,
block_slop_multiplier: 0,
max_block_slop_factor: 0,
nsfw_slop_factor: 0,
nudity_slop_factor: 0,
}
assert Slop.slop_factor(%{require_cred: true}, factors) == 2
end
end
| 25.102041 | 89 | 0.663415 |
735dfda19227c4db8e0e50e2a15518a644eee97d | 1,190 | ex | Elixir | core/sup_tree_core/periodic_log/message_builder.ex | wses-yoshida/antikythera | e108e59d2339edd0b0fad31ad4f41f56df45be55 | [
"Apache-2.0"
] | null | null | null | core/sup_tree_core/periodic_log/message_builder.ex | wses-yoshida/antikythera | e108e59d2339edd0b0fad31ad4f41f56df45be55 | [
"Apache-2.0"
] | null | null | null | core/sup_tree_core/periodic_log/message_builder.ex | wses-yoshida/antikythera | e108e59d2339edd0b0fad31ad4f41f56df45be55 | [
"Apache-2.0"
] | null | null | null | # Copyright(c) 2015-2019 ACCESS CO., LTD. All rights reserved.
defmodule AntikytheraCore.PeriodicLog.MessageBuilder do
@max_proc_to_log 5
@max_msg_to_log 10
@queue_len_threshold 100
def init() do
nil
end
def build_log(state) do
log =
:recon.proc_count(:message_queue_len, @max_proc_to_log)
|> Enum.filter(fn({_pid, qlen, _info}) -> qlen >= @queue_len_threshold end)
|> build_log_from_processes()
{log, state}
end
defp build_log_from_processes([]), do: nil
defp build_log_from_processes(procs) do
log_time = Antikythera.Time.to_iso_timestamp(Antikythera.Time.now())
procs
|> Enum.reduce(log_time, fn({pid, qlen, info}, acc) ->
acc2 = acc <> "\n" <> Integer.to_string(qlen) <> " " <> inspect(info, structs: false)
append_messages_to_log(acc2, Process.info(pid))
end)
end
defp append_messages_to_log(log, nil), do: log <> "\n This process has already exited."
defp append_messages_to_log(log, process_info) do
process_info
|> Keyword.get(:messages)
|> Enum.take(@max_msg_to_log)
|> Enum.reduce(log, fn(msg, acc) -> acc <> "\n " <> inspect(msg, structs: false) end)
end
end
| 31.315789 | 92 | 0.670588 |
735e50f235b6a67acc01e26eb9b5894c216ff57a | 1,036 | ex | Elixir | web/views/error_helpers.ex | mciastek/emotions-wheel-backend | 072a88b3ad15b2c6d2aad414e6b7cfc8fb4a70bf | [
"MIT"
] | null | null | null | web/views/error_helpers.ex | mciastek/emotions-wheel-backend | 072a88b3ad15b2c6d2aad414e6b7cfc8fb4a70bf | [
"MIT"
] | null | null | null | web/views/error_helpers.ex | mciastek/emotions-wheel-backend | 072a88b3ad15b2c6d2aad414e6b7cfc8fb4a70bf | [
"MIT"
] | null | null | null | defmodule EmotionsWheelBackend.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
if error = form.errors[field] do
content_tag :span, translate_error(error), class: "help-block"
end
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# Because error messages were defined within Ecto, we must
# call the Gettext module passing our Gettext backend. We
# also use the "errors" domain as translations are placed
# in the errors.po file. On your own code and templates,
# this could be written simply as:
#
# dngettext "errors", "1 file", "%{count} files", count
#
Gettext.dngettext(EmotionsWheelBackend.Gettext, "errors", msg, msg, opts[:count], opts)
end
def translate_error(msg) do
Gettext.dgettext(EmotionsWheelBackend.Gettext, "errors", msg)
end
end
| 28.777778 | 91 | 0.69112 |
735e70670a39a5ae13bfded5258ee23b1e8cebfd | 3,635 | ex | Elixir | clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_request.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/data_catalog/lib/google_api/data_catalog/v1beta1/model/google_cloud_datacatalog_v1beta1_search_catalog_request.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.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequest do
@moduledoc """
Request message for SearchCatalog.
## Attributes
* `orderBy` (*type:* `String.t`, *default:* `nil`) - Specifies the ordering of results, currently supported case-sensitive choices are: * `relevance`, only supports descending * `last_modified_timestamp [asc|desc]`, defaults to descending if not specified If not specified, defaults to `relevance` descending.
* `pageSize` (*type:* `integer()`, *default:* `nil`) - Number of results in the search page. If <=0 then defaults to 10. Max limit for page_size is 1000. Throws an invalid argument for page_size > 1000.
* `pageToken` (*type:* `String.t`, *default:* `nil`) - Optional. Pagination token returned in an earlier SearchCatalogResponse.next_page_token, which indicates that this is a continuation of a prior SearchCatalogRequest call, and that the system should return the next page of data. If empty, the first page is returned.
* `query` (*type:* `String.t`, *default:* `nil`) - Optional. The query string in search query syntax. An empty query string will result in all data assets (in the specified scope) that the user has access to. Query strings can be simple as "x" or more qualified as: * name:x * column:x * description:y Note: Query tokens need to have a minimum of 3 characters for substring matching to work correctly. See [Data Catalog Search Syntax](https://cloud.google.com/data-catalog/docs/how-to/search-reference) for more information.
* `scope` (*type:* `GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope.t`, *default:* `nil`) - Required. The scope of this search request. A `scope` that has empty `include_org_ids`, `include_project_ids` AND false `include_gcp_public_datasets` is considered invalid. Data Catalog will return an error in such a case.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:orderBy => String.t(),
:pageSize => integer(),
:pageToken => String.t(),
:query => String.t(),
:scope =>
GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope.t()
}
field(:orderBy)
field(:pageSize)
field(:pageToken)
field(:query)
field(:scope,
as: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequestScope
)
end
defimpl Poison.Decoder,
for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequest do
def decode(value, options) do
GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.DataCatalog.V1beta1.Model.GoogleCloudDatacatalogV1beta1SearchCatalogRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 53.455882 | 528 | 0.748556 |
735e7d18cff395532587f3a8f8ac46d071588efa | 18,957 | ex | Elixir | lib/phoenix_live_view.ex | roryokane/phoenix_live_view | d77f787356ee312eb8a8f8427c03da29a6010abe | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | roryokane/phoenix_live_view | d77f787356ee312eb8a8f8427c03da29a6010abe | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | roryokane/phoenix_live_view | d77f787356ee312eb8a8f8427c03da29a6010abe | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveView do
@moduledoc """
Live views are stateful views which update the browser on state changes.
## Configuration
A `:signing_salt` configuration is required in your endpoint's
`:live_view` configuration, for example:
config :my_app, AppWeb.Endpoint,
...,
live_view: [signing_salt: ...]
You can generate a secure, random signing salt with the
`mix phx.gen.secret 32` task.
## Life-cycle
A Live View begins as a regular HTTP request and HTML response,
and then upgrades to a stateful view on client connect,
guaranteeing a regular HTML page even if JavaScript is disabled.
Any time a stateful view changes or updates its socket assigns, it is
automatically re-rendered and the updates are pushed to the client.
You begin by rendering a Live View from your router or controller
while providing *session* data to the view, which represents request info
necessary for the view, such as params, cookie session info, etc.
The session is signed and stored on the client, then provided back
to the server when the client connects, or reconnects to the stateful
view. When a view is rendered from the controller, the `mount/2` callback
is invoked with the provided session data and the Live View's socket.
The `mount/2` callback wires up socket assigns necessary for rendering
the view. After mounting, `render/1` is invoked and the HTML is sent
as a regular HTML response to the client.
After rendering the static page with a signed session, the live
views connect from the client where stateful views are spawned
to push rendered updates to the browser, and receive client events
via phx bindings. Just like the controller flow, `mount/2` is invoked
with the signed session, and socket state, where mount assigns
values for rendering. However, in the connected client case, a
Live View process is spawned on the server, pushes the result of
`render/1` to the client and continues on for the duration of the
connection. If at any point during the stateful life-cycle a
crash is encountered, or the client connection drops, the client
gracefully reconnects to the server, passing its signed session
back to `mount/2`.
## Usage
First, a Live View requires two callbacks: `mount/2` and `render/1`:
defmodule AppWeb.ThermostatView do
def render(assigns) do
~L\"""
Current temperature: <%= @temperature %>
\"""
end
def mount(%{id: id, current_user_id: user_id}, socket) do
case Thermostat.get_user_reading(user_id, id) do
{:ok, temperature} ->
{:ok, assign(socket, :temperature, temperature)}
{:error, reason} ->
{:error, reason}
end
end
end
The `render/1` callback receives the `socket.assigns` and is responsible
for returning rendered content. You can use `Phoenix.LiveView.sigil_L/2`
to inline Live View templates. If you want to use `Phoenix.HTML` helpers,
remember to `use Phoenix.HTML` at the top of your `LiveView`.
With a Live View defined, you first define the `socket` path in your endpoint,
and point it to `Phoenix.LiveView.Socket`:
defmodule AppWeb.Endpoint do
use Phoenix.Endpoint
socket "/live", Phoenix.LiveView.Socket
...
end
Next, you can serve Live Views directly from your router:
defmodule AppWeb.Router do
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", AppWeb do
live "/thermostat", ThermostatView
end
end
Or you can `live_render` your view from any controller:
defmodule AppWeb.ThermostatController do
...
alias Phoenix.LiveView
def show(conn, %{"id" => id}) do
LiveView.Controller.live_render(conn, AppWeb.ThermostatView, session: %{
id: id,
current_user_id: get_session(conn, :user_id),
})
end
end
As we saw in the life-cycle section, you pass `:session` data about the
request to the view, such as the current user's id in the cookie session,
and parameters from the request. A regular HTML response is sent with a
signed token embedded in the DOM containing your Live View session data.
Next, your client code connects to the server:
import LiveSocket from "phoenix_live_view"
let liveSocket = new LiveSocket("/live")
liveSocket.connect()
After the client connects, `mount/2` will be invoked inside a spawn
Live View process. At this point, you can use `connected?/1` to
conditionally perform stateful work, such as subscribing to pubsub topics,
sending messages, etc. For example, you can periodically update a Live View
with a timer:
defmodule DemoWeb.ThermostatView do
use Phoenix.LiveView
...
def mount(%{id: id, current_user_id: user_id}, socket) do
if connected?(socket), do: :timer.send_interval(30000, self(), :update)
case Thermostat.get_user_reading(user_id, id) do
{:ok, temperature} ->
{:ok, assign(socket, temperature: temperature, id: id)}
{:error, reason} ->
{:error, reason}
end
end
def handle_info(:update, socket) do
{:ok, temperature} = Thermostat.get_reading(socket.assigns.id)
{:noreply, assign(socket, :temperature, temperature)}
end
end
We used `connected?(socket)` on mount to send our view a message every 30s if
the socket is in a connected state. We receive `:update_reading` in a
`handle_info` just like a GenServer, and update our socket assigns. Whenever
a socket's assigns change, `render/1` is automatically invoked, and the
updates are sent to the client.
## LiveEEx Templates
`Phoenix.LiveView`'s built-in templates provided by the `.leex`
extension or `~L` sigil, stands for Live EEx. They are similar
to regular `.eex` templates except they are designed to
minimize the amount of data sent over the wire by tracking
changes.
When you first render a `.leex` template, it will send
all of the static and dynamic parts of the template to
the client. After that, any change you do on the server
will now send only the dyamic parts and only if those
parts have changed.
The tracking of changes are done via assigns. Therefore,
if part of your template does this:
<%= something_with_user(@user) %>
That particular section will be re-rendered only if the
`@user` assign changes between events. Therefore, you
MUST pass all of the data to your templates via assigns
and avoid performing direct operations on the template
as much as possible. For example, if you perform this
operation in your template:
<%= for user <- Repo.all(User) do %>
<%= user.name %>
<% end %>
Then Phoenix will never re-render the section above, even
if the amount of users in the database changes. Instead,
you need to store the users as assigns in your LiveView
before it renders the template:
assign(socket, :users, Repo.all(User))
Generally speaking, **data loading should never happen inside
the template**, regardless if you are using LiveView or not.
The difference is that LiveView enforces those as best
practices.
Another restriction of LiveView is that, in order to track
variables, it may make some macros incompatible with `.leex`
templates. However, this would only happen if those macros
are injecting or accessing user variables, which are not
recommended in the first place. Overall, `.leex` templates
do their best to be compatible with any Elixir code, sometimes
even turning off optimizations to keep compatibility.
## Bindings
Phoenix supports DOM element bindings for client-server interaction. For
example, to react to a click on a button, you would render the element:
<button phx-click="inc_temperature">+</button>
Then on the server, all Live View bindings are handled with the `handle_event`
callback, for example:
def handle_event("inc_temperature", _value, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
### Click Events
The `phx-click` binding is used to send click events to the server. The
`value` passed to `handle_event` is chosen on the client with the following
priority:
* An optional `"phx-value"` binding on the clicked element
* The clicked element's `value` property
* An empty string
### Form Events
To handle form changes and submissions, use the `phx-change` and `phx-submit`
events. In general, it is preferred to handle input changes at the form level,
where all form fields are passed to the Live View's callback given any
single input change. For example, to handle real-time form validation and
saving, your template would use both `phx_change` and `phx_submit` bindings:
<%= form_for @changeset, "#", [phx_change: :validate, phx_submit: :save], fn f -> %>
<%= label f, :username %>
<%= text_input f, :username %>
<%= error_tag f, :username %>
<%= label f, :email %>
<%= text_input f, :email %>
<%= error_tag f, :email %>
<%= submit "Save" %>
<% end %>
Next, your Live View picks up the events in `handle_event` callbacks:
def render(assigns) ...
def mount(_session, socket) do
{:ok, assign(socket, %{changeset: Accounts.change_user(%User{})})}
end
def handle_event("validate", %{"user" => params}, socket) do
changeset =
%User{}
|> Accounts.change_user(params)
|> Map.put(:action, :insert)
{:noreply, assign(socket, changeset: changeset)}
end
def handle_event("save", %{"user" => user_params}, socket) do
case Accounts.create_user(user_params) do
{:ok, user} ->
{:stop,
socket
|> put_flash(:info, "user created")
|> redirect(to: Routes.user_path(AppWeb.Endpoint, AppWeb.User.ShowView, user))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
The validate callback simply updates the changeset based on all form input
values, then assigns the new changeset to the socket. If the changeset
changes, such as generating new errors, `render/1` is invoked and
the form is re-rendered.
Likewise for `phx-submit` bindings, the save callback is invoked and
persistence is attempted. On success, a `:stop` tuple is returned and the
socket is annotated for redirect with `Phoenix.LiveView.redirect/2`,
otherwise the socket assigns are updated with the errored changeset to be
re-rerendered for the client.
*Note*: For proper form error tag updates, the error tag must specify which
input it belongs to. This is accomplished with the `data-phx-error-for` attribute.
For example, your `AppWeb.ErrorHelpers` may use this function:
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error),
class: "help-block",
data: [phx_error_for: input_id(form, field)]
)
end)
end
### Key Events
The onkeypress, onkeydown, and onkeyup events are supported via
the `phx-keypress`, `phx-keydown`, and `phx-keyup` bindings. When
pushed, the value sent to the server will be the event's keyCode.
By default, the bound element will be the event listener, but an
optional `phx-target` may be provided which may be `"document"`,
`"window"`, or the DOM id of a target element, for example:
@up_key 38
@down_key 40
def render(assigns) do
~L\"""
<div id="thermostat" phx-keyup="update_temp" phx-target="document">
Current temperature: <%= @temperature %>
</div>
\"""
end
def handle_event("update_temp", @up_key, socket) do
{:ok, new_temp} = Thermostat.inc_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", _key, socket) do
{:ok, new_temp} = Thermostat.dec_temperature(socket.assigns.id)
{:noreply, assign(socket, :temperature, new_temp)}
end
def handle_event("update_temp", _key, socket) do
{:noreply, socket}
end
"""
alias Phoenix.LiveView
alias Phoenix.LiveView.Socket
@type unsigned_params :: map
@type from :: binary
@callback mount(session :: map, Socket.t()) ::
{:ok, Socket.t()} | {:stop, Socket.t()}
@callback render(Socket.assigns()) :: Phoenix.LiveView.Rendered.t()
@callback terminate(
reason :: :normal | :shutdown | {:shutdown, :left | :closed | term},
Socket.t()
) :: term
@callback handle_event(event :: binary, unsigned_params, Socket.t()) ::
{:noreply, Socket.t()} | {:stop, Socket.t()}
@optional_callbacks terminate: 2, mount: 2, handle_event: 3
defmacro __using__(_opts) do
quote do
import unquote(__MODULE__), except: [render: 2]
@behaviour unquote(__MODULE__)
@impl unquote(__MODULE__)
def mount(_session, socket), do: {:ok, socket}
@impl unquote(__MODULE__)
def terminate(reason, state), do: {:ok, state}
defoverridable mount: 2, terminate: 2
end
end
@doc """
Renders a Live View within an originating plug request or
within a parent Live View.
## Options
* `:session` - the map of session data to sign and send
to the client. When connecting from the client, the Live View
will receive the signed session from the client and verify
the contents before proceeding with `mount/2`.
## Examples
# within eex template
<%= live_render(@conn, MyApp.ThermostatLive) %>
# within leex template
<%= live_render(@socket, MyApp.ThermostatLive) %>
"""
def live_render(conn_or_socket, view, opts \\ []) do
opts = Keyword.put_new(opts, :session, %{})
do_live_render(conn_or_socket, view, opts)
end
defp do_live_render(%Plug.Conn{} = conn, view, opts) do
endpoint = Phoenix.Controller.endpoint_module(conn)
case LiveView.View.static_render(endpoint, view, opts) do
{:ok, content} ->
content
{:stop, {:redirect, _opts}} ->
raise RuntimeError, """
attempted to redirect from #{inspect(view)} while rendering Plug request.
Redirects from live renders inside a Plug request are not supported.
"""
end
end
defp do_live_render(%Socket{} = parent, view, opts) do
case LiveView.View.nested_static_render(parent, view, opts) do
{:ok, content} -> content
{:stop, reason} -> throw({:stop, reason})
end
end
@doc """
Returns true if the sockect is connected.
Useful for checking the connectivity status when mounting the view.
For example, on initial page render, the view is mounted statically,
rendered, and the HTML is sent to the client. Once the client
connects to the server, a Live View is then spawned and mounted
statefully within a process. Use `connected?/1` to conditionally
perform stateful work, such as subscribing to pubsub topics,
sending messages, etc.
## Examples
defmodule DemoWeb.ClockView do
use Phoenix.LiveView
...
def mount(_session, socket) do
if connected?(socket), do: :timer.send_interval(1000, self(), :tick)
{:ok, assign(socket, date: :calendar.local_time())}
end
def handle_info(:tick, socket) do
{:noreply, assign(socket, date: :calendar.local_time())}
end
end
"""
def connected?(%Socket{} = socket) do
LiveView.View.connected?(socket)
end
@doc """
Adds key value pairs to socket assigns.
A single key value pair may be passed, or a keyword list
of assigns may be provided to be merged into existing
socket assigns.
## Examples
iex> assign(socket, :name, "Elixir")
iex> assign(socket, name: "Elixir", logo: "💧")
"""
def assign(%Socket{} = socket, key, value) do
assign(socket, [{key, value}])
end
def assign(%Socket{} = socket, attrs)
when is_map(attrs) or is_list(attrs) do
Enum.reduce(attrs, socket, fn {key, val}, acc ->
case Map.fetch(acc.assigns, key) do
{:ok, ^val} -> acc
{:ok, _old_val} -> do_assign(acc, key, val)
:error -> do_assign(acc, key, val)
end
end)
end
defp do_assign(%Socket{assigns: assigns, changed: changed} = acc, key, val) do
new_changed = Map.put(changed || %{}, key, true)
new_assigns = Map.put(assigns, key, val)
%Socket{acc | assigns: new_assigns, changed: new_changed}
end
@doc """
Updates an existing key in the socket assigns.
The update function receives the current key's value and
returns the updated value. Raises if the key does not exist.
## Examples
iex> update(socket, :count, fn count -> count + 1 end)
iex> update(socket, :count, &(&1 + 1))
"""
def update(%Socket{assigns: assigns} = socket, key, func) do
case Map.fetch(assigns, key) do
{:ok, val} -> assign(socket, key, func.(val))
:error -> raise KeyError, key: key, term: assigns
end
end
@doc """
Adds a flash message to the socket to be displayed on redirect.
*Note*: the `Phoenix.LiveView.Flash` plug must be plugged in
your browser's pipeline for flash to be supported, for example:
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug Phoenix.LiveView.Flash
...
end
## Examples
iex> put_flash(socket, :info, "It worked!")
iex> put_flash(socket, :error, "You can't access that page")
"""
def put_flash(%Socket{private: private} = socket, kind, msg) do
new_private = Map.update(private, :flash, %{kind => msg}, &Map.put(&1, kind, msg))
%Socket{socket | private: new_private}
end
@doc """
Annotates the socket for redirect to a destination path.
*Note*: Live View redirects rely on instructing client
to perform a `window.location` update on the provided
redirect location.
TODO support `:external` and validation `:to` is a local path
## Options
* `:to` - the path to redirect to
"""
def redirect(%Socket{} = socket, opts) do
LiveView.View.put_redirect(socket, Keyword.fetch!(opts, :to))
end
@doc """
Provides `~L` sigil with HTML safe Live EEx syntax inside source files.
iex> ~L"\""
...> Hello <%= "world" %>
...> "\""
{:safe, ["Hello ", "world", "\\n"]}
"""
defmacro sigil_L({:<<>>, _, [expr]}, []) do
EEx.compile_string(expr, engine: Phoenix.LiveView.Engine, line: __CALLER__.line + 1)
end
end
| 33.912343 | 92 | 0.665664 |
735e81159c9a03536b02e08efbd885dd99642956 | 120 | ex | Elixir | lib/protocol/v4/frames/header/flags/tracing.ex | overdb/over_db | 0bc52de49ee684b4d63607e960d522663e17ed6a | [
"Apache-2.0"
] | 7 | 2019-04-13T01:11:18.000Z | 2020-08-11T08:11:03.000Z | lib/protocol/v4/frames/header/flags/tracing.ex | overdb/over_db | 0bc52de49ee684b4d63607e960d522663e17ed6a | [
"Apache-2.0"
] | null | null | null | lib/protocol/v4/frames/header/flags/tracing.ex | overdb/over_db | 0bc52de49ee684b4d63607e960d522663e17ed6a | [
"Apache-2.0"
] | null | null | null | defmodule OverDB.Protocol.V4.Frames.Header.Flags.Tracing do
@type t :: :tracing
def flag() do
0x02
end
end
| 12 | 59 | 0.683333 |
735ea5a7efcd2e85166fd7e6a31277645710bc2b | 640 | exs | Elixir | test/views/error_view_test.exs | dcarneiro/peepstack-api | 2c146adb12e914fea7eec5eade0bcf7c5c4ecfcc | [
"MIT"
] | null | null | null | test/views/error_view_test.exs | dcarneiro/peepstack-api | 2c146adb12e914fea7eec5eade0bcf7c5c4ecfcc | [
"MIT"
] | null | null | null | test/views/error_view_test.exs | dcarneiro/peepstack-api | 2c146adb12e914fea7eec5eade0bcf7c5c4ecfcc | [
"MIT"
] | null | null | null | defmodule Peepchat.ErrorViewTest do
use Peepchat.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.json" do
assert render(Peepchat.ErrorView, "404.json", []) ==
%{errors: [%{code: 404, title: "Not Found"}]}
end
test "render 500.json" do
assert render(Peepchat.ErrorView, "500.json", []) ==
%{errors: [%{code: 500, title: "Internal Server Error"}]}
end
test "render any other" do
assert render(Peepchat.ErrorView, "505.json", []) ==
%{errors: [%{code: 500, title: "Internal Server Error"}]}
end
end
| 29.090909 | 68 | 0.639063 |
735edb7a38f94a79925e6a69807bcff0856cd91e | 3,489 | ex | Elixir | lib/afk/state/keymap.ex | wevtimoteo/afk | a78457e59655c6999905ddb8d59a54e7d781c170 | [
"MIT"
] | null | null | null | lib/afk/state/keymap.ex | wevtimoteo/afk | a78457e59655c6999905ddb8d59a54e7d781c170 | [
"MIT"
] | null | null | null | lib/afk/state/keymap.ex | wevtimoteo/afk | a78457e59655c6999905ddb8d59a54e7d781c170 | [
"MIT"
] | 1 | 2020-01-06T13:52:14.000Z | 2020-01-06T13:52:14.000Z | defmodule AFK.State.Keymap do
@moduledoc false
alias AFK.Keycode.{Layer, None, Transparent}
@enforce_keys [:layers, :counter]
defstruct [:layers, :counter]
@type t :: %__MODULE__{
layers: %{
optional(non_neg_integer) => %{
active: bool,
activations: %{optional(atom) => AFK.Keycode.t(), optional(:default) => true},
layer: AFK.Keymap.layer()
}
},
counter: [non_neg_integer]
}
@spec new(AFK.Keymap.t()) :: t
def new([]) do
struct!(__MODULE__, layers: %{}, counter: [])
end
def new(keymap) when is_list(keymap) do
layers =
keymap
|> Enum.with_index()
|> Map.new(fn {layer, index} ->
{index,
%{
active: false,
activations: %{},
layer: layer
}}
end)
|> put_in([0, :active], true)
|> put_in([0, :activations, :default], true)
counter = Enum.to_list((Enum.count(layers) - 1)..0)
struct!(__MODULE__, layers: layers, counter: counter)
end
@spec find_keycode(t, atom) :: AFK.Keycode.t()
def find_keycode(%__MODULE__{} = keymap, key) do
case do_find_keycode(keymap.layers, keymap.counter, key) do
%_mod{} = keycode -> keycode
%{} -> %None{}
end
end
defp do_find_keycode(layers, counter, key) do
Enum.reduce_while(counter, layers, fn layer_id, acc ->
case Map.fetch!(layers, layer_id) do
%{active: true, layer: %{^key => %Transparent{}}} -> {:cont, acc}
%{active: true, layer: %{^key => keycode}} -> {:halt, keycode}
_else -> {:cont, acc}
end
end)
end
@spec add_activation(t, AFK.Keycode.Layer.t(), atom) :: t
def add_activation(%__MODULE__{} = keymap, %Layer{} = keycode, key) do
layers =
keymap.layers
|> put_in([keycode.layer, :activations, key], keycode)
|> Map.update!(keycode.layer, fn layer ->
if map_size(layer.activations) > 0 do
Map.put(layer, :active, true)
end
end)
%{keymap | layers: layers}
end
@spec remove_activation(t, AFK.Keycode.Layer.t(), atom) :: t
def remove_activation(%__MODULE__{} = keymap, %Layer{} = keycode, key) do
layers =
keymap.layers
|> update_in([keycode.layer, :activations], &Map.delete(&1, key))
|> Map.update!(keycode.layer, fn layer ->
if map_size(layer.activations) == 0 do
Map.put(layer, :active, false)
else
layer
end
end)
%{keymap | layers: layers}
end
@spec toggle_activation(t, AFK.Keycode.Layer.t(), atom) :: t
def toggle_activation(%__MODULE__{} = keymap, %Layer{} = keycode, key) do
case keymap.layers[keycode.layer].activations[key] do
^keycode -> remove_activation(keymap, keycode, key)
nil -> add_activation(keymap, keycode, key)
end
end
@spec set_default(t, AFK.Keycode.Layer.t(), atom) :: t
def set_default(%__MODULE__{} = keymap, %Layer{} = keycode, _key) do
layers =
Map.new(keymap.layers, fn {layer_id, layer} ->
cond do
layer.activations[:default] ->
{layer_id, layer |> update_in([:activations], &Map.delete(&1, :default)) |> Map.put(:active, false)}
layer_id == keycode.layer ->
{layer_id, layer |> put_in([:activations, :default], true) |> Map.put(:active, true)}
true ->
{layer_id, layer}
end
end)
%{keymap | layers: layers}
end
end
| 29.319328 | 112 | 0.573803 |
735f5b2c083aa8fb7082a4f5582ee4a804abfa76 | 4,147 | exs | Elixir | lib/mix/test/mix/local/installer_test.exs | vgsantoniazzi/elixir | b792ae50c3a61ff8b56c27b3ba63fc20ff151c77 | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/local/installer_test.exs | vgsantoniazzi/elixir | b792ae50c3a61ff8b56c27b3ba63fc20ff151c77 | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/local/installer_test.exs | vgsantoniazzi/elixir | b792ae50c3a61ff8b56c27b3ba63fc20ff151c77 | [
"Apache-2.0"
] | null | null | null | Code.require_file("../../test_helper.exs", __DIR__)
defmodule Mix.Local.InstallerTest do
use MixTest.Case
test "fetch" do
dep_spec = {:git_repo, git: fixture_path("git_repo")}
fetcher = fn mix_exs ->
send(self(), mix_exs)
Mix.Task.run("deps.get", [])
end
config =
Mix.Local.Installer.fetch(dep_spec, fetcher, fn _mix_exs ->
assert Mix.env() == :prod
Mix.Project.config()
end)
# Fetcher should run twice
assert_receive Mix.Local.Installer.MixProject
assert_receive GitRepo.MixProject
# In package runs once
assert Mix.env() == :dev
assert config[:app] == :git_repo
assert config[:deps_path] =~ ~r/mix-local-installer-fetcher-.*\/deps/
assert config[:lockfile] =~ ~r/mix-local-installer-fetcher-.*\/mix.lock/
end
test "parse_args Git" do
args = ["git", "https://example.com/user/repo.git"]
opts = [branch: "master", git: "https://example.com/user/repo.git", submodules: nil]
assert Mix.Local.Installer.parse_args(args, []) == {:fetcher, {:"new package", opts}}
end
test "parse_args Git branch" do
args = ["git", "https://example.com/user/repo.git", "branch", "not_master"]
opts = [branch: "not_master", git: "https://example.com/user/repo.git", submodules: nil]
assert Mix.Local.Installer.parse_args(args, []) == {:fetcher, {:"new package", opts}}
end
test "parse_args Git ref" do
args = ["git", "https://example.com/user/repo.git", "ref", "not_master"]
opts = [ref: "not_master", git: "https://example.com/user/repo.git", submodules: nil]
assert Mix.Local.Installer.parse_args(args, []) == {:fetcher, {:"new package", opts}}
end
test "parse_args Git tag" do
args = ["git", "https://example.com/user/repo.git", "tag", "not_master"]
opts = [tag: "not_master", git: "https://example.com/user/repo.git", submodules: nil]
assert Mix.Local.Installer.parse_args(args, []) == {:fetcher, {:"new package", opts}}
end
test "parse_args Git submodules" do
args = ["git", "https://example.com/user/repo.git"]
opts = [branch: "master", git: "https://example.com/user/repo.git", submodules: true]
assert Mix.Local.Installer.parse_args(args, submodules: true) ==
{:fetcher, {:"new package", opts}}
end
test "parse_args Git app" do
args = ["git", "https://example.com/user/repo.git"]
opts = [branch: "master", git: "https://example.com/user/repo.git", submodules: nil]
assert Mix.Local.Installer.parse_args(args, app: "my_app") == {:fetcher, {:my_app, opts}}
end
test "parse_args GitHub" do
args = ["github", "user/repo"]
opts = [branch: "master", git: "https://github.com/user/repo.git", submodules: nil]
assert Mix.Local.Installer.parse_args(args, []) == {:fetcher, {:"new package", opts}}
end
test "parse_args Hex" do
assert Mix.Local.Installer.parse_args(["hex", "a_package"], []) ==
{:fetcher, {:a_package, ">= 0.0.0", [hex: :a_package, repo: "hexpm"]}}
end
test "parse_args Hex app" do
assert Mix.Local.Installer.parse_args(["hex", "a_package"], app: "my_app") ==
{:fetcher, {:my_app, ">= 0.0.0", [hex: :a_package, repo: "hexpm"]}}
end
test "parse_args Hex version spec" do
assert Mix.Local.Installer.parse_args(["hex", "a_package", "1.0.0"], []) ==
{:fetcher, {:a_package, "1.0.0", [hex: :a_package, repo: "hexpm"]}}
end
test "parse_args Hex with organization" do
assert Mix.Local.Installer.parse_args(["hex", "a_package"], organization: "my_org") ==
{:fetcher, {:a_package, ">= 0.0.0", [hex: :a_package, repo: "hexpm:my_org"]}}
end
test "parse_args Hex with repo" do
assert Mix.Local.Installer.parse_args(["hex", "a_package"], repo: "my_repo") ==
{:fetcher, {:a_package, ">= 0.0.0", [hex: :a_package, repo: "my_repo"]}}
end
test "parse_args Hex with repo and organization" do
opts = [repo: "my_repo", organization: "my_org"]
assert Mix.Local.Installer.parse_args(["hex", "a_package"], opts) ==
{:fetcher, {:a_package, ">= 0.0.0", [hex: :a_package, repo: "my_repo:my_org"]}}
end
end
| 36.699115 | 93 | 0.626718 |
735f9ebe53d4a91585d73d7cce26d8014e18ab28 | 1,242 | ex | Elixir | lib/google_api/you_tube/v3/model/i18n_language_list_response.ex | jesteracer/ytb | 67e3cab899e4f69e586383f7be2c3855c6beea49 | [
"Apache-2.0"
] | null | null | null | lib/google_api/you_tube/v3/model/i18n_language_list_response.ex | jesteracer/ytb | 67e3cab899e4f69e586383f7be2c3855c6beea49 | [
"Apache-2.0"
] | null | null | null | lib/google_api/you_tube/v3/model/i18n_language_list_response.ex | jesteracer/ytb | 67e3cab899e4f69e586383f7be2c3855c6beea49 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.YouTube.V3.Model.I18nLanguageListResponse do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"etag",
:"eventId",
:"items",
:"kind",
:"visitorId"
]
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.I18nLanguageListResponse do
import GoogleApi.YouTube.V3.Deserializer
def decode(value, options) do
value
|> deserialize(:"items", :list, GoogleApi.YouTube.V3.Model.I18nLanguage, options)
end
end
| 28.883721 | 85 | 0.733494 |
735fa1a93fb251718684a9e23e17fd6ba2dbc590 | 1,215 | ex | Elixir | lib/mix/lib/mix/shell/io.ex | QuinnWilton/elixir | e42e3e55ca1561fe56b58d6f51c7b0faae6a7a1e | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/shell/io.ex | QuinnWilton/elixir | e42e3e55ca1561fe56b58d6f51c7b0faae6a7a1e | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/shell/io.ex | QuinnWilton/elixir | e42e3e55ca1561fe56b58d6f51c7b0faae6a7a1e | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Shell.IO do
@moduledoc """
This is Mix's default shell.
It simply prints messages to stdio and stderr.
"""
@behaviour Mix.Shell
@doc """
Executes the given command and prints its output
to stdout as it comes.
"""
def cmd(command) do
put_app
Mix.Shell.cmd(command, &IO.write(&1))
end
@doc """
Writes a message to the shell followed by new line.
"""
def info(message) do
put_app
IO.puts IO.ANSI.escape(message)
end
@doc """
Writes an error message to the shell followed by new line.
"""
def error(message) do
put_app
IO.puts :stderr, IO.ANSI.escape "%{red,bright}#{message}"
end
@doc """
Receives a message and asks the user if he wants to proceed.
He must press enter or type anything that matches the a "yes"
regex `%r/^Y(es)?$/i`.
"""
def yes?(message) do
put_app
got_yes? IO.gets(message <> IO.ANSI.escape(" [Yn] "))
end
defp got_yes?(answer) when is_binary(answer) do
Regex.match?(%r/^(Y(es)?)?$/i, answer)
end
# The io server may return :eof or :error
defp got_yes?(_), do: false
defp put_app do
if Mix.Shell.output_app? do
IO.puts "==> #{Mix.project[:app]}"
end
end
end
| 21.315789 | 63 | 0.636214 |
735fbf4ff76154536be61186cf3fcfb2d9490b3a | 90,490 | ex | Elixir | lib/elixir/lib/kernel.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | jbcrail/elixir | f30ef15d9d028a6d0f74d10c2bb320d5f8501bdb | [
"Apache-2.0"
] | null | null | null | # Use elixir_bootstrap module to be able to bootstrap Kernel.
# The bootstrap module provides simpler implementations of the
# functions removed, simple enough to bootstrap.
import Kernel, except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2,
defmacro: 1, defmacro: 2, defmacrop: 2]
import :elixir_bootstrap
defmodule Kernel do
@moduledoc """
`Kernel` provides the default macros and functions
Elixir imports into your environment. These macros and functions
can be skipped or cherry-picked via the `import` macro. For
instance, if you want to tell Elixir not to import the `if`
macro, you can do:
import Kernel, except: [if: 2]
Elixir also has special forms that are always imported and
cannot be skipped. These are described in `Kernel.SpecialForms`.
Some of the functions described in this module are inlined by
the Elixir compiler into their Erlang counterparts in the `:erlang`
module. Those functions are called BIFs (builtin internal functions)
in Erlang-land and they exhibit interesting properties, as some of
them are allowed in guards and others are used for compiler
optimizations.
Most of the inlined functions can be seen in effect when capturing
the function:
iex> &Kernel.is_atom/1
&:erlang.is_atom/1
Those functions will be explicitly marked in their docs as
"inlined by the compiler".
"""
## Delegations to Erlang with inlining (macros)
@doc """
Returns an integer or float which is the arithmetical absolute value of `number`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> abs(-3.33)
3.33
iex> abs(-3)
3
"""
@spec abs(number) :: number
def abs(number) do
:erlang.abs(number)
end
@doc """
Invokes the given `fun` with the array of arguments `args`.
Inlined by the compiler.
## Examples
iex> apply(fn x -> x * 2 end, [2])
4
"""
@spec apply(fun, [any]) :: any
def apply(fun, args) do
:erlang.apply(fun, args)
end
@doc """
Invokes the given `fun` from `module` with the array of arguments `args`.
Inlined by the compiler.
## Examples
iex> apply(Enum, :reverse, [[1, 2, 3]])
[3,2,1]
"""
@spec apply(module, atom, [any]) :: any
def apply(module, fun, args) do
:erlang.apply(module, fun, args)
end
@doc """
Extracts the part of the binary starting at `start` with length `length`.
Binaries are zero-indexed.
If start or length references in any way outside the binary, an
`ArgumentError` exception is raised.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> binary_part("foo", 1, 2)
"oo"
A negative length can be used to extract bytes at the end of a binary:
iex> binary_part("foo", 3, -1)
"o"
"""
@spec binary_part(binary, pos_integer, integer) :: binary
def binary_part(binary, start, length) do
:erlang.binary_part(binary, start, length)
end
@doc """
Returns an integer which is the size in bits of `bitstring`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> bit_size(<<433::16, 3::3>>)
19
iex> bit_size(<<1, 2, 3>>)
24
"""
@spec bit_size(bitstring) :: non_neg_integer
def bit_size(bitstring) do
:erlang.bit_size(bitstring)
end
@doc """
Returns the number of bytes needed to contain `bitstring`.
That is, if the number of bits in `bitstring` is not divisible by 8,
the resulting number of bytes will be rounded up. This operation
happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> byte_size(<<433::16, 3::3>>)
3
iex> byte_size(<<1, 2, 3>>)
3
"""
@spec byte_size(binary) :: non_neg_integer
def byte_size(binary) do
:erlang.byte_size(binary)
end
@doc """
Performs an integer division.
Raises an error if one of the arguments is not an integer.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> div(5, 2)
2
"""
@spec div(integer, integer) :: integer
def div(left, right) do
:erlang.div(left, right)
end
@doc """
Stops the execution of the calling process with the given reason.
Since evaluating this function causes the process to terminate,
it has no return value.
Inlined by the compiler.
## Examples
When a process reaches its end, by default it exits with
reason `:normal`. You can also call it explicitly if you
want to terminate a process but not signal any failure:
exit(:normal)
In case something goes wrong, you can also use `exit/1` with
a different reason:
exit(:seems_bad)
If the reason is not `:normal`, all linked process to the
exited process will crash (unless they are trapping exits).
## OTP exits
Exits are used by OTP to determine if a process exited abnormally
or not. The following exits are considered "normal":
* `exit(:normal)`
* `exit(:shutdown)`
* `exit({:shutdown, term})`
Exiting with any other reason is considered abnormal and treated
as a crash. This means the default supervisor behaviour kicks in,
error reports are emitted, etc.
This behaviour is relied on in many different places. For example,
`ExUnit` uses `exit(:shutdown)` when exiting the test process to
signal linked processes, supervision trees and so on to politely
shutdown too.
## CLI exits
Building on top of the exit signals mentioned above, if the
process started by the command line exits with any of the three
reasons above, its exit is considered normal and the Operating
System process will exit with status 0.
It is, however, possible to customize the Operating System exit
signal by invoking:
exit({:shutdown, integer})
This will cause the OS process to exit with the status given by
`integer` while signaling all linked OTP processes to politely
shutdown.
Any other exit reason will cause the OS process to exit with
status `1` and linked OTP processes to crash.
"""
@spec exit(term) :: no_return
def exit(reason) do
:erlang.exit(reason)
end
@doc """
Returns the head of a list, raises `badarg` if the list is empty.
Inlined by the compiler.
"""
@spec hd(list) :: term
def hd(list) do
:erlang.hd(list)
end
@doc """
Returns `true` if `term` is an atom; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_atom(term) :: boolean
def is_atom(term) do
:erlang.is_atom(term)
end
@doc """
Returns `true` if `term` is a binary; otherwise returns `false`.
A binary always contains a complete number of bytes.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_binary(term) :: boolean
def is_binary(term) do
:erlang.is_binary(term)
end
@doc """
Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_bitstring(term) :: boolean
def is_bitstring(term) do
:erlang.is_bitstring(term)
end
@doc """
Returns `true` if `term` is either the atom `true` or the atom `false` (i.e. a boolean);
otherwise returns false.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_boolean(term) :: boolean
def is_boolean(term) do
:erlang.is_boolean(term)
end
@doc """
Returns `true` if `term` is a floating point number; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_float(term) :: boolean
def is_float(term) do
:erlang.is_float(term)
end
@doc """
Returns `true` if `term` is a function; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_function(term) :: boolean
def is_function(term) do
:erlang.is_function(term)
end
@doc """
Returns `true` if `term` is a function that can be applied with `arity` number of arguments;
otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_function(term, non_neg_integer) :: boolean
def is_function(term, arity) do
:erlang.is_function(term, arity)
end
@doc """
Returns `true` if `term` is an integer; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_integer(term) :: boolean
def is_integer(term) do
:erlang.is_integer(term)
end
@doc """
Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_list(term) :: boolean
def is_list(term) do
:erlang.is_list(term)
end
@doc """
Returns `true` if `term` is either an integer or a floating point number;
otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_number(term) :: boolean
def is_number(term) do
:erlang.is_number(term)
end
@doc """
Returns `true` if `term` is a pid (process identifier); otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_pid(term) :: boolean
def is_pid(term) do
:erlang.is_pid(term)
end
@doc """
Returns `true` if `term` is a port identifier; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_port(term) :: boolean
def is_port(term) do
:erlang.is_port(term)
end
@doc """
Returns `true` if `term` is a reference; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_reference(term) :: boolean
def is_reference(term) do
:erlang.is_reference(term)
end
@doc """
Returns `true` if `term` is a tuple; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_tuple(term) :: boolean
def is_tuple(term) do
:erlang.is_tuple(term)
end
@doc """
Returns `true` if `term` is a map; otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
"""
@spec is_map(term) :: boolean
def is_map(term) do
:erlang.is_map(term)
end
@doc """
Returns the length of `list`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9])
9
"""
@spec length(list) :: non_neg_integer
def length(list) do
:erlang.length(list)
end
@doc """
Returns an almost unique reference.
The returned reference will re-occur after approximately 2^82 calls;
therefore it is unique enough for practical purposes.
Inlined by the compiler.
## Examples
make_ref() #=> #Reference<0.0.0.135>
"""
@spec make_ref() :: reference
def make_ref() do
:erlang.make_ref()
end
@doc """
Returns the size of a map.
This operation happens in constant time.
Allowed in guard tests. Inlined by the compiler.
"""
@spec map_size(map) :: non_neg_integer
def map_size(map) do
:erlang.map_size(map)
end
@doc """
Return the biggest of the two given terms according to
Erlang's term ordering. If the terms compare equal, the
first one is returned.
Inlined by the compiler.
## Examples
iex> max(1, 2)
2
"""
@spec max(term, term) :: term
def max(first, second) do
:erlang.max(first, second)
end
@doc """
Return the smallest of the two given terms according to
Erlang's term ordering. If the terms compare equal, the
first one is returned.
Inlined by the compiler.
## Examples
iex> min(1, 2)
1
"""
@spec min(term, term) :: term
def min(first, second) do
:erlang.min(first, second)
end
@doc """
Returns an atom representing the name of the local node.
If the node is not alive, `:nonode@nohost` is returned instead.
Allowed in guard tests. Inlined by the compiler.
"""
@spec node() :: node
def node do
:erlang.node
end
@doc """
Returns the node where the given argument is located.
The argument can be a pid, a reference, or a port.
If the local node is not alive, `nonode@nohost` is returned.
Allowed in guard tests. Inlined by the compiler.
"""
@spec node(pid|reference|port) :: node
def node(arg) do
:erlang.node(arg)
end
@doc """
Calculates the remainder of an integer division.
Raises an error if one of the arguments is not an integer.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> rem(5, 2)
1
"""
@spec rem(integer, integer) :: integer
def rem(left, right) do
:erlang.rem(left, right)
end
@doc """
Returns an integer by rounding the given number.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> round(5.5)
6
"""
@spec round(number) :: integer
def round(number) do
:erlang.round(number)
end
@doc """
Sends a message to the given `dest` and returns the message.
`dest` may be a remote or local pid, a (local) port, a locally
registered name, or a tuple `{registered_name, node}` for a registered
name at another node.
Inlined by the compiler.
## Examples
iex> send self(), :hello
:hello
"""
@spec send(dest :: pid | port | atom | {atom, node}, msg) :: msg when msg: any
def send(dest, msg) do
:erlang.send(dest, msg)
end
@doc """
Returns the pid (process identifier) of the calling process.
Allowed in guard clauses. Inlined by the compiler.
"""
@spec self() :: pid
def self() do
:erlang.self()
end
@doc """
Spawns the given function and returns its pid.
Check the modules `Process` and `Node` for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
current = Kernel.self
child = spawn(fn -> send current, {Kernel.self, 1 + 2} end)
receive do
{^child, 3} -> IO.puts "Received 3 back"
end
"""
@spec spawn((() -> any)) :: pid
def spawn(fun) do
:erlang.spawn(fun)
end
@doc """
Spawns the given module and function passing the given args
and returns its pid.
Check the modules `Process` and `Node` for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
spawn(SomeModule, :function, [1, 2, 3])
"""
@spec spawn(module, atom, list) :: pid
def spawn(module, fun, args) do
:erlang.spawn(module, fun, args)
end
@doc """
Spawns the given function, links it to the current process and returns its pid.
Check the modules `Process` and `Node` for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
current = Kernel.self
child = spawn_link(fn -> send current, {Kernel.self, 1 + 2} end)
receive do
{^child, 3} -> IO.puts "Received 3 back"
end
"""
@spec spawn_link((() -> any)) :: pid
def spawn_link(fun) do
:erlang.spawn_link(fun)
end
@doc """
Spawns the given module and function passing the given args,
links it to the current process and returns its pid.
Check the modules `Process` and `Node` for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
spawn_link(SomeModule, :function, [1, 2, 3])
"""
@spec spawn_link(module, atom, list) :: pid
def spawn_link(module, fun, args) do
:erlang.spawn_link(module, fun, args)
end
@doc """
Spawns the given function, monitors it and returns its pid
and monitoring reference.
Check the modules `Process` and `Node` for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
current = Kernel.self
spawn_monitor(fn -> send current, {Kernel.self, 1 + 2} end)
"""
@spec spawn_monitor((() -> any)) :: {pid, reference}
def spawn_monitor(fun) do
:erlang.spawn_monitor(fun)
end
@doc """
Spawns the given module and function passing the given args,
monitors it and returns its pid and monitoring reference.
Check the modules `Process` and `Node` for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
spawn_monitor(SomeModule, :function, [1, 2, 3])
"""
@spec spawn_monitor(module, atom, list) :: {pid, reference}
def spawn_monitor(module, fun, args) do
:erlang.spawn_monitor(module, fun, args)
end
@doc """
A non-local return from a function. Check `Kernel.SpecialForms.try/1` for more information.
Inlined by the compiler.
"""
@spec throw(term) :: no_return
def throw(term) do
:erlang.throw(term)
end
@doc """
Returns the tail of a list. Raises `ArgumentError` if the list is empty.
Allowed in guard tests. Inlined by the compiler.
"""
@spec tl(maybe_improper_list) :: maybe_improper_list
def tl(list) do
:erlang.tl(list)
end
@doc """
Returns an integer by truncating the given number.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> trunc(5.5)
5
"""
@spec trunc(number) :: integer
def trunc(number) do
:erlang.trunc(number)
end
@doc """
Returns the size of a tuple.
This operation happens in constant time.
Allowed in guard tests. Inlined by the compiler.
"""
@spec tuple_size(tuple) :: non_neg_integer
def tuple_size(tuple) do
:erlang.tuple_size(tuple)
end
@doc """
Arithmetic plus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 + 2
3
"""
@spec (number + number) :: number
def left + right do
:erlang.+(left, right)
end
@doc """
Arithmetic minus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 - 2
-1
"""
@spec (number - number) :: number
def left - right do
:erlang.-(left, right)
end
@doc """
Arithmetic unary plus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> +1
1
"""
@spec (+number) :: number
def (+value) do
:erlang.+(value)
end
@doc """
Arithmetic unary minus.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> -2
-2
"""
@spec (-number) :: number
def (-value) do
:erlang.-(value)
end
@doc """
Arithmetic multiplication.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 * 2
2
"""
@spec (number * number) :: number
def left * right do
:erlang.*(left, right)
end
@doc """
Arithmetic division.
The result is always a float. Use `div` and `rem` if you want
a natural division or the remainder.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 / 2
0.5
iex> 2 / 1
2.0
"""
@spec (number / number) :: float
def left / right do
:erlang./(left, right)
end
@doc """
Concatenates two lists.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> [1] ++ [2, 3]
[1,2,3]
iex> 'foo' ++ 'bar'
'foobar'
"""
@spec (list ++ term) :: maybe_improper_list
def left ++ right do
:erlang.++(left, right)
end
@doc """
Removes the first occurrence of an item on the left
for each item on the right.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> [1, 2, 3] -- [1, 2]
[3]
iex> [1, 2, 3, 2, 1] -- [1, 2, 2]
[3,1]
"""
@spec (list -- list) :: list
def left -- right do
:erlang.--(left, right)
end
@doc """
Boolean not. Argument must be a boolean.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> not false
true
"""
@spec not(boolean) :: boolean
def not(arg) do
:erlang.not(arg)
end
@doc """
Returns `true` if left is less than right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 < 2
true
"""
@spec (term < term) :: boolean
def left < right do
:erlang.<(left, right)
end
@doc """
Returns `true` if left is more than right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 > 2
false
"""
@spec (term > term) :: boolean
def left > right do
:erlang.>(left, right)
end
@doc """
Returns `true` if left is less than or equal to right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 <= 2
true
"""
@spec (term <= term) :: boolean
def left <= right do
:erlang."=<"(left, right)
end
@doc """
Returns `true` if left is more than or equal to right.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 >= 2
false
"""
@spec (term >= term) :: boolean
def left >= right do
:erlang.>=(left, right)
end
@doc """
Returns `true` if the two items are equal.
This operator considers 1 and 1.0 to be equal. For match
semantics, use `===` instead.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 == 2
false
iex> 1 == 1.0
true
"""
@spec (term == term) :: boolean
def left == right do
:erlang.==(left, right)
end
@doc """
Returns `true` if the two items are not equal.
This operator considers 1 and 1.0 to be equal. For match
comparison, use `!==` instead.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 != 2
true
iex> 1 != 1.0
false
"""
@spec (term != term) :: boolean
def left != right do
:erlang."/="(left, right)
end
@doc """
Returns `true` if the two items are match.
This operator gives the same semantics as the one existing in
pattern matching, i.e., `1` and `1.0` are equal, but they do
not match.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 === 2
false
iex> 1 === 1.0
false
"""
@spec (term === term) :: boolean
def left === right do
:erlang."=:="(left, right)
end
@doc """
Returns `true` if the two items do not match.
All terms in Elixir can be compared with each other.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> 1 !== 2
true
iex> 1 !== 1.0
true
"""
@spec (term !== term) :: boolean
def left !== right do
:erlang."=/="(left, right)
end
@doc """
Get the element at the zero-based `index` in `tuple`.
Allowed in guard tests. Inlined by the compiler.
## Example
iex> tuple = {:foo, :bar, 3}
iex> elem(tuple, 1)
:bar
"""
@spec elem(tuple, non_neg_integer) :: term
def elem(tuple, index) do
:erlang.element(index + 1, tuple)
end
@doc """
Puts the element in `tuple` at the zero-based `index` to the given `value`.
Inlined by the compiler.
## Example
iex> tuple = {:foo, :bar, 3}
iex> put_elem(tuple, 0, :baz)
{:baz, :bar, 3}
"""
@spec put_elem(tuple, non_neg_integer, term) :: tuple
def put_elem(tuple, index, value) do
:erlang.setelement(index + 1, tuple, value)
end
## Implemented in Elixir
@doc """
Boolean or. Requires only the first argument to be a
boolean since it short-circuits.
Allowed in guard tests.
## Examples
iex> true or false
true
"""
defmacro left or right do
quote do: __op__(:orelse, unquote(left), unquote(right))
end
@doc """
Boolean and. Requires only the first argument to be a
boolean since it short-circuits.
Allowed in guard tests.
## Examples
iex> true and false
false
"""
defmacro left and right do
quote do: __op__(:andalso, unquote(left), unquote(right))
end
@doc """
Receives any argument and returns `true` if it is `false`
or `nil`. Returns `false` otherwise. Not allowed in guard
clauses.
## Examples
iex> !Enum.empty?([])
false
iex> !List.first([])
true
"""
defmacro !(arg)
defmacro !({:!, _, [arg]}) do
optimize_boolean(quote do
case unquote(arg) do
x when x in [false, nil] -> false
_ -> true
end
end)
end
defmacro !(arg) do
optimize_boolean(quote do
case unquote(arg) do
x when x in [false, nil] -> true
_ -> false
end
end)
end
@doc """
Concatenates two binaries.
## Examples
iex> "foo" <> "bar"
"foobar"
The `<>` operator can also be used in guard clauses as
long as the first part is a literal binary:
iex> "foo" <> x = "foobar"
iex> x
"bar"
"""
defmacro left <> right do
concats = extract_concatenations({:<>, [], [left, right]})
quote do: << unquote_splicing(concats) >>
end
# Extracts concatenations in order to optimize many
# concatenations into one single clause.
defp extract_concatenations({:<>, _, [left, right]}) do
[wrap_concatenation(left)|extract_concatenations(right)]
end
defp extract_concatenations(other) do
[wrap_concatenation(other)]
end
defp wrap_concatenation(binary) when is_binary(binary) do
binary
end
defp wrap_concatenation(other) do
{:::, [], [other, {:binary, [], nil}]}
end
@doc """
Raises an exception.
If the argument is a binary, it raises `RuntimeError`
using the given argument as message.
If an atom, it will become a call to `raise(atom, [])`.
If anything else, it will just raise the given exception.
## Examples
raise "Given values do not match"
try do
1 + :foo
rescue
x in [ArithmeticError] ->
IO.puts "that was expected"
raise x
end
"""
defmacro raise(msg) do
# Try to figure out the type at compilation time
# to avoid dead code and make dialyzer happy.
msg = case not is_binary(msg) and bootstraped?(Macro) do
true -> Macro.expand(msg, __CALLER__)
false -> msg
end
case msg do
msg when is_binary(msg) ->
quote do
:erlang.error RuntimeError.exception(unquote(msg))
end
{:<<>>, _, _} = msg ->
quote do
:erlang.error RuntimeError.exception(unquote(msg))
end
alias when is_atom(alias) ->
quote do
:erlang.error unquote(alias).exception([])
end
_ ->
quote do
case unquote(msg) do
msg when is_binary(msg) ->
:erlang.error RuntimeError.exception(msg)
atom when is_atom(atom) ->
:erlang.error atom.exception([])
%{__struct__: struct, __exception__: true} = other when is_atom(struct) ->
:erlang.error other
end
end
end
end
@doc """
Raises an exception.
Calls `.exception` on the given argument passing
the attributes in order to retrieve the appropriate exception
structure.
Any module defined via `defexception/1` automatically
implements `exception(attrs)` callback expected by `raise/2`.
## Examples
iex> raise(ArgumentError, message: "Sample")
** (ArgumentError) Sample
"""
defmacro raise(exception, attrs) do
quote do
:erlang.error unquote(exception).exception(unquote(attrs))
end
end
@doc """
Raises an exception preserving a previous stacktrace.
Works like `raise/1` but does not generate a new stacktrace.
Notice that `System.stacktrace` returns the stacktrace
of the last exception. That said, it is common to assign
the stacktrace as the first expression inside a `rescue`
clause as any other exception potentially raised (and
rescued) in between the rescue clause and the raise call
may change the `System.stacktrace` value.
## Examples
try do
raise "Oops"
rescue
exception ->
stacktrace = System.stacktrace
if Exception.message(exception) == "Oops" do
reraise exception, stacktrace
end
end
"""
defmacro reraise(msg, stacktrace) do
# Try to figure out the type at compilation time
# to avoid dead code and make dialyzer happy.
case Macro.expand(msg, __CALLER__) do
msg when is_binary(msg) ->
quote do
:erlang.raise :error, RuntimeError.exception(unquote(msg)), unquote(stacktrace)
end
{:<<>>, _, _} = msg ->
quote do
:erlang.raise :error, RuntimeError.exception(unquote(msg)), unquote(stacktrace)
end
alias when is_atom(alias) ->
quote do
:erlang.raise :error, unquote(alias).exception([]), unquote(stacktrace)
end
msg ->
quote do
stacktrace = unquote(stacktrace)
case unquote(msg) do
msg when is_binary(msg) ->
:erlang.raise :error, RuntimeError.exception(msg), stacktrace
atom when is_atom(atom) ->
:erlang.raise :error, atom.exception([]), stacktrace
%{__struct__: struct, __exception__: true} = other when is_atom(struct) ->
:erlang.raise :error, other, stacktrace
end
end
end
end
@doc """
Raises an exception preserving a previous stacktrace.
Works like `raise/2` but does not generate a new stacktrace.
See `reraise/2` for more details.
## Examples
try do
raise "Oops"
rescue
exception ->
stacktrace = System.stacktrace
reraise WrapperError, [exception: exception], stacktrace
end
"""
defmacro reraise(exception, attrs, stacktrace) do
quote do
:erlang.raise :error, unquote(exception).exception(unquote(attrs)), unquote(stacktrace)
end
end
@doc """
Matches the term on the left against the regular expression or string on the
right. Returns true if `left` matches `right` (if it's a regular expression)
or contains `right` (if it's a string).
## Examples
iex> "abcd" =~ ~r/c(d)/
true
iex> "abcd" =~ ~r/e/
false
iex> "abcd" =~ "bc"
true
iex> "abcd" =~ "ad"
false
"""
def left =~ right when is_binary(left) and is_binary(right) do
:binary.match(left, right) != :nomatch
end
def left =~ right when is_binary(left) do
Regex.match?(right, left)
end
@doc ~S"""
Inspect the given argument according to the `Inspect` protocol.
The second argument is a keywords list with options to control
inspection.
## Options
`inspect/2` accepts a list of options that are internally
translated to an `Inspect.Opts` struct. Check the docs for
`Inspect.Opts` to see the supported options.
## Examples
iex> inspect(:foo)
":foo"
iex> inspect [1, 2, 3, 4, 5], limit: 3
"[1, 2, 3, ...]"
iex> inspect("olá" <> <<0>>)
"<<111, 108, 195, 161, 0>>"
iex> inspect("olá" <> <<0>>, binaries: :as_strings)
"\"olá\\0\""
iex> inspect("olá", binaries: :as_binaries)
"<<111, 108, 195, 161>>"
iex> inspect('bar')
"'bar'"
iex> inspect([0|'bar'])
"[0, 98, 97, 114]"
iex> inspect(100, base: :octal)
"0o144"
iex> inspect(100, base: :hex)
"0x64"
Note that the inspect protocol does not necessarily return a valid
representation of an Elixir term. In such cases, the inspected result
must start with `#`. For example, inspecting a function will return:
inspect fn a, b -> a + b end
#=> #Function<...>
"""
@spec inspect(Inspect.t, Keyword.t) :: String.t
def inspect(arg, opts \\ []) when is_list(opts) do
opts = struct(Inspect.Opts, opts)
limit = case opts.pretty do
true -> opts.width
false -> :infinity
end
IO.iodata_to_binary(
Inspect.Algebra.format(Inspect.Algebra.to_doc(arg, opts), limit)
)
end
@doc """
Creates and updates structs.
The struct argument may be an atom (which defines `defstruct`)
or a struct itself. The second argument is any Enumerable that
emits two-item tuples (key-value) during enumeration.
If one of the keys in the Enumerable does not exist in the struct,
they are automatically discarded.
This function is useful for dynamically creating and updating
structs.
## Example
defmodule User do
defstruct name: "john"
end
struct(User)
#=> %User{name: "john"}
opts = [name: "meg"]
user = struct(User, opts)
#=> %User{name: "meg"}
struct(user, unknown: "value")
#=> %User{name: "meg"}
"""
@spec struct(module | map, Enum.t) :: map
def struct(struct, kv \\ [])
def struct(struct, []) when is_atom(struct) or is_tuple(struct) do
apply(struct, :__struct__, [])
end
def struct(struct, kv) when is_atom(struct) or is_tuple(struct) do
struct(apply(struct, :__struct__, []), kv)
end
def struct(%{__struct__: _} = struct, kv) do
Enum.reduce(kv, struct, fn {k, v}, acc ->
case :maps.is_key(k, acc) and k != :__struct__ do
true -> :maps.put(k, v, acc)
false -> acc
end
end)
end
@doc """
Gets a value from a nested structure.
Uses the `Access` protocol to traverse the structures
according to the given `keys`, unless the `key` is a
function.
If a key is a function, the function will be invoked
passing three arguments, the operation (`:get`), the
data to be accessed, and a function to be invoked next.
This means `get_in/2` can be extended to provide
custom lookups. The downside is that functions cannot be
stored as keys in the accessed data structures.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["john", :age])
27
In case any of entries in the middle returns `nil`, `nil` will be returned
as per the Access protocol:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_in(users, ["unknown", :age])
nil
When one of the keys is a function, the function is invoked.
In the example below, we use a function to get all the maps
inside a list:
iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}]
iex> all = fn :get, data, next -> Enum.map(data, next) end
iex> get_in(users, [all, :age])
[27, 23]
If the previous value before invoking the function is nil,
the function *will* receive nil as a value and must handle it
accordingly.
"""
@spec get_in(Access.t, nonempty_list(term)) :: term
def get_in(data, keys)
def get_in(data, [h]) when is_function(h),
do: h.(:get, data, &(&1))
def get_in(data, [h|t]) when is_function(h),
do: h.(:get, data, &get_in(&1, t))
def get_in(nil, [_]),
do: nil
def get_in(nil, [_|t]),
do: get_in(nil, t)
def get_in(data, [h]),
do: Access.get(data, h)
def get_in(data, [h|t]),
do: get_in(Access.get(data, h), t)
@doc """
Puts a value in a nested structure.
Uses the `Access` protocol to traverse the structures
according to the given `keys`, unless the `key` is a
function. If the key is a function, it will be invoked
as specified in `get_and_update_in/3`.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users, ["john", :age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of entries in the middle returns `nil`,
an error will be raised when trying to access it next.
"""
@spec put_in(Access.t, nonempty_list(term), term) :: Access.t
def put_in(data, keys, value) do
elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1)
end
@doc """
Updates a key in a nested structure.
Uses the `Access` protocol to traverse the structures
according to the given `keys`, unless the `key` is a
function. If the key is a function, it will be invoked
as specified in `get_and_update_in/3`.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users, ["john", :age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
In case any of entries in the middle returns `nil`,
an error will be raised when trying to access it next.
"""
@spec update_in(Access.t, nonempty_list(term), (term -> term)) :: Access.t
def update_in(data, keys, fun) do
elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1)
end
@doc """
Gets a value and updates a nested structure.
It expects a tuple to be returned, containing the value
retrieved and the update one.
Uses the `Access` protocol to traverse the structures
according to the given `keys`, unless the `key` is a
function.
If a key is a function, the function will be invoked
passing three arguments, the operation (`:get_and_update`),
the data to be accessed, and a function to be invoked next.
This means `get_and_update_in/3` can be extended to provide
custom lookups. The downside is that functions cannot be stored
as keys in the accessed data structures.
## Examples
This function is useful when there is a need to retrieve the current
value (or something calculated in function of the current value) and
update it at the same time. For example, it could be used to increase
the age of a user by one and return the previous age in one pass:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1})
{27, %{"john" => %{age: 28}, "meg" => %{age: 23}}}
When one of the keys is a function, the function is invoked.
In the example below, we use a function to get and increment all
ages inside a list:
iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}]
iex> all = fn :get_and_update, data, next ->
...> Enum.map(data, next) |> :lists.unzip
...> end
iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1})
{[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]}
If the previous value before invoking the function is nil,
the function *will* receive `nil` as a value and must handle it
accordingly (be it by failing or providing a sane default).
"""
@spec get_and_update_in(Access.t, nonempty_list(term),
(term -> {get, term})) :: {get, Access.t} when get: var
def get_and_update_in(data, keys, fun)
def get_and_update_in(data, [h], fun) when is_function(h),
do: h.(:get_and_update, data, fun)
def get_and_update_in(data, [h|t], fun) when is_function(h),
do: h.(:get_and_update, data, &get_and_update_in(&1, t, fun))
def get_and_update_in(data, [h], fun),
do: Access.get_and_update(data, h, fun)
def get_and_update_in(data, [h|t], fun),
do: Access.get_and_update(data, h, &get_and_update_in(&1, t, fun))
@doc """
Puts a value in a nested structure via the given `path`.
This is similar to `put_in/3`, except the path is extracted via
a macro rather than passing a list. For example:
put_in(opts[:foo][:bar], :baz)
Is equivalent to:
put_in(opts, [:foo, :bar], :baz)
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check `get_and_update_in/2` docs.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"][:age], 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"].age, 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
"""
defmacro put_in(path, value) do
[h|t] = unnest(path, [], "put_in/2")
expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end))
quote do: :erlang.element(2, unquote(expr))
end
@doc """
Updates a nested structure via the given `path`.
This is similar to `update_in/3`, except the path is extracted via
a macro rather than passing a list. For example:
update_in(opts[:foo][:bar], &(&1 + 1))
Is equivalent to:
update_in(opts, [:foo, :bar], &(&1 + 1))
Note that in order for this macro to work, the complete path must always
be visible by this macro. For more information about the supported path
expressions, please check `get_and_update_in/2` docs.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users["john"][:age], &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> update_in(users["john"].age, &(&1 + 1))
%{"john" => %{age: 28}, "meg" => %{age: 23}}
"""
defmacro update_in(path, fun) do
[h|t] = unnest(path, [], "update_in/2")
expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end))
quote do: :erlang.element(2, unquote(expr))
end
@doc """
Gets a value and updates a nested data structure via the given `path`.
This is similar to `get_and_update_in/3`, except the path is extracted
via a macro rather than passing a list. For example:
get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1})
Is equivalent to:
get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1})
Note that in order for this macro to work, the complete path must always
be visible by this macro. See the Paths section below.
## Examples
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> get_and_update_in(users["john"].age, &{&1, &1 + 1})
{27, %{"john" => %{age: 28}, "meg" => %{age: 23}}}
## Paths
A path may start with a variable, local or remote call, and must be
followed by one or more:
* `foo[bar]` - access a field; in case an intermediate field is not
present or returns nil, an empty map is used
* `foo.bar` - access a map/struct field; in case the field is not
present, an error is raised
Here are some valid paths:
users["john"][:age]
users["john"].age
User.all["john"].age
all_users()["john"].age
Here are some invalid ones:
# Does a remote call after the initial value
users["john"].do_something(arg1, arg2)
# Does not access any field
users
"""
defmacro get_and_update_in(path, fun) do
[h|t] = unnest(path, [], "get_and_update_in/2")
nest_get_and_update_in(h, t, fun)
end
defp nest_get_and_update_in([], fun), do: fun
defp nest_get_and_update_in(list, fun) do
quote do
fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end
end
end
defp nest_get_and_update_in(h, [{:access, key}|t], fun) do
quote do
Access.get_and_update(
unquote(h),
unquote(key),
unquote(nest_get_and_update_in(t, fun))
)
end
end
defp nest_get_and_update_in(h, [{:map, key}|t], fun) do
quote do
Access.Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun)))
end
end
defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, kind) do
unnest(expr, [{:access, key}|acc], kind)
end
defp unnest({{:., _, [expr, key]}, _, []}, acc, kind)
when is_tuple(expr) and
:erlang.element(1, expr) != :__aliases__ and
:erlang.element(1, expr) != :__MODULE__ do
unnest(expr, [{:map, key}|acc], kind)
end
defp unnest(other, [], kind) do
raise ArgumentError,
"expected expression given to #{kind} to access at least one element, got: #{Macro.to_string other}"
end
defp unnest(other, acc, kind) do
case proper_start?(other) do
true -> [other|acc]
false ->
raise ArgumentError,
"expression given to #{kind} must start with a variable, local or remote call " <>
"and be followed by an element access, got: #{Macro.to_string other}"
end
end
defp proper_start?({{:., _, [expr, _]}, _, _args})
when is_atom(expr)
when :erlang.element(1, expr) == :__aliases__
when :erlang.element(1, expr) == :__MODULE__, do: true
defp proper_start?({atom, _, _args})
when is_atom(atom), do: true
defp proper_start?(other),
do: not is_tuple(other)
@doc """
Converts the argument to a string according to the
`String.Chars` protocol.
This is the function invoked when there is string interpolation.
## Examples
iex> to_string(:foo)
"foo"
"""
# If it is a binary at compilation time, simply return it.
defmacro to_string(arg) when is_binary(arg), do: arg
defmacro to_string(arg) do
quote do: String.Chars.to_string(unquote(arg))
end
@doc """
Convert the argument to a list according to the List.Chars protocol.
## Examples
iex> to_char_list(:foo)
'foo'
"""
defmacro to_char_list(arg) do
quote do: List.Chars.to_char_list(unquote(arg))
end
@doc """
Returns `true` if `term` is nil; otherwise returns `false`.
Allowed in guard clauses.
## Examples
iex> is_nil(1)
false
iex> is_nil(nil)
true
"""
defmacro is_nil(term) do
quote do: unquote(term) == nil
end
@doc """
A convenience macro that checks if the right side (an expression)
matches the left side (a pattern).
## Examples
iex> match?(1, 1)
true
iex> match?(1, 2)
false
iex> match?({1, _}, {1, 2})
true
Match can also be used to filter or find a value in an enumerable:
list = [{:a, 1}, {:b, 2}, {:a, 3}]
Enum.filter list, &match?({:a, _}, &1)
Guard clauses can also be given to the match:
list = [{:a, 1}, {:b, 2}, {:a, 3}]
Enum.filter list, &match?({:a, x} when x < 2, &1)
However, variables assigned in the match will not be available
outside of the function call:
iex> match?(x, 1)
true
iex> binding([:x]) == []
true
"""
defmacro match?(pattern, expr)
# Special case underscore since it always matches
defmacro match?({:_, _, atom}, _right) when is_atom(atom) do
true
end
defmacro match?(left, right) do
quote do
case unquote(right) do
unquote(left) ->
true
_ ->
false
end
end
end
@doc """
Read and write attributes of the current module.
The canonical example for attributes is annotating that a module
implements the OTP behaviour called `gen_server`:
defmodule MyServer do
@behaviour :gen_server
# ... callbacks ...
end
By default Elixir supports all Erlang module attributes, but any developer
can also add custom attributes:
defmodule MyServer do
@my_data 13
IO.inspect @my_data #=> 13
end
Unlike Erlang, such attributes are not stored in the module by
default since it is common in Elixir to use such attributes to store
temporary data. A developer can configure an attribute to behave closer
to Erlang by calling `Module.register_attribute/3`.
Finally, notice that attributes can also be read inside functions:
defmodule MyServer do
@my_data 11
def first_data, do: @my_data
@my_data 13
def second_data, do: @my_data
end
MyServer.first_data #=> 11
MyServer.second_data #=> 13
It is important to note that reading an attribute takes a snapshot of
its current value. In other words, the value is read at compilation
time and not at runtime. Check the module `Module` for other functions
to manipulate module attributes.
"""
defmacro @(expr)
# Typespecs attributes are special cased by the compiler so far
defmacro @({name, _, args}) do
# Check for Macro as it is compiled later than Module
case bootstraped?(Module) do
false -> nil
true ->
assert_module_scope(__CALLER__, :@, 1)
function? = __CALLER__.function != nil
case is_list(args) and length(args) == 1 and typespec(name) do
false ->
do_at(args, name, function?, __CALLER__)
macro ->
case bootstraped?(Kernel.Typespec) do
false -> nil
true -> quote do: Kernel.Typespec.unquote(macro)(unquote(hd(args)))
end
end
end
end
# @attribute value
defp do_at([arg], name, function?, env) do
case function? do
true ->
raise ArgumentError, "cannot set attribute @#{name} inside function/macro"
false ->
case name do
:behavior ->
:elixir_errors.warn warn_info(env_stacktrace(env)),
"@behavior attribute is not supported, please use @behaviour instead"
_ ->
:ok
end
quote do: Module.put_attribute(__MODULE__, unquote(name), unquote(arg))
end
end
# @attribute or @attribute()
defp do_at(args, name, function?, env) when is_atom(args) or args == [] do
stack = env_stacktrace(env)
case function? do
true ->
attr = Module.get_attribute(env.module, name, stack)
try do
:elixir_quote.escape(attr, false)
rescue
e in [ArgumentError] ->
raise ArgumentError, "cannot inject attribute @#{name} into function/macro because " <> Exception.message(e)
else
{val, _} -> val
end
false ->
escaped = case stack do
[] -> []
_ -> Macro.escape(stack)
end
quote do: Module.get_attribute(__MODULE__, unquote(name), unquote(escaped))
end
end
# All other cases
defp do_at(args, name, _function?, _env) do
raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}"
end
defp warn_info([entry|_]) do
opts = :erlang.element(tuple_size(entry), entry)
Exception.format_file_line(Keyword.get(opts, :file), Keyword.get(opts, :line)) <> " "
end
defp warn_info([]) do
""
end
defp typespec(:type), do: :deftype
defp typespec(:typep), do: :deftypep
defp typespec(:opaque), do: :defopaque
defp typespec(:spec), do: :defspec
defp typespec(:callback), do: :defcallback
defp typespec(_), do: false
@doc """
Returns the binding for the given context as a keyword list.
The variable name is the key and the variable value is the value.
## Examples
iex> x = 1
iex> binding()
[x: 1]
iex> x = 2
iex> binding()
[x: 2]
iex> binding(:foo)
[]
iex> var!(x, :foo) = 1
1
iex> binding(:foo)
[x: 1]
"""
defmacro binding(context \\ nil) do
in_match? = Macro.Env.in_match?(__CALLER__)
for {v, c} <- __CALLER__.vars, c == context do
{v, wrap_binding(in_match?, {v, [], c})}
end
end
defp wrap_binding(true, var) do
quote do: ^(unquote(var))
end
defp wrap_binding(_, var) do
var
end
@doc """
Provides an `if` macro. This macro expects the first argument to
be a condition and the rest are keyword arguments.
## One-liner examples
if(foo, do: bar)
In the example above, `bar` will be returned if `foo` evaluates to
`true` (i.e. it is neither `false` nor `nil`). Otherwise, `nil` will be returned.
An `else` option can be given to specify the opposite:
if(foo, do: bar, else: baz)
## Blocks examples
Elixir also allows you to pass a block to the `if` macro. The first
example above would be translated to:
if foo do
bar
end
Notice that `do/end` becomes delimiters. The second example would
then translate to:
if foo do
bar
else
baz
end
If you want to compare more than two clauses, you can use the `cond/1`
macro.
"""
defmacro if(condition, clauses) do
do_clause = Keyword.get(clauses, :do, nil)
else_clause = Keyword.get(clauses, :else, nil)
optimize_boolean(quote do
case unquote(condition) do
x when x in [false, nil] -> unquote(else_clause)
_ -> unquote(do_clause)
end
end)
end
@doc """
Evaluates and returns the do-block passed in as a second argument
unless clause evaluates to true.
Returns nil otherwise.
See also `if`.
## Examples
iex> unless(Enum.empty?([]), do: "Hello")
nil
iex> unless(Enum.empty?([1,2,3]), do: "Hello")
"Hello"
"""
defmacro unless(clause, options) do
do_clause = Keyword.get(options, :do, nil)
else_clause = Keyword.get(options, :else, nil)
quote do
if(unquote(clause), do: unquote(else_clause), else: unquote(do_clause))
end
end
@doc """
Allows you to destructure two lists, assigning each term in the right to the
matching term in the left. Unlike pattern matching via `=`, if the sizes of
the left and right lists don't match, destructuring simply stops instead of
raising an error.
## Examples
iex> destructure([x, y, z], [1, 2, 3, 4, 5])
iex> {x, y, z}
{1, 2, 3}
Notice in the example above, even though the right
size has more entries than the left, destructuring works
fine. If the right size is smaller, the remaining items
are simply assigned to nil:
iex> destructure([x, y, z], [1])
iex> {x, y, z}
{1, nil, nil}
The left side supports any expression you would use
on the left side of a match:
x = 1
destructure([^x, y, z], [1, 2, 3])
The example above will only work if x matches
the first value from the right side. Otherwise,
it will raise a CaseClauseError.
"""
defmacro destructure(left, right) when is_list(left) do
Enum.reduce left, right, fn item, acc ->
{:case, meta, args} =
quote do
case unquote(acc) do
[unquote(item)|t] ->
t
other when other == [] or other == nil ->
unquote(item) = nil
end
end
{:case, [{:export_head,true}|meta], args}
end
end
@doc """
Returns a range with the specified start and end.
Includes both ends.
## Examples
iex> 0 in 1..3
false
iex> 1 in 1..3
true
iex> 2 in 1..3
true
iex> 3 in 1..3
true
"""
defmacro first .. last do
{:%{}, [], [__struct__: Elixir.Range, first: first, last: last]}
end
@doc """
Provides a short-circuit operator that evaluates and returns
the second expression only if the first one evaluates to true
(i.e. it is not nil nor false). Returns the first expression
otherwise.
## Examples
iex> Enum.empty?([]) && Enum.empty?([])
true
iex> List.first([]) && true
nil
iex> Enum.empty?([]) && List.first([1])
1
iex> false && throw(:bad)
false
Notice that, unlike Erlang's `and` operator,
this operator accepts any expression as an argument,
not only booleans, however it is not allowed in guards.
"""
defmacro left && right do
quote do
case unquote(left) do
x when x in [false, nil] ->
x
_ ->
unquote(right)
end
end
end
@doc """
Provides a short-circuit operator that evaluates and returns the second
expression only if the first one does not evaluate to true (i.e. it
is either nil or false). Returns the first expression otherwise.
## Examples
iex> Enum.empty?([1]) || Enum.empty?([1])
false
iex> List.first([]) || true
true
iex> Enum.empty?([1]) || 1
1
iex> Enum.empty?([]) || throw(:bad)
true
Notice that, unlike Erlang's `or` operator,
this operator accepts any expression as an argument,
not only booleans, however it is not allowed in guards.
"""
defmacro left || right do
quote do
case unquote(left) do
x when x in [false, nil] ->
unquote(right)
x ->
x
end
end
end
@doc """
`|>` is the pipe operator.
This operator introduces the expression on the left as
the first argument to the function call on the right.
## Examples
iex> [1, [2], 3] |> List.flatten()
[1, 2, 3]
The example above is the same as calling `List.flatten([1, [2], 3])`,
i.e. the argument on the left side of `|>` is introduced as the first
argument of the function call on the right side.
This pattern is mostly useful when there is a desire to execute
a bunch of operations, resembling a pipeline:
iex> [1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)
[2, 4, 6]
The example above will pass the list to `List.flatten/1`, then get
the flattened list and pass to `Enum.map/2`, which will multiply
each entry in the list per two.
In other words, the expression above simply translates to:
Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)
Beware of operator precedence when using the pipe operator.
For example, the following expression:
String.graphemes "Hello" |> Enum.reverse
Translates to:
String.graphemes("Hello" |> Enum.reverse)
Which will result in an error as Enumerable protocol is not defined
for binaries. Adding explicit parenthesis resolves the ambiguity:
String.graphemes("Hello") |> Enum.reverse
Or, even better:
"Hello" |> String.graphemes |> Enum.reverse
"""
defmacro left |> right do
[{h, _}|t] = Macro.unpipe({:|>, [], [left, right]})
:lists.foldl fn {x, pos}, acc -> Macro.pipe(acc, x, pos) end, h, t
end
@doc """
Returns true if the `module` is loaded and contains a
public `function` with the given `arity`, otherwise false.
Notice that this function does not load the module in case
it is not loaded. Check `Code.ensure_loaded/1` for more
information.
"""
@spec function_exported?(atom | tuple, atom, arity) :: boolean
def function_exported?(module, function, arity) do
:erlang.function_exported(module, function, arity)
end
@doc """
Returns true if the `module` is loaded and contains a
public `macro` with the given `arity`, otherwise false.
Notice that this function does not load the module in case
it is not loaded. Check `Code.ensure_loaded/1` for more
information.
"""
@spec macro_exported?(atom, atom, integer) :: boolean
def macro_exported?(module, macro, arity) do
case :code.is_loaded(module) do
{:file, _} -> :lists.member({macro, arity}, module.__info__(:macros))
_ -> false
end
end
@doc """
Access the given element using the qualifier according
to the `Access` protocol. All calls in the form `foo[bar]`
are translated to `access(foo, bar)`.
The usage of this protocol is to access a raw value in a
keyword list.
iex> sample = [a: 1, b: 2, c: 3]
iex> sample[:b]
2
"""
@doc """
Checks if the element on the left side is member of the
collection on the right side.
## Examples
iex> x = 1
iex> x in [1, 2, 3]
true
This macro simply translates the expression above to:
Enum.member?([1,2,3], x)
## Guards
The `in` operator can be used on guard clauses as long as the
right side is a range or a list. Elixir will then expand the
operator to a valid guard expression. For example:
when x in [1,2,3]
Translates to:
when x === 1 or x === 2 or x === 3
When using ranges:
when x in 1..3
Translates to:
when x >= 1 and x <= 3
"""
defmacro left in right do
cache = (__CALLER__.context == nil)
right = case bootstraped?(Macro) do
true -> Macro.expand(right, __CALLER__)
false -> right
end
case right do
_ when cache ->
quote do: Elixir.Enum.member?(unquote(right), unquote(left))
[] ->
false
[h|t] ->
:lists.foldr(fn x, acc ->
quote do
unquote(comp(left, x)) or unquote(acc)
end
end, comp(left, h), t)
{:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} ->
in_range(left, Macro.expand(first, __CALLER__), Macro.expand(last, __CALLER__))
_ ->
raise ArgumentError, <<"invalid args for operator in, it expects a compile time list ",
"or range on the right side when used in guard expressions, got: ",
Macro.to_string(right) :: binary>>
end
end
defp in_range(left, first, last) do
case opt_in?(first) and opt_in?(last) do
true ->
case first <= last do
true -> increasing_compare(left, first, last)
false -> decreasing_compare(left, first, last)
end
false ->
quote do
(:erlang."=<"(unquote(first), unquote(last)) and
unquote(increasing_compare(left, first, last)))
or
(:erlang."<"(unquote(last), unquote(first)) and
unquote(decreasing_compare(left, first, last)))
end
end
end
defp opt_in?(x), do: is_integer(x) or is_float(x) or is_atom(x)
defp comp(left, right) do
quote(do: :erlang."=:="(unquote(left), unquote(right)))
end
defp increasing_compare(var, first, last) do
quote do
:erlang.">="(unquote(var), unquote(first)) and
:erlang."=<"(unquote(var), unquote(last))
end
end
defp decreasing_compare(var, first, last) do
quote do
:erlang."=<"(unquote(var), unquote(first)) and
:erlang.">="(unquote(var), unquote(last))
end
end
@doc """
When used inside quoting, marks that the variable should
not be hygienized. The argument can be either a variable
unquoted or in standard tuple form `{name, meta, context}`.
Check `Kernel.SpecialForms.quote/2` for more information.
"""
defmacro var!(var, context \\ nil)
defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do
do_var!(name, meta, context, __CALLER__)
end
defmacro var!(x, _context) do
raise ArgumentError, "expected a var to be given to var!, got: #{Macro.to_string(x)}"
end
defp do_var!(name, meta, context, env) do
# Remove counter and force them to be vars
meta = :lists.keydelete(:counter, 1, meta)
meta = :lists.keystore(:var, 1, meta, {:var, true})
case Macro.expand(context, env) do
x when is_atom(x) ->
{name, meta, x}
x ->
raise ArgumentError, "expected var! context to expand to an atom, got: #{Macro.to_string(x)}"
end
end
@doc """
When used inside quoting, marks that the alias should not
be hygienezed. This means the alias will be expanded when
the macro is expanded.
Check `Kernel.SpecialForms.quote/2` for more information.
"""
defmacro alias!(alias)
defmacro alias!(alias) when is_atom(alias) do
alias
end
defmacro alias!({:__aliases__, meta, args}) do
# Simply remove the alias metadata from the node
# so it does not affect expansion.
{:__aliases__, :lists.keydelete(:alias, 1, meta), args}
end
## Definitions implemented in Elixir
@doc ~S"""
Defines a module given by name with the given contents.
It returns the module name, the module binary and the
block contents result.
## Examples
iex> defmodule Foo do
...> def bar, do: :baz
...> end
iex> Foo.bar
:baz
## Nesting
Nesting a module inside another module affects its name:
defmodule Foo do
defmodule Bar do
end
end
In the example above, two modules `Foo` and `Foo.Bar` are created.
When nesting, Elixir automatically creates an alias, allowing the
second module `Foo.Bar` to be accessed as `Bar` in the same lexical
scope.
This means that, if the module `Bar` is moved to another file,
the references to `Bar` needs to be updated or an alias needs to
be explicitly set with the help of `Kernel.SpecialForms.alias/2`.
## Dynamic names
Elixir module names can be dynamically generated. This is very
useful for macros. For instance, one could write:
defmodule String.to_atom("Foo#{1}") do
# contents ...
end
Elixir will accept any module name as long as the expression
returns an atom. Note that, when a dynamic name is used, Elixir
won't nest the name under the current module nor automatically
set up an alias.
"""
defmacro defmodule(alias, do: block) do
env = __CALLER__
boot? = bootstraped?(Macro)
expanded =
case boot? do
true -> Macro.expand(alias, env)
false -> alias
end
{expanded, with_alias} =
case boot? and is_atom(expanded) do
true ->
# Expand the module considering the current environment/nesting
full = expand_module(alias, expanded, env)
# Generate the alias for this module definition
{new, old} = module_nesting(env.module, full)
meta = [defined: full, context: env.module] ++ alias_meta(alias)
{full, {:alias, meta, [old, [as: new, warn: false]]}}
false ->
{expanded, nil}
end
{escaped, _} = :elixir_quote.escape(block, false)
module_vars = module_vars(env.vars, 0)
quote do
unquote(with_alias)
:elixir_module.compile(unquote(expanded), unquote(escaped),
unquote(module_vars), __ENV__)
end
end
defp alias_meta({:__aliases__, meta, _}), do: meta
defp alias_meta(_), do: []
# defmodule :foo
defp expand_module(raw, _module, _env) when is_atom(raw),
do: raw
# defmodule Elixir.Alias
defp expand_module({:__aliases__, _, [:Elixir|t]}, module, _env) when t != [],
do: module
# defmodule Alias in root
defp expand_module({:__aliases__, _, _}, module, %{module: nil}),
do: module
# defmodule Alias nested
defp expand_module({:__aliases__, _, t}, _module, env),
do: :elixir_aliases.concat([env.module|t])
# defmodule _
defp expand_module(_raw, module, env),
do: :elixir_aliases.concat([env.module, module])
# quote vars to be injected into the module definition
defp module_vars([{key, kind}|vars], counter) do
var =
case is_atom(kind) do
true -> {key, [], kind}
false -> {key, [counter: kind], nil}
end
under = String.to_atom(<<"_@", :erlang.integer_to_binary(counter)::binary>>)
args = [key, kind, under, var]
[{:{}, [], args}|module_vars(vars, counter+1)]
end
defp module_vars([], _counter) do
[]
end
# Gets two modules names and return an alias
# which can be passed down to the alias directive
# and it will create a proper shortcut representing
# the given nesting.
#
# Examples:
#
# module_nesting('Elixir.Foo.Bar', 'Elixir.Foo.Bar.Baz.Bat')
# {'Elixir.Baz', 'Elixir.Foo.Bar.Baz'}
#
# In case there is no nesting/no module:
#
# module_nesting(nil, 'Elixir.Foo.Bar.Baz.Bat')
# {false, 'Elixir.Foo.Bar.Baz.Bat'}
#
defp module_nesting(nil, full),
do: {false, full}
defp module_nesting(prefix, full) do
case split_module(prefix) do
[] -> {false, full}
prefix -> module_nesting(prefix, split_module(full), [], full)
end
end
defp module_nesting([x|t1], [x|t2], acc, full),
do: module_nesting(t1, t2, [x|acc], full)
defp module_nesting([], [h|_], acc, _full),
do: {String.to_atom(<<"Elixir.", h::binary>>),
:elixir_aliases.concat(:lists.reverse([h|acc]))}
defp module_nesting(_, _, _acc, full),
do: {false, full}
defp split_module(atom) do
case :binary.split(Atom.to_string(atom), ".", [:global]) do
["Elixir"|t] -> t
_ -> []
end
end
@doc """
Defines a function with the given name and contents.
## Examples
defmodule Foo do
def bar, do: :baz
end
Foo.bar #=> :baz
A function that expects arguments can be defined as follow:
defmodule Foo do
def sum(a, b) do
a + b
end
end
In the example above, we defined a function `sum` that receives
two arguments and sums them.
"""
defmacro def(call, expr \\ nil) do
define(:def, call, expr, __CALLER__)
end
@doc """
Defines a function that is private. Private functions are
only accessible from within the module in which they are defined.
Check `def/2` for more information
## Examples
defmodule Foo do
def bar do
sum(1, 2)
end
defp sum(a, b), do: a + b
end
In the example above, `sum` is private and accessing it
through `Foo.sum` will raise an error.
"""
defmacro defp(call, expr \\ nil) do
define(:defp, call, expr, __CALLER__)
end
@doc """
Defines a macro with the given name and contents.
## Examples
defmodule MyLogic do
defmacro unless(expr, opts) do
quote do
if !unquote(expr), unquote(opts)
end
end
end
require MyLogic
MyLogic.unless false do
IO.puts "It works"
end
"""
defmacro defmacro(call, expr \\ nil) do
define(:defmacro, call, expr, __CALLER__)
end
@doc """
Defines a macro that is private. Private macros are
only accessible from the same module in which they are defined.
Check `defmacro/2` for more information
"""
defmacro defmacrop(call, expr \\ nil) do
define(:defmacrop, call, expr, __CALLER__)
end
defp define(kind, call, expr, env) do
assert_module_scope(env, kind, 2)
assert_no_function_scope(env, kind, 2)
line = env.line
{call, uc} = :elixir_quote.escape(call, true)
{expr, ue} = :elixir_quote.escape(expr, true)
# Do not check clauses if any expression was unquoted
check_clauses = not(ue or uc)
pos = :elixir_locals.cache_env(env)
quote do
:elixir_def.store_definition(unquote(line), unquote(kind), unquote(check_clauses),
unquote(call), unquote(expr), unquote(pos))
end
end
@doc """
Defines a struct for the current module.
A struct is a tagged map that allows developers to provide
default values for keys, tags to be used in polymorphic
dispatches and compile time assertions.
To define a struct, a developer needs to only define
a function named `__struct__/0` that returns a map with the
structs field. This macro is a convenience for defining such
function, with the addition of a type `t` and deriving
conveniences.
For more information about structs, please check
`Kernel.SpecialForms.%/2`.
## Examples
defmodule User do
defstruct name: nil, age: nil
end
Struct fields are evaluated at definition time, which allows
them to be dynamic. In the example below, `10 + 11` will be
evaluated at compilation time and the age field will be stored
with value `21`:
defmodule User do
defstruct name: nil, age: 10 + 11
end
## Deriving
Although structs are maps, by default structs do not implement
any of the protocols implemented for maps. For example, if you
attempt to use the access protocol with the User struct, it
will lead to an error:
%User{}[:age]
** (Protocol.UndefinedError) protocol Access not implemented for %User{...}
However, `defstruct/1` allows implementation for protocols to
derived by defining a `@derive` attribute as a list before `defstruct/1`
is invoked:
defmodule User do
@derive [Access]
defstruct name: nil, age: 10 + 11
end
%User{}[:age] #=> 21
For each protocol given to `@derive`, Elixir will assert there is an
implementation of that protocol for maps and check if the map
implementation defines a `__deriving__/3` callback. If so, the callback
is invoked, otherwise an implementation that simply points to the map
one is automatically derived.
## Types
It is recommended to define types for structs, by convention this type
is called `t`. To define a struct in a type the struct literal syntax
is used:
defmodule User do
defstruct name: "john", age: 25
@type t :: %User{name: String.t, age: integer}
end
It is recommended to only use the struct syntax when defining the struct's
type. When referring to another struct use `User.t`, not `%User{}`. Fields
in the struct not included in the type defaults to `term`.
Private structs that are not used outside its module should use the private
type attribute `@typep`. Public structs whose internal structure is private
to the local module (you are not allowed to pattern match it or directly
access fields) should use the `@opaque` attribute. Structs whose internal
structure is public should use `@type`.
"""
defmacro defstruct(fields) do
quote bind_quoted: [fields: fields] do
fields = :lists.map(fn
{key, val} when is_atom(key) ->
try do
Macro.escape(val)
rescue
e in [ArgumentError] ->
raise ArgumentError, "invalid value for struct field #{key}, " <> Exception.message(e)
else
_ -> {key, val}
end
key when is_atom(key) ->
{key, nil}
other ->
raise ArgumentError, "struct field names must be atoms, got: #{inspect other}"
end, fields)
@struct :maps.put(:__struct__, __MODULE__, :maps.from_list(fields))
case Module.get_attribute(__MODULE__, :derive) do
[] -> :ok
derive -> Protocol.__derive__(derive, __MODULE__, __ENV__)
end
@spec __struct__() :: %__MODULE__{}
def __struct__() do
@struct
end
fields
end
end
@doc ~S"""
Defines an exception.
Exceptions are structs backed by a module that implements
the Exception behaviour. The Exception behaviour requires
two functions to be implemented:
* `exception/1` - that receives the arguments given to `raise/2`
and returns the exception struct. The default implementation
accepts a set of keyword arguments that is merged into the
struct.
* `message/1` - receives the exception struct and must return its
message. Most commonly exceptions have a message field which
by default is accessed by this function. However, if your exception
does not have a message field, this function must be explicitly
implemented.
Since exceptions are structs, all the API supported by `defstruct/1`
is also available in `defexception/1`.
## Raising exceptions
The most common way to raise an exception is via the `raise/2`
function:
defmodule MyAppError do
defexception [:message]
end
value = [:hello]
raise MyAppError,
message: "did not get what was expected, got: #{inspect value}"
In many cases it is more convenient to pass the expected value to
`raise` and generate the message in the `exception/1` callback:
defmodule MyAppError do
defexception [:message]
def exception(value) do
msg = "did not get what was expected, got: #{inspect value}"
%MyAppError{message: msg}
end
end
raise MyAppError, value
The example above is the preferred mechanism for customizing
exception messages.
"""
defmacro defexception(fields) do
fields = case is_list(fields) do
true -> [{:__exception__, true}|fields]
false -> quote(do: [{:__exception__, true}] ++ unquote(fields))
end
quote do
@behaviour Exception
fields = defstruct unquote(fields)
@spec exception(Keyword.t) :: Exception.t
def exception(args) when is_list(args) do
Kernel.struct(__struct__, args)
end
defoverridable exception: 1
if Keyword.has_key?(fields, :message) do
@spec message(Exception.t) :: String.t
def message(exception) do
exception.message
end
defoverridable message: 1
end
end
end
@doc """
Defines a protocol.
A protocol specifies an API that should be defined by its
implementations.
## Examples
In Elixir, only `false` and `nil` are considered falsy values.
Everything else evaluates to true in `if` clauses. Depending
on the application, it may be important to specify a `blank?`
protocol that returns a boolean for other data types that should
be considered `blank?`. For instance, an empty list or an empty
binary could be considered blanks.
We could implement this protocol as follow:
defprotocol Blank do
@doc "Returns true if data is considered blank/empty"
def blank?(data)
end
Now that the protocol is defined, we can implement it. We need
to implement the protocol for each Elixir type. For example:
# Integers are never blank
defimpl Blank, for: Integer do
def blank?(number), do: false
end
# Just empty list is blank
defimpl Blank, for: List do
def blank?([]), do: true
def blank?(_), do: false
end
# Just the atoms false and nil are blank
defimpl Blank, for: Atom do
def blank?(false), do: true
def blank?(nil), do: true
def blank?(_), do: false
end
And we would have to define the implementation for all types.
The supported types available are:
* Structs (see below)
* `Tuple`
* `Atom`
* `List`
* `BitString`
* `Integer`
* `Float`
* `Function`
* `PID`
* `Map`
* `Port`
* `Reference`
* `Any` (see below)
## Protocols + Structs
The real benefit of protocols comes when mixed with structs.
For instance, Elixir ships with many data types implemented as
structs, like `HashDict` and `HashSet`. We can implement the
`Blank` protocol for those types as well:
defimpl Blank, for: [HashDict, HashSet] do
def blank?(enum_like), do: Enum.empty?(enum_like)
end
If a protocol is not found for a given type, it will fallback to
`Any`.
## Fallback to any
In some cases, it may be convenient to provide a default
implementation for all types. This can be achieved by
setting `@fallback_to_any` to `true` in the protocol
definition:
defprotocol Blank do
@fallback_to_any true
def blank?(data)
end
Which can now be implemented as:
defimpl Blank, for: Any do
def blank?(_), do: true
end
One may wonder why such fallback is not true by default.
It is two-fold: first, the majority of protocols cannot
implement an action in a generic way for all types. In fact,
providing a default implementation may be harmful, because users
may rely on the default implementation instead of providing a
specialized one.
Second, falling back to `Any` adds an extra lookup to all types,
which is unnecessary overhead unless an implementation for Any is
required.
## Types
Defining a protocol automatically defines a type named `t`, which
can be used as:
@spec present?(Blank.t) :: boolean
def present?(blank) do
not Blank.blank?(blank)
end
The `@spec` above expresses that all types allowed to implement the
given protocol are valid argument types for the given function.
## Reflection
Any protocol module contains three extra functions:
* `__protocol__/1` - returns the protocol name when `:name` is given, and a
keyword list with the protocol functions when `:functions` is given
* `impl_for/1` - receives a structure and returns the module that
implements the protocol for the structure, `nil` otherwise
* `impl_for!/1` - same as above but raises an error if an implementation is
not found
## Consolidation
In order to cope with code loading in development, protocols in
Elixir provide a slow implementation of protocol dispatching specific
to development.
In order to speed up dispatching in production environments, where
all implementations are known up-front, Elixir provides a feature
called protocol consolidation. For this reason, all protocols are
compiled with `debug_info` set to true, regardless of the option
set by `elixirc` compiler. The debug info though may be removed
after consolidation.
For more information on how to apply protocol consolidation to
a given project, please check the functions in the `Protocol`
module or the `mix compile.protocols` task.
"""
defmacro defprotocol(name, do: block) do
Protocol.__protocol__(name, do: block)
end
@doc """
Defines an implementation for the given protocol. See
`defprotocol/2` for examples.
Inside an implementation, the name of the protocol can be accessed
via `@protocol` and the current target as `@for`.
"""
defmacro defimpl(name, opts, do_block \\ []) do
merged = Keyword.merge(opts, do_block)
merged = Keyword.put_new(merged, :for, __CALLER__.module)
Protocol.__impl__(name, merged)
end
@doc """
Makes the given functions in the current module overridable. An overridable
function is lazily defined, allowing a developer to customize it.
## Example
defmodule DefaultMod do
defmacro __using__(_opts) do
quote do
def test(x, y) do
x + y
end
defoverridable [test: 2]
end
end
end
defmodule InheritMod do
use DefaultMod
def test(x, y) do
x * y + super(x, y)
end
end
As seen as in the example `super` can be used to call the default
implementation.
"""
defmacro defoverridable(tuples) do
quote do
Module.make_overridable(__MODULE__, unquote(tuples))
end
end
@doc """
`use` is a simple mechanism for using a given module into
the current context.
## Examples
For example, in order to write tests using the ExUnit framework,
a developer should use the `ExUnit.Case` module:
defmodule AssertionTest do
use ExUnit.Case, async: true
test "always pass" do
assert true
end
end
By calling `use`, a hook called `__using__` will be invoked in
`ExUnit.Case` which will then do the proper setup.
Simply put, `use` is simply a translation to:
defmodule AssertionTest do
require ExUnit.Case
ExUnit.Case.__using__([async: true])
test "always pass" do
assert true
end
end
"""
defmacro use(module, opts \\ []) do
expanded = Macro.expand(module, __CALLER__)
case is_atom(expanded) do
false ->
raise ArgumentError, "invalid arguments for use, expected an atom or alias as argument"
true ->
quote do
require unquote(expanded)
unquote(expanded).__using__(unquote(opts))
end
end
end
@doc """
Defines the given functions in the current module that will
delegate to the given `target`. Functions defined with
`defdelegate` are public and are allowed to be invoked
from external. If you find yourself wishing to define a
delegation as private, you should likely use import
instead.
Delegation only works with functions, delegating to macros
is not supported.
## Options
* `:to` - the expression to delegate to. Any expression
is allowed and its results will be calculated on runtime.
* `:as` - the function to call on the target given in `:to`.
This parameter is optional and defaults to the name being
delegated.
* `:append_first` - if true, when delegated, first argument
passed to the delegate will be relocated to the end of the
arguments when dispatched to the target.
The motivation behind this is because Elixir normalizes
the "handle" as a first argument and some Erlang modules
expect it as last argument.
## Examples
defmodule MyList do
defdelegate reverse(list), to: :lists
defdelegate [reverse(list), map(callback, list)], to: :lists
defdelegate other_reverse(list), to: :lists, as: :reverse
end
MyList.reverse([1, 2, 3])
#=> [3,2,1]
MyList.other_reverse([1, 2, 3])
#=> [3,2,1]
"""
defmacro defdelegate(funs, opts) do
funs = Macro.escape(funs, unquote: true)
quote bind_quoted: [funs: funs, opts: opts] do
target = Keyword.get(opts, :to) ||
raise ArgumentError, "Expected to: to be given as argument"
append_first = Keyword.get(opts, :append_first, false)
for fun <- List.wrap(funs) do
{name, args} =
case Macro.decompose_call(fun) do
{_, _} = pair -> pair
_ -> raise ArgumentError, "invalid syntax in defdelegate #{Macro.to_string(fun)}"
end
actual_args =
case append_first and args != [] do
true -> tl(args) ++ [hd(args)]
false -> args
end
fun = Keyword.get(opts, :as, name)
def unquote(name)(unquote_splicing(args)) do
unquote(target).unquote(fun)(unquote_splicing(actual_args))
end
end
end
end
## Sigils
@doc ~S"""
Handles the sigil ~S. It simply returns a string
without escaping characters and without interpolations.
## Examples
iex> ~S(foo)
"foo"
iex> ~S(f#{o}o)
"f\#{o}o"
"""
defmacro sigil_S(string, []) do
string
end
@doc ~S"""
Handles the sigil ~s. It returns a string as if it was double quoted
string, unescaping characters and replacing interpolations.
## Examples
iex> ~s(foo)
"foo"
iex> ~s(f#{:o}o)
"foo"
iex> ~s(f\#{:o}o)
"f\#{:o}o"
"""
defmacro sigil_s({:<<>>, line, pieces}, []) do
{:<<>>, line, Macro.unescape_tokens(pieces)}
end
@doc ~S"""
Handles the sigil ~C. It simply returns a char list
without escaping characters and without interpolations.
## Examples
iex> ~C(foo)
'foo'
iex> ~C(f#{o}o)
'f\#{o}o'
"""
defmacro sigil_C({:<<>>, _line, [string]}, []) when is_binary(string) do
String.to_char_list(string)
end
@doc ~S"""
Handles the sigil ~c. It returns a char list as if it were a single
quoted string, unescaping characters and replacing interpolations.
## Examples
iex> ~c(foo)
'foo'
iex> ~c(f#{:o}o)
'foo'
iex> ~c(f\#{:o}o)
'f\#{:o}o'
"""
# We can skip the runtime conversion if we are
# creating a binary made solely of series of chars.
defmacro sigil_c({:<<>>, _line, [string]}, []) when is_binary(string) do
String.to_char_list(Macro.unescape_string(string))
end
defmacro sigil_c({:<<>>, line, pieces}, []) do
binary = {:<<>>, line, Macro.unescape_tokens(pieces)}
quote do: String.to_char_list(unquote(binary))
end
@doc """
Handles the sigil ~r. It returns a Regex pattern.
## Examples
iex> Regex.match?(~r(foo), "foo")
true
"""
defmacro sigil_r({:<<>>, _line, [string]}, options) when is_binary(string) do
binary = Macro.unescape_string(string, fn(x) -> Regex.unescape_map(x) end)
regex = Regex.compile!(binary, :binary.list_to_bin(options))
Macro.escape(regex)
end
defmacro sigil_r({:<<>>, line, pieces}, options) do
binary = {:<<>>, line, Macro.unescape_tokens(pieces, fn(x) -> Regex.unescape_map(x) end)}
quote do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))
end
@doc ~S"""
Handles the sigil ~R. It returns a Regex pattern without escaping
nor interpreting interpolations.
## Examples
iex> Regex.match?(~R(f#{1,3}o), "f#o")
true
"""
defmacro sigil_R({:<<>>, _line, [string]}, options) when is_binary(string) do
regex = Regex.compile!(string, :binary.list_to_bin(options))
Macro.escape(regex)
end
@doc ~S"""
Handles the sigil ~w. It returns a list of "words" split by whitespace.
## Modifiers
* `s`: strings (default)
* `a`: atoms
* `c`: char lists
## Examples
iex> ~w(foo #{:bar} baz)
["foo", "bar", "baz"]
iex> ~w(--source test/enum_test.exs)
["--source", "test/enum_test.exs"]
iex> ~w(foo bar baz)a
[:foo, :bar, :baz]
"""
defmacro sigil_w({:<<>>, _line, [string]}, modifiers) when is_binary(string) do
split_words(Macro.unescape_string(string), modifiers)
end
defmacro sigil_w({:<<>>, line, pieces}, modifiers) do
binary = {:<<>>, line, Macro.unescape_tokens(pieces)}
split_words(binary, modifiers)
end
@doc ~S"""
Handles the sigil ~W. It returns a list of "words" split by whitespace
without escaping nor interpreting interpolations.
## Modifiers
* `s`: strings (default)
* `a`: atoms
* `c`: char lists
## Examples
iex> ~W(foo #{bar} baz)
["foo", "\#{bar}", "baz"]
"""
defmacro sigil_W({:<<>>, _line, [string]}, modifiers) when is_binary(string) do
split_words(string, modifiers)
end
defp split_words("", _modifiers), do: []
defp split_words(string, modifiers) do
mod =
case modifiers do
[] -> ?s
[mod] when mod == ?s or mod == ?a or mod == ?c -> mod
_else -> raise ArgumentError, "modifier must be one of: s, a, c"
end
case is_binary(string) do
true ->
case mod do
?s -> String.split(string)
?a -> for p <- String.split(string), do: String.to_atom(p)
?c -> for p <- String.split(string), do: String.to_char_list(p)
end
false ->
case mod do
?s -> quote do: String.split(unquote(string))
?a -> quote do: for(p <- String.split(unquote(string)), do: String.to_atom(p))
?c -> quote do: for(p <- String.split(unquote(string)), do: String.to_char_list(p))
end
end
end
## Shared functions
defp optimize_boolean({:case, meta, args}) do
{:case, [{:optimize_boolean, true}|meta], args}
end
# We need this check only for bootstrap purposes.
# Once Kernel is loaded and we recompile, it is a no-op.
case :code.ensure_loaded(Kernel) do
{:module, _} ->
defp bootstraped?(_), do: true
{:error, _} ->
defp bootstraped?(module), do: :code.ensure_loaded(module) == {:module, module}
end
defp assert_module_scope(env, fun, arity) do
case env.module do
nil -> raise ArgumentError, "cannot invoke #{fun}/#{arity} outside module"
_ -> :ok
end
end
defp assert_no_function_scope(env, fun, arity) do
case env.function do
nil -> :ok
_ -> raise ArgumentError, "cannot invoke #{fun}/#{arity} inside function/macro"
end
end
defp env_stacktrace(env) do
case bootstraped?(Path) do
true -> Macro.Env.stacktrace(env)
false -> []
end
end
end
| 25.290665 | 120 | 0.631816 |
735fcb6bf644d6449476a6b97ebec8e8e36b75ad | 990 | exs | Elixir | elixir/learning-files/part-3/patterns.exs | Cyan101/code-examples | 7f112c716a3deb3b4d21b27590939e9aa71b8448 | [
"MIT"
] | null | null | null | elixir/learning-files/part-3/patterns.exs | Cyan101/code-examples | 7f112c716a3deb3b4d21b27590939e9aa71b8448 | [
"MIT"
] | 1 | 2018-10-05T06:00:01.000Z | 2018-10-05T06:00:01.000Z | elixir/learning-files/part-3/patterns.exs | Cyan101/code-examples | 7f112c716a3deb3b4d21b27590939e9aa71b8448 | [
"MIT"
] | 1 | 2018-10-05T04:43:55.000Z | 2018-10-05T04:43:55.000Z | # `=` is also known as the "match" operator
x = 1
1 = x
#=> 1
2 = x
#=> MatchError
# This is because both sides do not equal the same value (1)
# Pattern Matching
{a, b, c} = {:hello, "world", 42}
IO.puts a
#=> :hello
IO.puts b
#=> "world"
{a, b, c} = {:hello, "world"}
#=> MatchError
# This is because both sides do not have the same size
{a, b, c} = [:hello, "world", 42]
#=> MatchError
# This is because they are different data types
{:ok, result} = {:ok, 13}
# This will limit matching to when the right-hand side starts with `:ok`
{:ok, result} = {:error, :oops}
#=> MatchError
[a, b, c] = [1, 2, 3]
IO.puts a
#=> 1
# Pattern Matching works on lists
[head | tail] = [1, 2, 3]
IO.puts head
#=> 1
IO.puts tail
#=> [2,3]
list = [1, 2, 3]
IO.puts [0 | list]
#=> [0,1,2,3]
# Pattern matching allows developers to easily destructure data types such as tuples and lists.
# It is one of the foundations of recursion in Elixir and applies to other types as well, like maps and binaries.
| 22 | 113 | 0.638384 |
735fdecad174edf8451318cf0389b4cfa01e9e2c | 371 | ex | Elixir | lib/inmana.ex | ricktrovato/Trail_Elixir-Phoenix | 2cfc86a88a3992fbcea0b3905300f6727572e7a3 | [
"MIT"
] | 14 | 2021-04-26T14:19:28.000Z | 2021-09-12T03:29:42.000Z | lib/inmana.ex | israel206/InmanaIsrael | bc93ddb3ca23f3188f89ef012e463fcacc4e9777 | [
"MIT"
] | null | null | null | lib/inmana.ex | israel206/InmanaIsrael | bc93ddb3ca23f3188f89ef012e463fcacc4e9777 | [
"MIT"
] | 6 | 2021-04-27T12:41:16.000Z | 2021-07-02T04:11:53.000Z | defmodule Inmana do
alias Inmana.Restaurants.Create, as: RestaurantCreate
alias Inmana.Supplies.Create, as: SupplyCreate
alias Inmana.Supplies.Get, as: SupplyGet
defdelegate create_restaurant(params), to: RestaurantCreate, as: :call
defdelegate create_supply(params), to: SupplyCreate, as: :call
defdelegate get_supply(params), to: SupplyGet, as: :call
end
| 33.727273 | 72 | 0.781671 |
735fe11f353adc3b073a726e434747d98af56542 | 786 | ex | Elixir | joshcrews+elixir/apps/cqrs_bank/lib/cqrs_bank/application.ex | NashFP/cqrs-bank | 6071db4a0c5ec681554aea8bebe783310c5d1525 | [
"MIT"
] | 7 | 2017-05-17T00:36:50.000Z | 2021-11-02T03:02:03.000Z | joshcrews+elixir/apps/cqrs_bank/lib/cqrs_bank/application.ex | NashFP/cqrs-bank | 6071db4a0c5ec681554aea8bebe783310c5d1525 | [
"MIT"
] | 3 | 2017-05-17T00:31:28.000Z | 2017-05-18T04:50:37.000Z | joshcrews+elixir/apps/cqrs_bank/lib/cqrs_bank/application.ex | NashFP/cqrs-bank | 6071db4a0c5ec681554aea8bebe783310c5d1525 | [
"MIT"
] | 5 | 2017-05-16T23:13:19.000Z | 2021-12-02T06:45:25.000Z | defmodule CqrsBank.Application do
# See http://elixir-lang.org/docs/stable/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
import Supervisor.Spec, warn: false
# Define workers and child supervisors to be supervised
children = [
# Starts a worker by calling: CqrsBank.Worker.start_link(arg1, arg2, arg3)
worker(CqrsBank.EventHistoryServer, []),
worker(CqrsBank.EventHandler, []),
worker(CqrsBank.ReadServer, []),
]
# See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: CqrsBank.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 30.230769 | 80 | 0.708651 |
735ffea3f11f05028e5fc504d472b2f8fcea5226 | 289 | exs | Elixir | www/priv/repo/migrations/20161219220300_create_language_history.exs | Nagasaki45/krihelinator | 243bfe476b8128dc2f0fcd913bebd8cf20b7deb6 | [
"MIT"
] | 47 | 2016-07-17T08:49:36.000Z | 2020-11-06T14:12:15.000Z | www/priv/repo/migrations/20161219220300_create_language_history.exs | Nagasaki45/krihelinator | 243bfe476b8128dc2f0fcd913bebd8cf20b7deb6 | [
"MIT"
] | 181 | 2016-07-11T13:20:40.000Z | 2019-10-22T14:43:40.000Z | www/priv/repo/migrations/20161219220300_create_language_history.exs | Nagasaki45/krihelinator | 243bfe476b8128dc2f0fcd913bebd8cf20b7deb6 | [
"MIT"
] | 2 | 2017-02-25T16:19:09.000Z | 2017-12-24T20:22:32.000Z | defmodule Krihelinator.Repo.Migrations.CreateLanguageHistory do
use Ecto.Migration
def change do
create table(:languages_history) do
add :name, :string
add :krihelimeter, :integer
add :num_of_repos, :integer
add :timestamp, :utc_datetime
end
end
end
| 22.230769 | 63 | 0.709343 |
73601088569412212f8971c4d157007c167c9ed1 | 934 | ex | Elixir | learning/redfour/physics/lib/converter.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | 2 | 2020-01-20T20:15:20.000Z | 2020-02-27T11:08:42.000Z | learning/redfour/physics/lib/converter.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | learning/redfour/physics/lib/converter.ex | Mdlkxzmcp/various_elixir | c87527b7118a0c74a042073c04d2228025888ddf | [
"MIT"
] | null | null | null | defmodule Converter do
def seconds_to_hours(val) when is_integer(val) or is_float(val) do
(val / 3600) |> to_nearest_tenth
end
def to_nearest_tenth(val) do
round_to(val, 1)
end
def to_km(val) do
val / 1000
end
def to_meters(val) do
val * 1000
end
def to_light_seconds(arg), do: to_light_seconds(arg, precision: 5)
def to_light_seconds({unit, val}, precision: precision) do
light_seconds =
case unit do
:miles -> from_miles(val)
:meters -> from_meters(val)
:feet -> from_feet(val)
:inches -> from_inches(val)
end
light_seconds |> round_to(precision)
end
defp from_miles(val), do: val * 5.36819e-6
defp from_meters(val), do: val * 3.335638620368e-9
defp from_feet(val), do: val * 1.016702651488166404e-9
defp from_inches(val), do: val * 8.472522095734715723e-11
defp round_to(val, precision), do: Float.round(val, precision)
end
| 24.578947 | 68 | 0.671306 |
7360138b5b076cecfa0b769a1c3ec777107d9eae | 3,877 | ex | Elixir | lib/api/base.ex | MitjaBezensek/pinterex | 2c278212f17227d64c7402e65f0dad6563dea49f | [
"MIT"
] | 1 | 2018-01-29T17:52:47.000Z | 2018-01-29T17:52:47.000Z | lib/api/base.ex | MitjaBezensek/pinterex | 2c278212f17227d64c7402e65f0dad6563dea49f | [
"MIT"
] | null | null | null | lib/api/base.ex | MitjaBezensek/pinterex | 2c278212f17227d64c7402e65f0dad6563dea49f | [
"MIT"
] | null | null | null | defmodule Pinterex.Api.Base do
@moduledoc """
The module contains all the logic that does the actual calls to
the Pinterest API
"""
use Tesla
plug Tesla.Middleware.BaseUrl, "https://api.pinterest.com/v1/"
plug Tesla.Middleware.Query, [access_token: key]
plug Tesla.Middleware.JSON
#plug Tesla.Middleware.DebugLogger
defp key do
Application.get_env(:pinterest, :key) ||
System.get_env("PINTEREST_KEY")
end
@doc """
This is the main function that does get requests.
## Parameters
- :get: it only matches get requests
- path: the path of the resource, this path should already contain
all the query field and everything
## Returns
The data of the returned response. If the response is not successful it
crashes since it cannot parse the response correctly.
"""
def execute_request(:get, create_struct, path) do
get(path)
|> handle_response(create_struct)
end
@doc """
This is the main function that does post requests.
## Parameters
- :post: it only matches post requests
- path: the path of the resource, this path should already contain
all the query field and everything
- data: the data to post. Example: %{board: "username/board_name"}
"""
def execute_request(:post, path, data) do
post(path, data)
|> handle_response
end
@doc """
This is the main function that does delete requests.
## Parameters
- :delete: it only matches delete requests
- path: the path of the resource, this path should already contain
all the query field and everything
"""
def execute_request(:delete, path) do
delete(path)
|> handle_response
end
def execute_request(:get, createStruct, path, []) do
execute_request(:get, createStruct, path)
end
@doc """
The function is used for doing get requests that have additional parameters.
## Parameters
- :get: it only matches get requests
- createStruct: if the response succeeds this is the function that will be used to created the structs from the data that was received
- path: the path of the resource, this path should already contain
all the query field and everything
- options: a list of options that should be added to the request. For example
we might wish to get bio and counts for a certain user. In this case we would
pass in ["bio", "counts"].
## Returns
The data of the returned response. If the response is not successful it
crashes since it cannot parse the response correctly.
"""
def execute_request(:get, createStruct, path, options) do
case List.keyfind(options, :next, 0) do
{:next, url} -> execute_request(:get, createStruct, url)
_ -> execute_request(:get, createStruct, path <> get_fields(path, options))
end
end
@doc """
This is the main function that does patch requests.
## Parameters
- :patch: it only matches patch requests
- path: the path of the resource, this path should already contain
all the query field and everything
- data: the data to . Example: %{name: "New Name"}
"""
def execute_request(:patch, create_struct, path, data) do
patch(path, data)
|> handle_response(create_struct)
end
def get_fields(path, options) do
start =
if(String.contains? path, "?") do
"&"
else
"?"
end
start <> Enum.join(Enum.map(options, &concat_items/1), "&")
end
defp concat_items({k, v}) when is_list(v) do
"#{k}=" <> Enum.join(v, ",")
end
defp concat_items({k, v}) do
"#{k}=#{v}"
end
defp handle_response(response, createStruct) do
case response.status do
200 -> {:ok, createStruct.(response.body)}
_ -> {:error, response.body["message"]}
end
end
defp handle_response(response) do
case response.status do
200 -> {:ok, response.body["data"]}
_ -> {:error, response.body["message"]}
end
end
end
| 27.302817 | 136 | 0.682486 |
736020419493b17c9f6b559c4c2cdbb767041b79 | 3,079 | ex | Elixir | lib/optimus/option.ex | savonarola/optimus | e5369b1ddd5ba2bc6c71bbecf0a7ba0e96e52a08 | [
"MIT"
] | 82 | 2016-12-14T22:21:45.000Z | 2019-11-19T13:47:25.000Z | lib/optimus/option.ex | savonarola/optimus | e5369b1ddd5ba2bc6c71bbecf0a7ba0e96e52a08 | [
"MIT"
] | 15 | 2017-01-08T06:54:02.000Z | 2019-11-12T10:30:49.000Z | lib/optimus/option.ex | savonarola/optimus | e5369b1ddd5ba2bc6c71bbecf0a7ba0e96e52a08 | [
"MIT"
] | 7 | 2017-01-08T06:42:41.000Z | 2019-11-12T09:32:50.000Z | defmodule Optimus.Option do
defstruct [
:name,
:value_name,
:short,
:long,
:help,
:multiple,
:required,
:default,
:parser
]
def new(spec) do
Optimus.Option.Builder.build(spec)
end
def parse(option, parsed, command_line) when length(command_line) > 0 do
case parse_option_parts(option, command_line) do
{:ok, raw_value, rest} ->
key = {:option, option.name}
if option.multiple || !Map.has_key?(parsed, key) do
case option.parser.(raw_value) do
{:ok, value} ->
{:ok, Map.update(parsed, key, [value], &[value | &1]), rest}
{:error, reason} ->
{:error,
"invalid value #{inspect(raw_value)} for #{Optimus.Format.format_in_error(option)} option: #{
reason
}", rest}
end
else
{:error, "multiple occurrences of option #{Optimus.Format.format_in_error(option)}",
rest}
end
:skip ->
:skip
end
end
def parse(_, _, _), do: :skip
defp parse_option_parts(option, [item | items]) do
case extract_value(option, item) do
{:ok, value} ->
{:ok, value, items}
:none ->
case items do
[value_item | rest] ->
if item == option.long or item == option.short do
{:ok, value_item, rest}
else
:skip
end
_ ->
:skip
end
end
end
defp extract_value(option, str) do
if option.long do
length = String.length(option.long) + 1
if option.long <> "=" == String.slice(str, 0..(length - 1)) do
{:ok, String.slice(str, length..-1)}
else
:none
end
else
:none
end
end
def try_match([option | options], parsed, items) do
case parse(option, parsed, items) do
:skip -> try_match(options, parsed, items)
value -> value
end
end
def try_match([], _, _), do: :skip
end
defimpl Optimus.Format, for: Optimus.Option do
def format(option) do
[option.short, option.long]
|> Enum.reject(&is_nil/1)
|> Enum.join(", ")
end
def format_in_error(option) do
case {option.long, option.short} do
{long, nil} -> long
{nil, short} -> short
{long, short} -> "#{long}(#{short})"
end
end
def format_in_usage(option) do
option_name = option.long || option.short
if option.required do
"#{option_name} #{option.value_name}"
else
"[#{option_name} #{option.value_name}]"
end
end
def help(option) do
help_string = option.help || ""
if option.default do
default_value_string =
if is_list(option.default) do
option.default |> Enum.map(&to_s/1) |> inspect
else
to_s(option.default)
end
"#{help_string} (default: #{default_value_string})"
else
help_string
end
end
def to_s(term) do
if String.Chars.impl_for(term) do
to_string(term)
else
inspect(term)
end
end
end
| 21.992857 | 108 | 0.551153 |
736020b4cece7699d164bd6386d0906b66fcc3de | 94 | ex | Elixir | lib/learn/v14.ex | DitoHI/basic_elixir | af21384e99df0f7289ca1908c3e21bce8aef475c | [
"MIT"
] | null | null | null | lib/learn/v14.ex | DitoHI/basic_elixir | af21384e99df0f7289ca1908c3e21bce8aef475c | [
"MIT"
] | null | null | null | lib/learn/v14.ex | DitoHI/basic_elixir | af21384e99df0f7289ca1908c3e21bce8aef475c | [
"MIT"
] | null | null | null | defmodule V14 do
@moduledoc false
# struct
defstruct [:school, name: "VJ", age: 27]
end
| 15.666667 | 42 | 0.670213 |
73602cae20e44da80e8742403baa2f43264143bd | 16,518 | ex | Elixir | lib/ecto/ulid.ex | heri16/ecto-ulid | 969023feed28083fda18b0af9a322ea33b015ef8 | [
"MIT"
] | 2 | 2021-12-10T01:54:14.000Z | 2021-12-10T05:35:25.000Z | lib/ecto/ulid.ex | heri16/ecto-ulid | 969023feed28083fda18b0af9a322ea33b015ef8 | [
"MIT"
] | null | null | null | lib/ecto/ulid.ex | heri16/ecto-ulid | 969023feed28083fda18b0af9a322ea33b015ef8 | [
"MIT"
] | 1 | 2021-12-10T05:17:54.000Z | 2021-12-10T05:17:54.000Z | defmodule Ecto.ULID do
@moduledoc """
An Ecto type for ULID strings.
"""
@default_params %{variant: :b32}
# replace with `use Ecto.ParameterizedType` after Ecto 3.2.0 is required
@behaviour Ecto.ParameterizedType
# and remove both of these functions
def embed_as(_, _params), do: :self
def equal?(term1, term2, _params), do: term1 == term2
@doc """
The underlying schema type.
"""
def type(_params), do: :uuid
@doc false
def init(opts) do
case Keyword.get(opts, :variant, :b32) do
v when v in [:b32, :b64, :push] -> %{variant: v}
_ -> raise "Ecto.ULID variant must be one of [:b32, :b64, :push]"
end
end
@doc """
Casts a string to ULID.
"""
def cast(value, params \\ @default_params)
def cast(nil, _params), do: {:ok, nil}
def cast(<<_::bytes-size(26)>> = value, %{variant: :b32}) do
# Crockford Base32 encoded string
if valid?(value) do
{:ok, value}
else
:error
end
end
def cast(<<_::bytes-size(22)>> = value, %{variant: :b64}) do
# Lexicographic Base64 encoded string
if valid64?(value) do
{:ok, value}
else
:error
end
end
def cast(<<_::bytes-size(20)>> = value, %{variant: :push}) do
# Firebase-Push-Key Base64 encoded string
if valid64?(value) do
{:ok, value}
else
:error
end
end
def cast(_, _params), do: :error
@doc """
Same as `cast/2` but raises `Ecto.CastError` on invalid arguments.
"""
def cast!(value, params \\ @default_params) do
case cast(value, params) do
{:ok, ulid} -> ulid
:error -> raise Ecto.CastError, type: __MODULE__, value: value
end
end
@doc """
Converts a Crockford Base32 encoded string or
Lexicographic Base64 encoded string or Firebase-Push-Key Base64 encoded string
into a binary ULID.
"""
def dump(encoded)
def dump(<<_::bytes-size(26)>> = encoded), do: decode(encoded)
def dump(<<_::bytes-size(22)>> = encoded), do: decode64(encoded)
def dump(<<_::bytes-size(20)>> = encoded), do: decode64(encoded)
def dump(_), do: :error
@doc false
def dump(nil, _, _), do: {:ok, nil}
def dump(encoded, _dumper, _params), do: dump(encoded)
@doc """
Converts a binary ULID into an encoded string (defaults to Crockford Base32 encoding).
Variants:
* `:b32`: Crockford Base32 encoding (default)
* `:b64`: Lexicographic Base64 encoding
* `:push`: Firebase Push-Key Base64 encoding
Arguments:
* `bytes`: A binary ULID.
* `variant`: :b32 (default), :b64 (Base64), or :push (Firebase Push-Key).
"""
def load(bytes, variant \\ :b32)
def load(<<_::unsigned-size(128)>> = bytes, :b32), do: encode(bytes)
def load(<<_::unsigned-size(128)>> = bytes, :b64), do: encode64(bytes)
def load(<<ts::bits-size(48), _::bits-size(8), rand::bits-size(72)>> = _bytes, :push), do: encode64(<<ts::binary, rand::binary>>)
def load(_, _variant), do: :error
@doc false
def load(nil, _, _), do: {:ok, nil}
def load(bytes, _loader, %{variant: variant}), do: load(bytes, variant)
def load(_, _loader, _params), do: :error
@doc false
def autogenerate(%{variant: variant} = _params), do: generate(variant)
@doc """
Generates a string encoded ULID (defaults to Crockford Base32 encoding).
If a value is provided for `timestamp`, the generated ULID will be for the provided timestamp.
Otherwise, a ULID will be generated for the current time.
Variants:
* `:b32`: Crockford Base32 encoding (default)
* `:b64`: Lexicographic Base64 encoding
* `:push`: Firebase Push-Key Base64 encoding
Arguments:
* `variant`: :b32 (default), :b64 (Base64), or :push (Firebase Push-Key).
* `timestamp`: A Unix timestamp with millisecond precision.
"""
def generate(variant \\ :b32, timestamp \\ System.system_time(:millisecond))
def generate(:b32, timestamp) do
{:ok, ulid} = encode(bingenerate(timestamp))
ulid
end
def generate(:b64, timestamp) do
{:ok, ulid} = encode64(bingenerate(timestamp))
ulid
end
def generate(:push, timestamp) do
<<ts::bits-size(48), _::bits-size(8), rand::bits-size(72)>> = bingenerate(timestamp)
{:ok, ulid} = encode64(<<ts::binary, rand::binary>>)
ulid
end
def generate(timestamp, _) when is_integer(timestamp) do
{:ok, ulid} = encode(bingenerate(timestamp))
ulid
end
@doc """
Generates a binary ULID.
If a value is provided for `timestamp`, the generated ULID will be for the provided timestamp.
Otherwise, a ULID will be generated for the current time.
Arguments:
* `timestamp`: A Unix timestamp with millisecond precision.
"""
def bingenerate(timestamp \\ System.system_time(:millisecond)) do
<<timestamp::unsigned-size(48), :crypto.strong_rand_bytes(10)::binary>>
end
defp encode(<< b1::3, b2::5, b3::5, b4::5, b5::5, b6::5, b7::5, b8::5, b9::5, b10::5, b11::5, b12::5, b13::5,
b14::5, b15::5, b16::5, b17::5, b18::5, b19::5, b20::5, b21::5, b22::5, b23::5, b24::5, b25::5, b26::5>>) do
<<e(b1), e(b2), e(b3), e(b4), e(b5), e(b6), e(b7), e(b8), e(b9), e(b10), e(b11), e(b12), e(b13),
e(b14), e(b15), e(b16), e(b17), e(b18), e(b19), e(b20), e(b21), e(b22), e(b23), e(b24), e(b25), e(b26)>>
catch
:error -> :error
else
encoded -> {:ok, encoded}
end
defp encode(_), do: :error
defp encode64(<< b1::2, b2::6, b3::6, b4::6, b5::6, b6::6, b7::6, b8::6, b9::6, b10::6, b11::6, b12::6, b13::6,
b14::6, b15::6, b16::6, b17::6, b18::6, b19::6, b20::6, b21::6, b22::6>>) do
<<e64(b1), e64(b2), e64(b3), e64(b4), e64(b5), e64(b6), e64(b7), e64(b8), e64(b9), e64(b10), e64(b11), e64(b12), e64(b13),
e64(b14), e64(b15), e64(b16), e64(b17), e64(b18), e64(b19), e64(b20), e64(b21), e64(b22)>>
catch
:error -> :error
else
encoded -> {:ok, encoded}
end
defp encode64(<< b1::6, b2::6, b3::6, b4::6, b5::6, b6::6, b7::6, b8::6, b9::6, b10::6, b11::6, b12::6, b13::6,
b14::6, b15::6, b16::6, b17::6, b18::6, b19::6, b20::6>>) do
<<e64(b1), e64(b2), e64(b3), e64(b4), e64(b5), e64(b6), e64(b7), e64(b8), e64(b9), e64(b10), e64(b11), e64(b12), e64(b13),
e64(b14), e64(b15), e64(b16), e64(b17), e64(b18), e64(b19), e64(b20)>>
catch
:error -> :error
else
encoded -> {:ok, encoded}
end
defp encode64(_), do: :error
@compile {:inline, e: 1, e64: 1}
defp e(0), do: ?0
defp e(1), do: ?1
defp e(2), do: ?2
defp e(3), do: ?3
defp e(4), do: ?4
defp e(5), do: ?5
defp e(6), do: ?6
defp e(7), do: ?7
defp e(8), do: ?8
defp e(9), do: ?9
defp e(10), do: ?A
defp e(11), do: ?B
defp e(12), do: ?C
defp e(13), do: ?D
defp e(14), do: ?E
defp e(15), do: ?F
defp e(16), do: ?G
defp e(17), do: ?H
defp e(18), do: ?J
defp e(19), do: ?K
defp e(20), do: ?M
defp e(21), do: ?N
defp e(22), do: ?P
defp e(23), do: ?Q
defp e(24), do: ?R
defp e(25), do: ?S
defp e(26), do: ?T
defp e(27), do: ?V
defp e(28), do: ?W
defp e(29), do: ?X
defp e(30), do: ?Y
defp e(31), do: ?Z
defp e64(0), do: ?-
defp e64(1), do: ?0
defp e64(2), do: ?1
defp e64(3), do: ?2
defp e64(4), do: ?3
defp e64(5), do: ?4
defp e64(6), do: ?5
defp e64(7), do: ?6
defp e64(8), do: ?7
defp e64(9), do: ?8
defp e64(10), do: ?9
defp e64(11), do: ?A
defp e64(12), do: ?B
defp e64(13), do: ?C
defp e64(14), do: ?D
defp e64(15), do: ?E
defp e64(16), do: ?F
defp e64(17), do: ?G
defp e64(18), do: ?H
defp e64(19), do: ?I
defp e64(20), do: ?J
defp e64(21), do: ?K
defp e64(22), do: ?L
defp e64(23), do: ?M
defp e64(24), do: ?N
defp e64(25), do: ?O
defp e64(26), do: ?P
defp e64(27), do: ?Q
defp e64(28), do: ?R
defp e64(29), do: ?S
defp e64(30), do: ?T
defp e64(31), do: ?U
defp e64(32), do: ?V
defp e64(33), do: ?W
defp e64(34), do: ?X
defp e64(35), do: ?Y
defp e64(36), do: ?Z
defp e64(37), do: ?_
defp e64(38), do: ?a
defp e64(39), do: ?b
defp e64(40), do: ?c
defp e64(41), do: ?d
defp e64(42), do: ?e
defp e64(43), do: ?f
defp e64(44), do: ?g
defp e64(45), do: ?h
defp e64(46), do: ?i
defp e64(47), do: ?j
defp e64(48), do: ?k
defp e64(49), do: ?l
defp e64(50), do: ?m
defp e64(51), do: ?n
defp e64(52), do: ?o
defp e64(53), do: ?p
defp e64(54), do: ?q
defp e64(55), do: ?r
defp e64(56), do: ?s
defp e64(57), do: ?t
defp e64(58), do: ?u
defp e64(59), do: ?v
defp e64(60), do: ?w
defp e64(61), do: ?x
defp e64(62), do: ?y
defp e64(63), do: ?z
defp decode(<< c1::8, c2::8, c3::8, c4::8, c5::8, c6::8, c7::8, c8::8, c9::8, c10::8, c11::8, c12::8, c13::8,
c14::8, c15::8, c16::8, c17::8, c18::8, c19::8, c20::8, c21::8, c22::8, c23::8, c24::8, c25::8, c26::8>>) do
<< d(c1)::3, d(c2)::5, d(c3)::5, d(c4)::5, d(c5)::5, d(c6)::5, d(c7)::5, d(c8)::5, d(c9)::5, d(c10)::5, d(c11)::5, d(c12)::5, d(c13)::5,
d(c14)::5, d(c15)::5, d(c16)::5, d(c17)::5, d(c18)::5, d(c19)::5, d(c20)::5, d(c21)::5, d(c22)::5, d(c23)::5, d(c24)::5, d(c25)::5, d(c26)::5>>
catch
:error -> :error
else
decoded -> {:ok, decoded}
end
defp decode(_), do: :error
defp decode64(<< c1::8, c2::8, c3::8, c4::8, c5::8, c6::8, c7::8, c8::8, c9::8, c10::8, c11::8, c12::8, c13::8,
c14::8, c15::8, c16::8, c17::8, c18::8, c19::8, c20::8, c21::8, c22::8>>) do
<< d64(c1)::2, d64(c2)::6, d64(c3)::6, d64(c4)::6, d64(c5)::6, d64(c6)::6, d64(c7)::6, d64(c8)::6, d64(c9)::6, d64(c10)::6, d64(c11)::6, d64(c12)::6, d64(c13)::6,
d64(c14)::6, d64(c15)::6, d64(c16)::6, d64(c17)::6, d64(c18)::6, d64(c19)::6, d64(c20)::6, d64(c21)::6, d64(c22)::6>>
catch
:error -> :error
else
decoded -> {:ok, decoded}
end
defp decode64(<< c1::8, c2::8, c3::8, c4::8, c5::8, c6::8, c7::8, c8::8, c9::8, c10::8, c11::8, c12::8, c13::8,
c14::8, c15::8, c16::8, c17::8, c18::8, c19::8, c20::8>>) do
<< d64(c1)::6, d64(c2)::6, d64(c3)::6, d64(c4)::6, d64(c5)::6, d64(c6)::6, d64(c7)::6, d64(c8)::6, 0::unsigned-size(8), d64(c9)::6, d64(c10)::6, d64(c11)::6, d64(c12)::6, d64(c13)::6,
d64(c14)::6, d64(c15)::6, d64(c16)::6, d64(c17)::6, d64(c18)::6, d64(c19)::6, d64(c20)::6>>
catch
:error -> :error
else
decoded -> {:ok, decoded}
end
defp decode64(_), do: :error
@compile {:inline, d: 1, d64: 1}
defp d(?0), do: 0
defp d(?1), do: 1
defp d(?2), do: 2
defp d(?3), do: 3
defp d(?4), do: 4
defp d(?5), do: 5
defp d(?6), do: 6
defp d(?7), do: 7
defp d(?8), do: 8
defp d(?9), do: 9
defp d(?A), do: 10
defp d(?B), do: 11
defp d(?C), do: 12
defp d(?D), do: 13
defp d(?E), do: 14
defp d(?F), do: 15
defp d(?G), do: 16
defp d(?H), do: 17
defp d(?J), do: 18
defp d(?K), do: 19
defp d(?M), do: 20
defp d(?N), do: 21
defp d(?P), do: 22
defp d(?Q), do: 23
defp d(?R), do: 24
defp d(?S), do: 25
defp d(?T), do: 26
defp d(?V), do: 27
defp d(?W), do: 28
defp d(?X), do: 29
defp d(?Y), do: 30
defp d(?Z), do: 31
defp d(_), do: throw :error
defp d64(?-), do: 0
defp d64(?0), do: 1
defp d64(?1), do: 2
defp d64(?2), do: 3
defp d64(?3), do: 4
defp d64(?4), do: 5
defp d64(?5), do: 6
defp d64(?6), do: 7
defp d64(?7), do: 8
defp d64(?8), do: 9
defp d64(?9), do: 10
defp d64(?A), do: 11
defp d64(?B), do: 12
defp d64(?C), do: 13
defp d64(?D), do: 14
defp d64(?E), do: 15
defp d64(?F), do: 16
defp d64(?G), do: 17
defp d64(?H), do: 18
defp d64(?I), do: 19
defp d64(?J), do: 20
defp d64(?K), do: 21
defp d64(?L), do: 22
defp d64(?M), do: 23
defp d64(?N), do: 24
defp d64(?O), do: 25
defp d64(?P), do: 26
defp d64(?Q), do: 27
defp d64(?R), do: 28
defp d64(?S), do: 29
defp d64(?T), do: 30
defp d64(?U), do: 31
defp d64(?V), do: 32
defp d64(?W), do: 33
defp d64(?X), do: 34
defp d64(?Y), do: 35
defp d64(?Z), do: 36
defp d64(?_), do: 37
defp d64(?a), do: 38
defp d64(?b), do: 39
defp d64(?c), do: 40
defp d64(?d), do: 41
defp d64(?e), do: 42
defp d64(?f), do: 43
defp d64(?g), do: 44
defp d64(?h), do: 45
defp d64(?i), do: 46
defp d64(?j), do: 47
defp d64(?k), do: 48
defp d64(?l), do: 49
defp d64(?m), do: 50
defp d64(?n), do: 51
defp d64(?o), do: 52
defp d64(?p), do: 53
defp d64(?q), do: 54
defp d64(?r), do: 55
defp d64(?s), do: 56
defp d64(?t), do: 57
defp d64(?u), do: 58
defp d64(?v), do: 59
defp d64(?w), do: 60
defp d64(?x), do: 61
defp d64(?y), do: 62
defp d64(?z), do: 63
defp d64(_), do: throw :error
defp valid?(<< c1::8, c2::8, c3::8, c4::8, c5::8, c6::8, c7::8, c8::8, c9::8, c10::8, c11::8, c12::8, c13::8,
c14::8, c15::8, c16::8, c17::8, c18::8, c19::8, c20::8, c21::8, c22::8, c23::8, c24::8, c25::8, c26::8>>) do
c1 in [?0, ?1, ?2, ?3, ?4, ?5, ?6, ?7] &&
v(c2) && v(c3) && v(c4) && v(c5) && v(c6) && v(c7) && v(c8) && v(c9) && v(c10) && v(c11) && v(c12) && v(c13) &&
v(c14) && v(c15) && v(c16) && v(c17) && v(c18) && v(c19) && v(c20) && v(c21) && v(c22) && v(c23) && v(c24) && v(c25) && v(c26)
end
defp valid?(_), do: false
defp valid64?(<< c1::8, c2::8, c3::8, c4::8, c5::8, c6::8, c7::8, c8::8, c9::8, c10::8, c11::8, c12::8, c13::8,
c14::8, c15::8, c16::8, c17::8, c18::8, c19::8, c20::8, c21::8, c22::8>>) do
v64(c1) && v64(c2) && v64(c3) && v64(c4) && v64(c5) && v64(c6) && v64(c7) && v64(c8) && v64(c9) && v64(c10) && v64(c11) && v64(c12) && v64(c13) &&
v64(c14) && v64(c15) && v64(c16) && v64(c17) && v64(c18) && v64(c19) && v64(c20) && v64(c21) && v64(c22)
end
defp valid64?(<< c1::8, c2::8, c3::8, c4::8, c5::8, c6::8, c7::8, c8::8, c9::8, c10::8, c11::8, c12::8, c13::8,
c14::8, c15::8, c16::8, c17::8, c18::8, c19::8, c20::8>>) do
v64(c1) && v64(c2) && v64(c3) && v64(c4) && v64(c5) && v64(c6) && v64(c7) && v64(c8) && v64(c9) && v64(c10) && v64(c11) && v64(c12) && v64(c13) &&
v64(c14) && v64(c15) && v64(c16) && v64(c17) && v64(c18) && v64(c19) && v64(c20)
end
defp valid64?(_), do: false
@compile {:inline, v: 1, v64: 1}
defp v(?0), do: true
defp v(?1), do: true
defp v(?2), do: true
defp v(?3), do: true
defp v(?4), do: true
defp v(?5), do: true
defp v(?6), do: true
defp v(?7), do: true
defp v(?8), do: true
defp v(?9), do: true
defp v(?A), do: true
defp v(?B), do: true
defp v(?C), do: true
defp v(?D), do: true
defp v(?E), do: true
defp v(?F), do: true
defp v(?G), do: true
defp v(?H), do: true
defp v(?J), do: true
defp v(?K), do: true
defp v(?M), do: true
defp v(?N), do: true
defp v(?P), do: true
defp v(?Q), do: true
defp v(?R), do: true
defp v(?S), do: true
defp v(?T), do: true
defp v(?V), do: true
defp v(?W), do: true
defp v(?X), do: true
defp v(?Y), do: true
defp v(?Z), do: true
defp v(_), do: false
defp v64(?-), do: true
defp v64(?0), do: true
defp v64(?1), do: true
defp v64(?2), do: true
defp v64(?3), do: true
defp v64(?4), do: true
defp v64(?5), do: true
defp v64(?6), do: true
defp v64(?7), do: true
defp v64(?8), do: true
defp v64(?9), do: true
defp v64(?A), do: true
defp v64(?B), do: true
defp v64(?C), do: true
defp v64(?D), do: true
defp v64(?E), do: true
defp v64(?F), do: true
defp v64(?G), do: true
defp v64(?H), do: true
defp v64(?I), do: true
defp v64(?J), do: true
defp v64(?K), do: true
defp v64(?L), do: true
defp v64(?M), do: true
defp v64(?N), do: true
defp v64(?O), do: true
defp v64(?P), do: true
defp v64(?Q), do: true
defp v64(?R), do: true
defp v64(?S), do: true
defp v64(?T), do: true
defp v64(?U), do: true
defp v64(?V), do: true
defp v64(?W), do: true
defp v64(?X), do: true
defp v64(?Y), do: true
defp v64(?Z), do: true
defp v64(?_), do: true
defp v64(?a), do: true
defp v64(?b), do: true
defp v64(?c), do: true
defp v64(?d), do: true
defp v64(?e), do: true
defp v64(?f), do: true
defp v64(?g), do: true
defp v64(?h), do: true
defp v64(?i), do: true
defp v64(?j), do: true
defp v64(?k), do: true
defp v64(?l), do: true
defp v64(?m), do: true
defp v64(?n), do: true
defp v64(?o), do: true
defp v64(?p), do: true
defp v64(?q), do: true
defp v64(?r), do: true
defp v64(?s), do: true
defp v64(?t), do: true
defp v64(?u), do: true
defp v64(?v), do: true
defp v64(?w), do: true
defp v64(?x), do: true
defp v64(?y), do: true
defp v64(?z), do: true
defp v64(_), do: false
end
| 30.197441 | 193 | 0.53923 |
73603f52a19ca814b8512c87d131e6f05691ca0e | 345 | exs | Elixir | priv/repo/seeds.exs | Sapfir0/elCloud | 3ef9e8d2400898250ee65d36870672e76006c263 | [
"Unlicense"
] | 2 | 2021-05-30T20:11:44.000Z | 2021-12-20T19:08:56.000Z | priv/repo/seeds.exs | Sapfir0/elCloud | 3ef9e8d2400898250ee65d36870672e76006c263 | [
"Unlicense"
] | null | null | null | priv/repo/seeds.exs | Sapfir0/elCloud | 3ef9e8d2400898250ee65d36870672e76006c263 | [
"Unlicense"
] | 1 | 2022-01-23T05:29:08.000Z | 2022-01-23T05:29:08.000Z | # Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Test.Repo.insert!(%Test.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 28.75 | 61 | 0.701449 |
7360409352b92037f56997b3687c29bbf3ef7836 | 907 | ex | Elixir | lib/ua_parser/version.ex | webnard/ua_parser | ec83f5110fda3e4f87d0ee7ea5ea57d9d196f6bf | [
"Apache-2.0"
] | null | null | null | lib/ua_parser/version.ex | webnard/ua_parser | ec83f5110fda3e4f87d0ee7ea5ea57d9d196f6bf | [
"Apache-2.0"
] | null | null | null | lib/ua_parser/version.ex | webnard/ua_parser | ec83f5110fda3e4f87d0ee7ea5ea57d9d196f6bf | [
"Apache-2.0"
] | null | null | null | defmodule UAParser.Version do
@moduledoc """
A module representing user agent version struct and helper methods.
"""
@doc """
## Examples
iex> version = %UAParser.Version{major: "1", minor: "2", patch: "3", patch_minor: "4"}
iex> to_string(version)
"1.2.3.4"
iex> version = %UAParser.Version{major: "1", minor: "2", patch: "3"}
iex> to_string(version)
"1.2.3"
iex> version = %UAParser.Version{major: "1", minor: "2"}
iex> to_string(version)
"1.2"
iex> version = %UAParser.Version{major: "1"}
iex> to_string(version)
"1"
"""
defstruct [:major, :minor, :patch, :patch_minor]
end
defimpl String.Chars, for: UAParser.Version do
def to_string(%{major: major, minor: minor, patch: patch, patch_minor: patch_minor}) do
[major, minor, patch, patch_minor]
|> Enum.reject(&is_nil/1)
|> Enum.join(".")
end
end
| 25.914286 | 92 | 0.610805 |
73605c58d11915dd1f43fc525e5e9a208a6c8195 | 1,718 | ex | Elixir | lib/camino_challenge_web/endpoint.ex | kadmohardy/camino_challenge | 53117f763c0a51b0825cac18b799b7d772781671 | [
"MIT"
] | null | null | null | lib/camino_challenge_web/endpoint.ex | kadmohardy/camino_challenge | 53117f763c0a51b0825cac18b799b7d772781671 | [
"MIT"
] | null | null | null | lib/camino_challenge_web/endpoint.ex | kadmohardy/camino_challenge | 53117f763c0a51b0825cac18b799b7d772781671 | [
"MIT"
] | null | null | null | defmodule CaminoChallengeWeb.Endpoint do
@moduledoc false
use Phoenix.Endpoint, otp_app: :camino_challenge
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
@session_options [
store: :cookie,
key: "_camino_challenge_key",
signing_salt: "QXEjaOMV"
]
socket "/live", Phoenix.LiveView.Socket, websocket: [connect_info: [session: @session_options]]
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :camino_challenge,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
plug Plug.Static, at: "/uploads/arquivos", from: Path.expand('./uploads/arquivos'), gzip: false
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
plug Phoenix.Ecto.CheckRepoStatus, otp_app: :camino_challenge
end
plug Phoenix.LiveDashboard.RequestLogger,
param_key: "request_logger",
cookie_key: "request_logger"
plug Plug.RequestId
plug Plug.Telemetry, event_prefix: [:phoenix, :endpoint]
plug Plug.Parsers,
parsers: [:urlencoded, {:multipart, length: 500_000_000}, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session, @session_options
plug CaminoChallengeWeb.Router
end
| 31.814815 | 97 | 0.728172 |
736087b277de61bfee005a4074ada686c1e65730 | 26,686 | ex | Elixir | lib/ecto/multi.ex | iautom8things/ecto | 9e89e9b7f8c7d11373c2372f2d3365dd8b4aaccf | [
"Apache-2.0"
] | 1 | 2022-03-13T23:01:45.000Z | 2022-03-13T23:01:45.000Z | lib/ecto/multi.ex | iautom8things/ecto | 9e89e9b7f8c7d11373c2372f2d3365dd8b4aaccf | [
"Apache-2.0"
] | null | null | null | lib/ecto/multi.ex | iautom8things/ecto | 9e89e9b7f8c7d11373c2372f2d3365dd8b4aaccf | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Multi do
@moduledoc """
`Ecto.Multi` is a data structure for grouping multiple Repo operations.
`Ecto.Multi` makes it possible to pack operations that should be
performed in a single database transaction and gives a way to introspect
the queued operations without actually performing them. Each operation
is given a name that is unique and will identify its result in case of
success or failure.
If a multi is valid (i.e. all the changesets in it are valid),
all operations will be executed in the order they were added.
The `Ecto.Multi` structure should be considered opaque. You can use
`%Ecto.Multi{}` to pattern match the type, but accessing fields or
directly modifying them is not advised.
`Ecto.Multi.to_list/1` returns a canonical representation of the
structure that can be used for introspection.
## Changesets
If multi contains operations that accept changesets (like `insert/4`,
`update/4` or `delete/4`) they will be checked before starting the
transaction. If any changeset has errors, the transaction won't even
be started and the error will be immediately returned.
Note: `insert/4`, `update/4`, `insert_or_update/4`, and `delete/4`
variants that accept a function are not performing such checks since
the functions are executed after the transaction has started.
## Run
Multi allows you to run arbitrary functions as part of your transaction
via `run/3` and `run/5`. This is especially useful when an operation
depends on the value of a previous operation. For this reason, the
function given as a callback to `run/3` and `run/5` will receive the repo
as the first argument, and all changes performed by the multi so far as a
map for the second argument.
The function given to `run` must return `{:ok, value}` or `{:error, value}`
as its result. Returning an error will abort any further operations
and make the whole multi fail.
## Example
Let's look at an example definition and usage. The use case we'll be
looking into is resetting a password. We need to update the account
with proper information, log the request and remove all current sessions:
defmodule PasswordManager do
alias Ecto.Multi
def reset(account, params) do
Multi.new()
|> Multi.update(:account, Account.password_reset_changeset(account, params))
|> Multi.insert(:log, Log.password_reset_changeset(account, params))
|> Multi.delete_all(:sessions, Ecto.assoc(account, :sessions))
end
end
We can later execute it in the integration layer using Repo:
Repo.transaction(PasswordManager.reset(account, params))
By pattern matching on the result we can differentiate different conditions:
case result do
{:ok, %{account: account, log: log, sessions: sessions}} ->
# Operation was successful, we can access results (exactly the same
# we would get from running corresponding Repo functions) under keys
# we used for naming the operations.
{:error, failed_operation, failed_value, changes_so_far} ->
# One of the operations failed. We can access the operation's failure
# value (like changeset for operations on changesets) to prepare a
# proper response. We also get access to the results of any operations
# that succeeded before the indicated operation failed. However, any
# successful operations would have been rolled back.
end
We can also easily unit test our transaction without actually running it.
Since changesets can use in-memory-data, we can use an account that is
constructed in memory as well (without persisting it to the database):
test "dry run password reset" do
account = %Account{password: "letmein"}
multi = PasswordManager.reset(account, params)
assert [
{:account, {:update, account_changeset, []}},
{:log, {:insert, log_changeset, []}},
{:sessions, {:delete_all, query, []}}
] = Ecto.Multi.to_list(multi)
# We can introspect changesets and query to see if everything
# is as expected, for example:
assert account_changeset.valid?
assert log_changeset.valid?
assert inspect(query) == "#Ecto.Query<from a in Session>"
end
The name of each operation does not have to be an atom. This can be particularly
useful when you wish to update a collection of changesets at once, and track their
errors individually:
accounts = [%Account{id: 1}, %Account{id: 2}]
Enum.reduce(accounts, Multi.new(), fn account, multi ->
Multi.update(
multi,
{:account, account.id},
Account.password_reset_changeset(account, params)
)
end)
"""
alias __MODULE__
alias Ecto.Changeset
defstruct operations: [], names: MapSet.new()
@type changes :: map
@type run :: ((Ecto.Repo.t, changes) -> {:ok | :error, any}) | {module, atom, [any]}
@type fun(result) :: (changes -> result)
@type merge :: (changes -> t) | {module, atom, [any]}
@typep schema_or_source :: binary | {binary, module} | module
@typep operation :: {:changeset, Changeset.t, Keyword.t} |
{:run, run} |
{:put, any} |
{:inspect, Keyword.t} |
{:merge, merge} |
{:update_all, Ecto.Query.t, Keyword.t} |
{:delete_all, Ecto.Query.t, Keyword.t} |
{:insert_all, schema_or_source, [map | Keyword.t], Keyword.t}
@typep operations :: [{name, operation}]
@typep names :: MapSet.t
@type name :: any
@type t :: %__MODULE__{operations: operations, names: names}
@doc """
Returns an empty `Ecto.Multi` struct.
## Example
iex> Ecto.Multi.new() |> Ecto.Multi.to_list()
[]
"""
@spec new :: t
def new do
%Multi{}
end
@doc """
Appends the second multi to the first one.
All names must be unique between both structures.
## Example
iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end)
iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end)
iex> Ecto.Multi.append(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
[:left, :right]
"""
@spec append(t, t) :: t
def append(lhs, rhs) do
merge_structs(lhs, rhs, &(&2 ++ &1))
end
@doc """
Prepends the second multi to the first one.
All names must be unique between both structures.
## Example
iex> lhs = Ecto.Multi.new() |> Ecto.Multi.run(:left, fn _, changes -> {:ok, changes} end)
iex> rhs = Ecto.Multi.new() |> Ecto.Multi.run(:right, fn _, changes -> {:error, changes} end)
iex> Ecto.Multi.prepend(lhs, rhs) |> Ecto.Multi.to_list |> Keyword.keys
[:right, :left]
"""
@spec prepend(t, t) :: t
def prepend(lhs, rhs) do
merge_structs(lhs, rhs, &(&1 ++ &2))
end
defp merge_structs(%Multi{} = lhs, %Multi{} = rhs, joiner) do
%{names: lhs_names, operations: lhs_ops} = lhs
%{names: rhs_names, operations: rhs_ops} = rhs
case MapSet.intersection(lhs_names, rhs_names) |> MapSet.to_list do
[] ->
%Multi{names: MapSet.union(lhs_names, rhs_names),
operations: joiner.(lhs_ops, rhs_ops)}
common ->
raise ArgumentError, """
error when merging the following Ecto.Multi structs:
#{Kernel.inspect lhs}
#{Kernel.inspect rhs}
both declared operations: #{Kernel.inspect common}
"""
end
end
@doc """
Merges a multi returned dynamically by an anonymous function.
This function is useful when the multi to be merged requires information
from the original multi. Hence the second argument is an anonymous function
that receives the multi changes so far. The anonymous function must return
another multi.
If you would prefer to simply merge two multis together, see `append/2` or
`prepend/2`.
Duplicated operations are not allowed.
## Example
multi =
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{title: "first"})
multi
|> Ecto.Multi.merge(fn %{post: post} ->
Ecto.Multi.new()
|> Ecto.Multi.insert(:comment, Ecto.build_assoc(post, :comments))
end)
|> MyApp.Repo.transaction()
"""
@spec merge(t, (changes -> t)) :: t
def merge(%Multi{} = multi, merge) when is_function(merge, 1) do
Map.update!(multi, :operations, &[{:merge, {:merge, merge}} | &1])
end
@doc """
Merges a multi returned dynamically by calling `module` and `function` with `args`.
Similar to `merge/2`, but allows to pass module name, function and arguments.
The function should return an `Ecto.Multi`, and receives changes so far
as the first argument (prepended to those passed in the call to the function).
Duplicated operations are not allowed.
"""
@spec merge(t, module, function, args) :: t when function: atom, args: [any]
def merge(%Multi{} = multi, mod, fun, args)
when is_atom(mod) and is_atom(fun) and is_list(args) do
Map.update!(multi, :operations, &[{:merge, {:merge, {mod, fun, args}}} | &1])
end
@doc """
Adds an insert operation to the multi.
Accepts the same arguments and options as `c:Ecto.Repo.insert/2` does.
## Example
Ecto.Multi.new()
|> Ecto.Multi.insert(:insert, %Post{title: "first"})
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{title: "first"})
|> Ecto.Multi.insert(:comment, fn %{post: post} ->
Ecto.build_assoc(post, :comments)
end)
|> MyApp.Repo.transaction()
"""
@spec insert(t, name, Changeset.t | Ecto.Schema.t | fun(Changeset.t | Ecto.Schema.t), Keyword.t) :: t
def insert(multi, name, changeset_or_struct_or_fun, opts \\ [])
def insert(multi, name, %Changeset{} = changeset, opts) do
add_changeset(multi, :insert, name, changeset, opts)
end
def insert(multi, name, %_{} = struct, opts) do
insert(multi, name, Changeset.change(struct), opts)
end
def insert(multi, name, fun, opts) when is_function(fun, 1) do
run(multi, name, operation_fun({:insert, fun}, opts))
end
@doc """
Adds an update operation to the multi.
Accepts the same arguments and options as `c:Ecto.Repo.update/2` does.
## Example
post = MyApp.Repo.get!(Post, 1)
changeset = Ecto.Changeset.change(post, title: "New title")
Ecto.Multi.new()
|> Ecto.Multi.update(:update, changeset)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.insert(:post, %Post{title: "first"})
|> Ecto.Multi.update(:fun, fn %{post: post} ->
Ecto.Changeset.change(post, title: "New title")
end)
|> MyApp.Repo.transaction()
"""
@spec update(t, name, Changeset.t | fun(Changeset.t), Keyword.t) :: t
def update(multi, name, changeset_or_fun, opts \\ [])
def update(multi, name, %Changeset{} = changeset, opts) do
add_changeset(multi, :update, name, changeset, opts)
end
def update(multi, name, fun, opts) when is_function(fun, 1) do
run(multi, name, operation_fun({:update, fun}, opts))
end
@doc """
Inserts or updates a changeset depending on whether the changeset was persisted or not.
Accepts the same arguments and options as `c:Ecto.Repo.insert_or_update/2` does.
## Example
changeset = Post.changeset(%Post{}, %{title: "New title"})
Ecto.Multi.new()
|> Ecto.Multi.insert_or_update(:insert_or_update, changeset)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
{:ok, repo.get(Post, 1) || %Post{}}
end)
|> Ecto.Multi.insert_or_update(:update, fn %{post: post} ->
Ecto.Changeset.change(post, title: "New title")
end)
|> MyApp.Repo.transaction()
"""
@spec insert_or_update(t, name, Changeset.t | fun(Changeset.t), Keyword.t) :: t
def insert_or_update(multi, name, changeset_or_fun, opts \\ [])
def insert_or_update(multi, name, %Changeset{data: %{__meta__: %{state: :loaded}}} = changeset, opts) do
add_changeset(multi, :update, name, changeset, opts)
end
def insert_or_update(multi, name, %Changeset{} = changeset, opts) do
add_changeset(multi, :insert, name, changeset, opts)
end
def insert_or_update(multi, name, fun, opts) when is_function(fun, 1) do
run(multi, name, operation_fun({:insert_or_update, fun}, opts))
end
@doc """
Adds a delete operation to the multi.
Accepts the same arguments and options as `c:Ecto.Repo.delete/2` does.
## Example
post = MyApp.Repo.get!(Post, 1)
Ecto.Multi.new()
|> Ecto.Multi.delete(:delete, post)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.delete(:delete, fn %{post: post} ->
# Others validations
post
end)
|> MyApp.Repo.transaction()
"""
@spec delete(t, name, Changeset.t | Ecto.Schema.t | fun(Changeset.t | Ecto.Schema.t), Keyword.t) :: t
def delete(multi, name, changeset_or_struct_fun, opts \\ [])
def delete(multi, name, %Changeset{} = changeset, opts) do
add_changeset(multi, :delete, name, changeset, opts)
end
def delete(multi, name, %_{} = struct, opts) do
delete(multi, name, Changeset.change(struct), opts)
end
def delete(multi, name, fun, opts) when is_function(fun, 1) do
run(multi, name, operation_fun({:delete, fun}, opts))
end
defp add_changeset(multi, action, name, changeset, opts) when is_list(opts) do
add_operation(multi, name, {:changeset, put_action(changeset, action), opts})
end
defp put_action(%{action: nil} = changeset, action) do
%{changeset | action: action}
end
defp put_action(%{action: action} = changeset, action) do
changeset
end
defp put_action(%{action: original}, action) do
raise ArgumentError, "you provided a changeset with an action already set " <>
"to #{Kernel.inspect original} when trying to #{action} it"
end
@doc """
Causes the multi to fail with the given value.
Running the multi in a transaction will execute
no previous steps and returns the value of the first
error added.
"""
@spec error(t, name, error :: term) :: t
def error(multi, name, value) do
add_operation(multi, name, {:error, value})
end
@doc """
Adds a function to run as part of the multi.
The function should return either `{:ok, value}` or `{:error, value}`,
and receives the repo as the first argument, and the changes so far
as the second argument.
## Example
Ecto.Multi.run(multi, :write, fn _repo, %{image: image} ->
with :ok <- File.write(image.name, image.contents) do
{:ok, nil}
end
end)
"""
@spec run(t, name, run) :: t
def run(multi, name, run) when is_function(run, 2) do
add_operation(multi, name, {:run, run})
end
@doc """
Adds a function to run as part of the multi.
Similar to `run/3`, but allows to pass module name, function and arguments.
The function should return either `{:ok, value}` or `{:error, value}`, and
receives the repo as the first argument, and the changes so far as the
second argument (prepended to those passed in the call to the function).
"""
@spec run(t, name, module, function, args) :: t when function: atom, args: [any]
def run(multi, name, mod, fun, args)
when is_atom(mod) and is_atom(fun) and is_list(args) do
add_operation(multi, name, {:run, {mod, fun, args}})
end
@doc """
Adds an insert_all operation to the multi.
Accepts the same arguments and options as `c:Ecto.Repo.insert_all/3` does.
## Example
posts = [%{title: "My first post"}, %{title: "My second post"}]
Ecto.Multi.new()
|> Ecto.Multi.insert_all(:insert_all, Post, posts)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.insert_all(:insert_all, Comment, fn %{post: post} ->
# Others validations
entries
|> Enum.map(fn comment ->
Map.put(comment, :post_id, post.id)
end)
end)
|> MyApp.Repo.transaction()
"""
@spec insert_all(
t,
name,
schema_or_source,
entries_or_query_or_fun :: [map | Keyword.t()] | fun([map | Keyword.t()]) | Ecto.Query.t(),
Keyword.t()
) :: t
def insert_all(multi, name, schema_or_source, entries_or_query_or_fun, opts \\ [])
def insert_all(multi, name, schema_or_source, entries_fun, opts)
when is_function(entries_fun, 1) and is_list(opts) do
run(multi, name, operation_fun({:insert_all, schema_or_source, entries_fun}, opts))
end
def insert_all(multi, name, schema_or_source, entries_or_query, opts) when is_list(opts) do
add_operation(multi, name, {:insert_all, schema_or_source, entries_or_query, opts})
end
@doc """
Adds an update_all operation to the multi.
Accepts the same arguments and options as `c:Ecto.Repo.update_all/3` does.
## Example
Ecto.Multi.new()
|> Ecto.Multi.update_all(:update_all, Post, set: [title: "New title"])
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.update_all(:update_all, fn %{post: post} ->
# Others validations
from(c in Comment, where: c.post_id == ^post.id, update: [set: [title: "New title"]])
end, [])
|> MyApp.Repo.transaction()
"""
@spec update_all(t, name, Ecto.Queryable.t | fun(Ecto.Queryable.t), Keyword.t, Keyword.t) :: t
def update_all(multi, name, queryable_or_fun, updates, opts \\ [])
def update_all(multi, name, queryable_fun, updates, opts) when is_function(queryable_fun, 1) and is_list(opts) do
run(multi, name, operation_fun({:update_all, queryable_fun, updates}, opts))
end
def update_all(multi, name, queryable, updates, opts) when is_list(opts) do
query = Ecto.Queryable.to_query(queryable)
add_operation(multi, name, {:update_all, query, updates, opts})
end
@doc """
Adds a delete_all operation to the multi.
Accepts the same arguments and options as `c:Ecto.Repo.delete_all/2` does.
## Example
queryable = from(p in Post, where: p.id < 5)
Ecto.Multi.new()
|> Ecto.Multi.delete_all(:delete_all, queryable)
|> MyApp.Repo.transaction()
Ecto.Multi.new()
|> Ecto.Multi.run(:post, fn repo, _changes ->
case repo.get(Post, 1) do
nil -> {:error, :not_found}
post -> {:ok, post}
end
end)
|> Ecto.Multi.delete_all(:delete_all, fn %{post: post} ->
# Others validations
from(c in Comment, where: c.post_id == ^post.id)
end)
|> MyApp.Repo.transaction()
"""
@spec delete_all(t, name, Ecto.Queryable.t | fun(Ecto.Queryable.t), Keyword.t) :: t
def delete_all(multi, name, queryable_or_fun, opts \\ [])
def delete_all(multi, name, fun, opts) when is_function(fun, 1) and is_list(opts) do
run(multi, name, operation_fun({:delete_all, fun}, opts))
end
def delete_all(multi, name, queryable, opts) when is_list(opts) do
query = Ecto.Queryable.to_query(queryable)
add_operation(multi, name, {:delete_all, query, opts})
end
defp add_operation(%Multi{} = multi, name, operation) do
%{operations: operations, names: names} = multi
if MapSet.member?(names, name) do
raise "#{Kernel.inspect name} is already a member of the Ecto.Multi: \n#{Kernel.inspect multi}"
else
%{multi | operations: [{name, operation} | operations],
names: MapSet.put(names, name)}
end
end
@doc """
Returns the list of operations stored in `multi`.
Always use this function when you need to access the operations you
have defined in `Ecto.Multi`. Inspecting the `Ecto.Multi` struct internals
directly is discouraged.
"""
@spec to_list(t) :: [{name, term}]
def to_list(%Multi{operations: operations}) do
operations
|> Enum.reverse
|> Enum.map(&format_operation/1)
end
defp format_operation({name, {:changeset, changeset, opts}}),
do: {name, {changeset.action, changeset, opts}}
defp format_operation(other),
do: other
@doc """
Adds a value to the changes so far under the given name.
## Example
Ecto.Multi.new()
|> Ecto.Multi.put(:params, params)
|> Ecto.Multi.insert(:user, fn changes -> User.changeset(changes.params) end)
|> Ecto.Multi.insert(:person, fn changes -> Person.changeset(changes.user, changes.params) end)
|> MyApp.Repo.transaction()
"""
@spec put(t, name, any) :: t
def put(multi, name, value) do
add_operation(multi, name, {:put, value})
end
@doc """
Inspects results from a Multi
By default, the name is shown as a label to the inspect, custom labels are
supported through the `IO.inspect/2` `label` option.
## Options
All options for IO.inspect/2 are supported, it also support the following ones:
* `:only` - A field or a list of fields to inspect, will print the entire
map by default.
## Examples
Ecto.Multi.new()
|> Ecto.Multi.insert(:person_a, changeset)
|> Ecto.Multi.insert(:person_b, changeset)
|> Ecto.Multi.inspect()
|> MyApp.Repo.transaction()
Prints:
%{person_a: %Person{...}, person_b: %Person{...}}
We can use the `:only` option to limit which fields will be printed:
Ecto.Multi.new()
|> Ecto.Multi.insert(:person_a, changeset)
|> Ecto.Multi.insert(:person_b, changeset)
|> Ecto.Multi.inspect(only: :person_a)
|> MyApp.Repo.transaction()
Prints:
%{person_a: %Person{...}}
"""
@spec inspect(t, Keyword.t) :: t
def inspect(multi, opts \\ []) do
Map.update!(multi, :operations, &[{:inspect, {:inspect, opts}} | &1])
end
@doc false
@spec __apply__(t, Ecto.Repo.t, fun, (term -> no_return)) :: {:ok, term} | {:error, term}
def __apply__(%Multi{} = multi, repo, wrap, return) do
operations = Enum.reverse(multi.operations)
with {:ok, operations} <- check_operations_valid(operations) do
apply_operations(operations, multi.names, repo, wrap, return)
end
end
defp check_operations_valid(operations) do
Enum.find_value(operations, &invalid_operation/1) || {:ok, operations}
end
defp invalid_operation({name, {:changeset, %{valid?: false} = changeset, _}}),
do: {:error, {name, changeset, %{}}}
defp invalid_operation({name, {:error, value}}),
do: {:error, {name, value, %{}}}
defp invalid_operation(_operation),
do: nil
defp apply_operations([], _names, _repo, _wrap, _return), do: {:ok, %{}}
defp apply_operations(operations, names, repo, wrap, return) do
wrap.(fn ->
operations
|> Enum.reduce({%{}, names}, &apply_operation(&1, repo, wrap, return, &2))
|> elem(0)
end)
end
defp apply_operation({_, {:merge, merge}}, repo, wrap, return, {acc, names}) do
case __apply__(apply_merge_fun(merge, acc), repo, wrap, return) do
{:ok, value} ->
merge_results(acc, value, names)
{:error, {name, value, nested_acc}} ->
{acc, _names} = merge_results(acc, nested_acc, names)
return.({name, value, acc})
end
end
defp apply_operation({_name, {:inspect, opts}}, _repo, _wrap_, _return, {acc, names}) do
if opts[:only] do
acc |> Map.take(List.wrap(opts[:only])) |> IO.inspect(opts)
else
IO.inspect(acc, opts)
end
{acc, names}
end
defp apply_operation({name, operation}, repo, wrap, return, {acc, names}) do
case apply_operation(operation, acc, {wrap, return}, repo) do
{:ok, value} ->
{Map.put(acc, name, value), names}
{:error, value} ->
return.({name, value, acc})
other ->
raise "expected Ecto.Multi callback named `#{Kernel.inspect name}` to return either {:ok, value} or {:error, value}, got: #{Kernel.inspect other}"
end
end
defp apply_operation({:changeset, changeset, opts}, _acc, _apply_args, repo),
do: apply(repo, changeset.action, [changeset, opts])
defp apply_operation({:run, run}, acc, _apply_args, repo),
do: apply_run_fun(run, repo, acc)
defp apply_operation({:error, value}, _acc, _apply_args, _repo),
do: {:error, value}
defp apply_operation({:insert_all, source, entries, opts}, _acc, _apply_args, repo),
do: {:ok, repo.insert_all(source, entries, opts)}
defp apply_operation({:update_all, query, updates, opts}, _acc, _apply_args, repo),
do: {:ok, repo.update_all(query, updates, opts)}
defp apply_operation({:delete_all, query, opts}, _acc, _apply_args, repo),
do: {:ok, repo.delete_all(query, opts)}
defp apply_operation({:put, value}, _acc, _apply_args, _repo),
do: {:ok, value}
defp apply_merge_fun({mod, fun, args}, acc), do: apply(mod, fun, [acc | args])
defp apply_merge_fun(fun, acc), do: apply(fun, [acc])
defp apply_run_fun({mod, fun, args}, repo, acc), do: apply(mod, fun, [repo, acc | args])
defp apply_run_fun(fun, repo, acc), do: apply(fun, [repo, acc])
defp merge_results(changes, new_changes, names) do
new_names = new_changes |> Map.keys |> MapSet.new()
case MapSet.intersection(names, new_names) |> MapSet.to_list do
[] ->
{Map.merge(changes, new_changes), MapSet.union(names, new_names)}
common ->
raise "cannot merge multi, the following operations were found in " <>
"both Ecto.Multi: #{Kernel.inspect common}"
end
end
defp operation_fun({:update_all, queryable_fun, updates}, opts) do
fn repo, changes ->
{:ok, repo.update_all(queryable_fun.(changes), updates, opts)}
end
end
defp operation_fun({:insert_all, schema_or_source, entries_fun}, opts) do
fn repo, changes ->
{:ok, repo.insert_all(schema_or_source, entries_fun.(changes), opts)}
end
end
defp operation_fun({:delete_all, fun}, opts) do
fn repo, changes ->
{:ok, repo.delete_all(fun.(changes), opts)}
end
end
defp operation_fun({operation, fun}, opts) do
fn repo, changes ->
apply(repo, operation, [fun.(changes), opts])
end
end
end
| 33.82256 | 154 | 0.644046 |
7360a17e06acfb8f91aa826b2f99e0461d8d6ebf | 2,725 | exs | Elixir | test/pos_web/controllers/order_controller_test.exs | ancarvalho/backend-elixir | e42c22ae0881d80336a60dc6c87d4786db97c7a8 | [
"MIT"
] | null | null | null | test/pos_web/controllers/order_controller_test.exs | ancarvalho/backend-elixir | e42c22ae0881d80336a60dc6c87d4786db97c7a8 | [
"MIT"
] | null | null | null | test/pos_web/controllers/order_controller_test.exs | ancarvalho/backend-elixir | e42c22ae0881d80336a60dc6c87d4786db97c7a8 | [
"MIT"
] | null | null | null | defmodule PosWeb.OrderControllerTest do
use PosWeb.ConnCase
alias Pos.Requests
alias Pos.Requests.Order
@create_attrs %{
requests: [],
table: 42,
waitress_id: "some waitress_id"
}
@update_attrs %{
requests: [],
table: 43,
waitress_id: "some updated waitress_id"
}
@invalid_attrs %{requests: nil, table: nil, waitress_id: nil}
def fixture(:order) do
{:ok, order} = Requests.create_order(@create_attrs)
order
end
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
describe "index" do
test "lists all orders", %{conn: conn} do
conn = get(conn, Routes.order_path(conn, :index))
assert json_response(conn, 200)["data"] == []
end
end
describe "create order" do
test "renders order when data is valid", %{conn: conn} do
conn = post(conn, Routes.order_path(conn, :create), order: @create_attrs)
assert %{"id" => id} = json_response(conn, 201)["data"]
conn = get(conn, Routes.order_path(conn, :show, id))
assert %{
"id" => id,
"requests" => [],
"table" => 42,
"waitress_id" => "some waitress_id"
} = json_response(conn, 200)["data"]
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.order_path(conn, :create), order: @invalid_attrs)
assert json_response(conn, 422)["errors"] != %{}
end
end
describe "update order" do
setup [:create_order]
test "renders order when data is valid", %{conn: conn, order: %Order{id: id} = order} do
conn = put(conn, Routes.order_path(conn, :update, order), order: @update_attrs)
assert %{"id" => ^id} = json_response(conn, 200)["data"]
conn = get(conn, Routes.order_path(conn, :show, id))
assert %{
"id" => id,
"requests" => [],
"table" => 43,
"waitress_id" => "some updated waitress_id"
} = json_response(conn, 200)["data"]
end
test "renders errors when data is invalid", %{conn: conn, order: order} do
conn = put(conn, Routes.order_path(conn, :update, order), order: @invalid_attrs)
assert json_response(conn, 422)["errors"] != %{}
end
end
describe "delete order" do
setup [:create_order]
test "deletes chosen order", %{conn: conn, order: order} do
conn = delete(conn, Routes.order_path(conn, :delete, order))
assert response(conn, 204)
assert_error_sent 404, fn ->
get(conn, Routes.order_path(conn, :show, order))
end
end
end
defp create_order(_) do
order = fixture(:order)
%{order: order}
end
end
| 28.092784 | 92 | 0.59633 |
7360ac64a212692b5512556acbe25a49c11cb0cd | 2,657 | exs | Elixir | test/dark_matter/enums_test.exs | dark-elixir/dark_matter | 3f70edf4220ad1c066489110ef30880a143522fd | [
"Apache-2.0"
] | 2 | 2020-12-01T21:33:44.000Z | 2021-05-29T14:51:18.000Z | test/dark_matter/enums_test.exs | dark-elixir/dark_matter | 3f70edf4220ad1c066489110ef30880a143522fd | [
"Apache-2.0"
] | null | null | null | test/dark_matter/enums_test.exs | dark-elixir/dark_matter | 3f70edf4220ad1c066489110ef30880a143522fd | [
"Apache-2.0"
] | 2 | 2020-09-02T14:36:58.000Z | 2021-04-22T11:20:43.000Z | defmodule DarkMatter.EnumsTest.TestEctoStruct do
@moduledoc false
defstruct [:id, :name, :__meta__]
end
defmodule DarkMatter.EnumsTest do
@moduledoc """
Test for DarkMatter.Enums
"""
use ExUnit.Case, async: true
alias __MODULE__.TestEctoStruct
alias DarkMatter.Enums
describe ".jsonify/1" do
@cases [
{nil, nil},
{1, 1},
{1.5, 1.5},
{[], []},
{%{}, %{}},
{%{date: ~D[2020-01-01]}, %{date: "2020-01-01"}},
{%{datetime: ~U[2020-05-14 21:01:03.007183Z]}, %{datetime: "2020-05-14T21:01:03.007183Z"}},
{%{decimal_normal: Decimal.new("1.2345")}, %{decimal_normal: "1.2345"}},
{%{decimal_scientific: Decimal.new("1e3")}, %{decimal_scientific: "1000"}},
{%TestEctoStruct{}, %{id: nil, name: nil}},
{%{nested: %TestEctoStruct{}}, %{nested: %{id: nil, name: nil}}},
{{1, 2}, [1, 2]},
{[{"a", "b"}, {:a, "b"}], %{:a => "b", "a" => "b"}},
# NOTE: the case below inserts `1` at the `0` index
{[{}, %{}, [1, abc: 23]], [[], %{}, [1, [:abc, 23]]]}
]
for {given, expected} <- @cases do
test "with #{inspect(given)} it returns #{inspect(expected)}" do
assert Enums.jsonify(unquote(Macro.escape(given))) == unquote(Macro.escape(expected))
end
test "with #{inspect(given)} it is encodable" do
assert {:ok, _} = Jason.encode(Enums.jsonify(unquote(Macro.escape(given))))
end
end
end
describe ".stringify/1" do
@cases [
{nil, nil},
{1, 1},
{1.5, 1.5},
{[], []},
{%{}, %{}},
{%{date: ~D[2020-01-01]}, %{"date" => "2020-01-01"}},
{%{datetime: ~U[2020-05-14 21:01:03.007183Z]},
%{"datetime" => "2020-05-14T21:01:03.007183Z"}},
{%{decimal_normal: Decimal.new("1.2345")}, %{"decimal_normal" => "1.2345"}},
{%{decimal_scientific: Decimal.new("1e3")}, %{"decimal_scientific" => "1000"}},
{%TestEctoStruct{}, %{"id" => nil, "name" => nil}},
{%{nested: %TestEctoStruct{}}, %{"nested" => %{"id" => nil, "name" => nil}}},
{{1, 2}, [1, 2]},
# NOTE: Overwriting keys
{[{"a", "a"}, {:a, "b"}], %{"a" => "a"}},
# NOTE: the case below inserts `1` at the `0` index
{[{}, %{}, [1, abc: 23]], [[], %{}, [1, ["abc", 23]]]}
]
for {given, expected} <- @cases do
test "with #{inspect(given)} it returns #{inspect(expected)}" do
assert Enums.stringify(unquote(Macro.escape(given))) == unquote(Macro.escape(expected))
end
test "with #{inspect(given)} it is encodable" do
assert {:ok, _} = Jason.encode(Enums.stringify(unquote(Macro.escape(given))))
end
end
end
end
| 33.632911 | 97 | 0.529168 |
7360b1880ac2f244f6b88137015f81fca85fbcfa | 21,630 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/snapshots.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/compute/lib/google_api/compute/v1/api/snapshots.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/snapshots.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 "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 elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.Compute.V1.Api.Snapshots do
@moduledoc """
API calls for all endpoints tagged `Snapshots`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Deletes the specified Snapshot resource. Keep in mind that deleting a single snapshot might not necessarily delete all the data on that snapshot. If any data on the snapshot that is marked for deletion is needed for subsequent snapshots, the data will be moved to the next corresponding snapshot.
For more information, see Deleting snapshots.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `snapshot` (*type:* `String.t`) - Name of the Snapshot resource to delete.
* `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.
* `:requestId` (*type:* `String.t`) - An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed.
For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments.
The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000).
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_delete(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_delete(connection, project, snapshot, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:requestId => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/global/snapshots/{snapshot}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"snapshot" => URI.encode(snapshot, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns the specified Snapshot resource. Gets a list of available snapshots by making a list() request.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `snapshot` (*type:* `String.t`) - Name of the Snapshot resource to return.
* `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.Compute.V1.Model.Snapshot{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_get(Tesla.Env.client(), String.t(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.Snapshot.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_get(connection, project, snapshot, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/snapshots/{snapshot}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"snapshot" => URI.encode(snapshot, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Snapshot{}])
end
@doc """
Gets the access control policy for a resource. May be empty if no such policy or resource exists.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `resource` (*type:* `String.t`) - Name or id of the resource for this request.
* `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.Compute.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_get_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_get_iam_policy(
connection,
project,
resource,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/snapshots/{resource}/getIamPolicy", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}])
end
@doc """
Retrieves the list of Snapshot resources contained within the specified project.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `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.
* `:filter` (*type:* `String.t`) - A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either =, !=, >, or <.
For example, if you are filtering Compute Engine instances, you can exclude instances named example-instance by specifying name != example-instance.
You can also filter nested fields. For example, you could specify scheduling.automaticRestart = false to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels.
To filter on multiple expressions, provide each separate expression within parentheses. For example, (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake"). By default, each expression is an AND expression. However, you can include AND and OR expressions explicitly. For example, (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true).
* `:maxResults` (*type:* `integer()`) - The maximum number of results per page that should be returned. If the number of available results is larger than maxResults, Compute Engine returns a nextPageToken that can be used to get the next page of results in subsequent list requests. Acceptable values are 0 to 500, inclusive. (Default: 500)
* `:orderBy` (*type:* `String.t`) - Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name.
You can also sort results in descending order based on the creation timestamp using orderBy="creationTimestamp desc". This sorts results based on the creationTimestamp field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first.
Currently, only sorting by name or creationTimestamp desc is supported.
* `:pageToken` (*type:* `String.t`) - Specifies a page token to use. Set pageToken to the nextPageToken returned by a previous list request to get the next page of results.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.SnapshotList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_list(Tesla.Env.client(), String.t(), keyword(), keyword()) ::
{:ok, GoogleApi.Compute.V1.Model.SnapshotList.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_list(connection, project, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:filter => :query,
:maxResults => :query,
:orderBy => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/{project}/global/snapshots", %{
"project" => URI.encode(project, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.SnapshotList{}])
end
@doc """
Sets the access control policy on the specified resource. Replaces any existing policy.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `resource` (*type:* `String.t`) - Name or id of the resource for this request.
* `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.Compute.V1.Model.GlobalSetPolicyRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Policy{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_set_iam_policy(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Policy.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_set_iam_policy(
connection,
project,
resource,
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("/{project}/global/snapshots/{resource}/setIamPolicy", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Policy{}])
end
@doc """
Sets the labels on a snapshot. To learn more about labels, read the Labeling Resources documentation.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `resource` (*type:* `String.t`) - Name or id of the resource for this request.
* `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.Compute.V1.Model.GlobalSetLabelsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_set_labels(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_set_labels(
connection,
project,
resource,
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("/{project}/global/snapshots/{resource}/setLabels", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Returns permissions that a caller has on the specified resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `resource` (*type:* `String.t`) - Name or id of the resource for this request.
* `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.Compute.V1.Model.TestPermissionsRequest.t`) -
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}}` on success
* `{:error, info}` on failure
"""
@spec compute_snapshots_test_iam_permissions(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.TestPermissionsResponse.t()} | {:error, Tesla.Env.t()}
def compute_snapshots_test_iam_permissions(
connection,
project,
resource,
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("/{project}/global/snapshots/{resource}/testIamPermissions", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"resource" => URI.encode(resource, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.TestPermissionsResponse{}])
end
end
| 47.960089 | 414 | 0.644938 |
7361031d2b40fb960f54fda83c021c329f27de9e | 53 | exs | Elixir | config/dev.exs | ktec/assert_html | 07aecb5bf564a6c17a278d09724d793d89e00919 | [
"MIT"
] | 7 | 2019-04-19T23:52:12.000Z | 2022-03-14T22:17:30.000Z | config/dev.exs | ktec/assert_html | 07aecb5bf564a6c17a278d09724d793d89e00919 | [
"MIT"
] | 1 | 2019-04-12T09:00:27.000Z | 2019-04-12T09:00:27.000Z | config/dev.exs | ktec/assert_html | 07aecb5bf564a6c17a278d09724d793d89e00919 | [
"MIT"
] | 4 | 2019-02-26T15:58:55.000Z | 2020-09-28T13:45:38.000Z | use Mix.Config
config :assert_html,
log_dsl: true
| 10.6 | 20 | 0.754717 |
73612fff75dcb30f2315526d917f235c6a462fa9 | 416 | ex | Elixir | lib/home_web/plugs/auth_plug.ex | marktermaat/home_bot | b6d0bd5e1e97b2b0c95e201618e27de4259378d3 | [
"MIT"
] | null | null | null | lib/home_web/plugs/auth_plug.ex | marktermaat/home_bot | b6d0bd5e1e97b2b0c95e201618e27de4259378d3 | [
"MIT"
] | null | null | null | lib/home_web/plugs/auth_plug.ex | marktermaat/home_bot | b6d0bd5e1e97b2b0c95e201618e27de4259378d3 | [
"MIT"
] | null | null | null | defmodule HomeWeb.Plugs.AuthPlug do
import Plug.Conn
import Phoenix.Controller
alias HomeWeb.Router.Helpers
def init(_params) do
end
def call(conn, _params) do
logged_in = Plug.Conn.get_session(conn, :logged_in)
if logged_in do
conn
else
conn
|> put_flash(:error, "Not logged in")
|> redirect(to: Helpers.login_path(conn, :index))
|> halt()
end
end
end
| 18.909091 | 55 | 0.653846 |
736131771e8557bd425df20eee49822384209fc9 | 738 | ex | Elixir | host_core/lib/host_core/refmaps/manager.ex | sleipnir/wasmcloud-otp | aef10f2f07257e65c527be6030006aaed2b85ff9 | [
"Apache-2.0"
] | null | null | null | host_core/lib/host_core/refmaps/manager.ex | sleipnir/wasmcloud-otp | aef10f2f07257e65c527be6030006aaed2b85ff9 | [
"Apache-2.0"
] | null | null | null | host_core/lib/host_core/refmaps/manager.ex | sleipnir/wasmcloud-otp | aef10f2f07257e65c527be6030006aaed2b85ff9 | [
"Apache-2.0"
] | null | null | null | defmodule HostCore.Refmaps.Manager do
require Logger
def lookup_refmap(oci_url) do
case :ets.lookup(:refmap_table, oci_url) do
[pk] -> {:ok, pk}
[] -> :error
end
end
def cache_refmap(oci_url, public_key) do
:ets.insert(:refmap_table, {oci_url, public_key})
end
def put_refmap(oci_url, public_key) do
cache_refmap(oci_url, public_key)
publish_refmap(oci_url, public_key)
end
def publish_refmap(oci_url, public_key) do
Logger.debug("Publishing ref map")
prefix = HostCore.Host.lattice_prefix()
topic = "lc.#{prefix}.ocimap.#{HostCore.Nats.sanitize_for_topic(oci_url)}"
Gnat.pub(:control_nats, topic, Jason.encode!(%{oci_url: oci_url, public_key: public_key}))
end
end
| 25.448276 | 94 | 0.701897 |
73615f49767c0516e48c162fe7629d86ec86091b | 1,409 | ex | Elixir | test/support/data_case.ex | trewdys/source-academy2-debug | 6146e1fac81472184877f47aa32dee7fdceb4fb6 | [
"Unlicense"
] | null | null | null | test/support/data_case.ex | trewdys/source-academy2-debug | 6146e1fac81472184877f47aa32dee7fdceb4fb6 | [
"Unlicense"
] | null | null | null | test/support/data_case.ex | trewdys/source-academy2-debug | 6146e1fac81472184877f47aa32dee7fdceb4fb6 | [
"Unlicense"
] | null | null | null | defmodule SourceAcademy.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
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.
"""
alias Ecto.Adapters.SQL.Sandbox
alias Ecto.Changeset
alias SourceAcademy.Repo
use ExUnit.CaseTemplate
using do
quote do
alias SourceAcademy.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import SourceAcademy.DataCase
end
end
setup tags do
:ok = Sandbox.checkout(Repo)
unless tags[:async] do
Sandbox.mode(Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transform changeset errors to a map of messages.
changeset = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Changeset.traverse_errors(changeset, fn {message, opts} ->
Enum.reduce(opts, message, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
end
end
| 25.160714 | 74 | 0.685593 |
736176cf54aa12623c443baae55dae2f4f57c3ca | 1,009 | ex | Elixir | elixir/fibo45/lib/fibo45.ex | gmelodie/learning | 4d33f1f8a26f74bc959a769ede1acbf00da9351b | [
"MIT"
] | null | null | null | elixir/fibo45/lib/fibo45.ex | gmelodie/learning | 4d33f1f8a26f74bc959a769ede1acbf00da9351b | [
"MIT"
] | null | null | null | elixir/fibo45/lib/fibo45.ex | gmelodie/learning | 4d33f1f8a26f74bc959a769ede1acbf00da9351b | [
"MIT"
] | null | null | null | require Time
defmodule Fibo45 do
@correct_45th_number 1134903170
def fibo(stop_idx, curr_idx \\ 3, last_num \\ 1, second_to_last_num \\ 1)
def fibo(stop_idx, curr_idx, last_num, _) when curr_idx == stop_idx + 1 do last_num end
def fibo(stop_idx, _, _, _) when stop_idx == 1 do 1 end
def fibo(stop_idx, _, _, _) when stop_idx == 2 do 1 end
def fibo(stop_idx, _, _, _) when stop_idx < 1 do
raise ArgumentError, message: "Invalid stop index. Needs to be higher than 0"
end
def fibo(stop_idx, curr_idx, last_num, second_to_last_num) do
curr_num = last_num + second_to_last_num
fibo(stop_idx, curr_idx+1, curr_num, last_num)
end
def find do
fibo(45)
end
def time do
start = Time.utc_now()
ans = find()
if ans != @correct_45th_number do
IO.puts("Incorrect number! Expected #{} got #{}")
end
stop = Time.utc_now()
runtime = Time.diff(stop, start, :microsecond)
IO.puts("Number calculated in #{runtime} microseconds (1e-6s)")
end
end
| 28.027778 | 89 | 0.67889 |
73617b9f4b5f9c02fd593e4acffb664003d6f32c | 4,108 | ex | Elixir | lib/vintage_net/power_manager/state_machine.ex | axelson/vintage_net | 68866ff223fa40e7ad6fd4d9fb2f7960cf51b1ca | [
"Apache-2.0"
] | 85 | 2019-05-09T14:54:38.000Z | 2022-02-08T16:52:04.000Z | lib/vintage_net/power_manager/state_machine.ex | axelson/vintage_net | 68866ff223fa40e7ad6fd4d9fb2f7960cf51b1ca | [
"Apache-2.0"
] | 132 | 2019-05-09T15:57:59.000Z | 2022-02-28T16:31:22.000Z | lib/vintage_net/power_manager/state_machine.ex | axelson/vintage_net | 68866ff223fa40e7ad6fd4d9fb2f7960cf51b1ca | [
"Apache-2.0"
] | 14 | 2019-07-08T19:18:23.000Z | 2022-02-08T16:52:05.000Z | defmodule VintageNet.PowerManager.StateMachine do
@moduledoc false
# Power management state machine implementation
#
# This is a side effect free implementation of the power management state machine
# to make it easier to test. VintageNet.PowerManager.PMControl does what this module
# tells it to do.
#
# See assets/power_manager_state_machine.png for the picture.
#
# If you're reading this and have seen someone nicely embed a graphviz
# state machine in hex docs, please let me know!
@type state() ::
:on_hold
| :on
| :waiting_to_power_off
| :powering_off
| :resetting
| :waiting_to_power_on
| :off_hold
| :off
@type action() ::
:start_powering_off
| :power_off
| :power_on
| :start_transient_timer
| :start_watchdog_timer
@type actions() :: [action()]
@spec init() :: :off
def init() do
:off
end
@spec power_on(state()) :: {state(), actions()}
def power_on(state) do
handle(state, :power_on)
end
@spec power_off(state()) :: {state(), actions()}
def power_off(state) do
handle(state, :power_off)
end
@spec timeout(state()) :: {state(), actions()}
def timeout(state) do
handle(state, :timeout)
end
@spec pet_watchdog(state()) :: {state(), actions()}
def pet_watchdog(state) do
handle(state, :pet_watchdog)
end
@spec force_reset(state()) :: {state(), actions()}
def force_reset(state) do
handle(state, :force_reset)
end
@spec info(state(), non_neg_integer()) :: String.t()
def info(state, time_left) do
handle(state, {:info, time_left})
end
# on_hold
defp handle(:on_hold, :timeout) do
{:on, [:start_watchdog_timer]}
end
defp handle(:on_hold, :power_off) do
{:waiting_to_power_off, []}
end
defp handle(:on_hold, :force_reset) do
{:resetting, [:start_powering_off]}
end
defp handle(:on_hold, {:info, time_left}) do
"Starting up/on (#{time_left} ms left)"
end
# waiting_to_power_off
defp handle(:waiting_to_power_off, :timeout) do
{:powering_off, [:start_powering_off]}
end
defp handle(:waiting_to_power_off, :power_on) do
{:on_hold, []}
end
defp handle(:waiting_to_power_off, {:info, time_left}) do
"Waiting to power off (#{time_left} ms left)"
end
# on
defp handle(:on, :timeout) do
{:resetting, [:start_powering_off]}
end
defp handle(:on, :power_off) do
{:waiting_to_power_off, [:start_transient_timer]}
end
defp handle(:on, :pet_watchdog) do
{:on, [:start_watchdog_timer]}
end
defp handle(:on, :force_reset) do
{:resetting, [:start_powering_off]}
end
defp handle(:on, {:info, time_left}) do
"On (watchdog timeout in #{time_left} ms)"
end
# resetting
defp handle(:resetting, :timeout) do
{:waiting_to_power_on, [:power_off]}
end
defp handle(:resetting, :power_off) do
{:powering_off, []}
end
defp handle(:resetting, {:info, time_left}) do
"Resetting in #{time_left} ms"
end
# powering_off
defp handle(:powering_off, :power_on) do
{:resetting, []}
end
defp handle(:powering_off, :timeout) do
{:off_hold, [:power_off]}
end
defp handle(:powering_off, {:info, time_left}) do
"Power off done in #{time_left} ms"
end
# waiting_to_power_on
defp handle(:waiting_to_power_on, :timeout) do
{:on_hold, [:power_on]}
end
defp handle(:waiting_to_power_on, :power_off) do
{:off_hold, []}
end
defp handle(:waiting_to_power_on, {:info, time_left}) do
"Will power on in #{time_left} ms"
end
# off_hold
defp handle(:off_hold, :timeout) do
{:off, []}
end
defp handle(:off_hold, :power_on) do
{:waiting_to_power_on, []}
end
defp handle(:off_hold, {:info, time_left}) do
"Off (OK to power on in #{time_left} ms)"
end
# off
defp handle(:off, :power_on) do
{:on_hold, [:power_on]}
end
defp handle(:off, {:info, _time_left}) do
"Off"
end
# Anything that wasn't handled is a no-op
defp handle(state, _event) do
{state, []}
end
end
| 22.086022 | 86 | 0.642162 |
73617d3cbeca35ea03e567cfd7aa8be1bec154a7 | 205 | exs | Elixir | config/test.exs | kianmeng/cldr_calendars_lunisolar | 5754991127fb74722e74e4fc8d0a27f86fc49029 | [
"Apache-2.0"
] | null | null | null | config/test.exs | kianmeng/cldr_calendars_lunisolar | 5754991127fb74722e74e4fc8d0a27f86fc49029 | [
"Apache-2.0"
] | null | null | null | config/test.exs | kianmeng/cldr_calendars_lunisolar | 5754991127fb74722e74e4fc8d0a27f86fc49029 | [
"Apache-2.0"
] | null | null | null | import Config
# Global config
config :ex_cldr,
default_locale: "en-001",
default_backend: MyApp.Cldr
config :ex_unit,
module_load_timeout: 220_000,
case_load_timeout: 220_000,
timeout: 120_000
| 17.083333 | 31 | 0.765854 |
73619a26f9c5c9b74c15613a90e5ed608034f773 | 2,194 | exs | Elixir | test/document_viewer_web/controllers/auth_controller_test.exs | arkadyan/document_viewer | d45594632b83559520820744e4afd37d3bfdb03d | [
"MIT"
] | 1 | 2021-03-17T19:04:28.000Z | 2021-03-17T19:04:28.000Z | test/document_viewer_web/controllers/auth_controller_test.exs | mbta/document_viewer | f3af972f4996759bc18811186f753b87bbe43b53 | [
"MIT"
] | 121 | 2021-03-18T21:03:02.000Z | 2022-03-28T09:24:49.000Z | test/document_viewer_web/controllers/auth_controller_test.exs | arkadyan/document_viewer | d45594632b83559520820744e4afd37d3bfdb03d | [
"MIT"
] | 1 | 2021-05-19T21:21:56.000Z | 2021-05-19T21:21:56.000Z | defmodule DocumentViewerWeb.AuthControllerTest do
use DocumentViewerWeb.ConnCase
use Plug.Test
import ExUnit.CaptureLog
import Test.Support.Helpers
@mock_auth %Ueberauth.Auth{
uid: "[email protected]",
credentials: %Ueberauth.Auth.Credentials{
expires_at: System.system_time(:second) + 1_000,
other: %{groups: ["test-group"]}
}
}
describe "GET /auth/:provider" do
test "redirects to the callback", %{conn: conn} do
conn = get(conn, "/auth/cognito")
assert redirected_to(conn) == "/auth/cognito/callback"
end
end
describe "GET /auth/:provider/callback" do
setup do
reassign_log_level(:info)
end
@tag capture_log: true
test "redirects to the index page for an ueberauth auth", %{conn: conn} do
conn =
conn
|> assign(:ueberauth_auth, @mock_auth)
|> get("/auth/cognito/callback")
assert redirected_to(conn) == "/"
assert Guardian.Plug.current_claims(conn)["groups"] == ["test-group"]
end
test "logs a successful login", %{conn: conn} do
log =
capture_log(fn ->
conn
|> assign(:ueberauth_auth, @mock_auth)
|> get("/auth/cognito/callback")
end)
assert log =~ "username=\"[email protected]\""
assert log =~ "action=:login"
end
@tag capture_log: true
test "redirects home for an ueberauth failure", %{conn: conn} do
conn =
conn
|> Plug.Test.init_test_session(%{username: "[email protected]"})
|> assign(:ueberauth_failure, %Ueberauth.Failure{
errors: [%Ueberauth.Failure.Error{message: "failed"}]
})
|> get("/auth/cognito/callback")
assert redirected_to(conn) == "https://www.mbta.com"
end
test "logs ueberauth failures", %{conn: conn} do
log =
capture_log(fn ->
conn
|> Plug.Test.init_test_session(%{username: "[email protected]"})
|> assign(:ueberauth_failure, %Ueberauth.Failure{
errors: [%Ueberauth.Failure.Error{message: "failed"}]
})
|> get("/auth/cognito/callback")
end)
assert log =~ "Ueberauth error: failed"
end
end
end
| 27.772152 | 78 | 0.60392 |
7361b805500bc99375b75d8cf1f66340335594d1 | 1,801 | ex | Elixir | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/authentication_token.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/authentication_token.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/android_enterprise/lib/google_api/android_enterprise/v1/model/authentication_token.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AndroidEnterprise.V1.Model.AuthenticationToken do
@moduledoc """
An AuthenticationToken is used by the EMM's device policy client on a device to provision the given EMM-managed user on that device.
## Attributes
* `kind` (*type:* `String.t`, *default:* `androidenterprise#authenticationToken`) -
* `token` (*type:* `String.t`, *default:* `nil`) - The authentication token to be passed to the device policy client on the device where it can be used to provision the account for which this token was generated.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:kind => String.t(),
:token => String.t()
}
field(:kind)
field(:token)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidEnterprise.V1.Model.AuthenticationToken do
def decode(value, options) do
GoogleApi.AndroidEnterprise.V1.Model.AuthenticationToken.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidEnterprise.V1.Model.AuthenticationToken do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.02 | 216 | 0.739589 |
7361bcf1411a8357fd90d913b1dd2a4fd828ad6c | 1,870 | ex | Elixir | clients/service_user/lib/google_api/service_user/v1/model/search_services_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/service_user/lib/google_api/service_user/v1/model/search_services_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/service_user/lib/google_api/service_user/v1/model/search_services_response.ex | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.ServiceUser.V1.Model.SearchServicesResponse do
@moduledoc """
Response message for SearchServices method.
## Attributes
- nextPageToken (String.t): Token that can be passed to `ListAvailableServices` to resume a paginated query. Defaults to: `null`.
- services ([PublishedService]): Services available publicly or available to the authenticated caller. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:nextPageToken => any(),
:services => list(GoogleApi.ServiceUser.V1.Model.PublishedService.t())
}
field(:nextPageToken)
field(:services, as: GoogleApi.ServiceUser.V1.Model.PublishedService, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceUser.V1.Model.SearchServicesResponse do
def decode(value, options) do
GoogleApi.ServiceUser.V1.Model.SearchServicesResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceUser.V1.Model.SearchServicesResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.666667 | 141 | 0.754545 |
7361c905d4dd0fd274a292dd8e3bd408cca19ce8 | 1,361 | ex | Elixir | web/controllers/auth_controller.ex | beccanelson/8th-light-library | d0aa70371ca7645abf8609b53202ebb1808ca633 | [
"MIT"
] | null | null | null | web/controllers/auth_controller.ex | beccanelson/8th-light-library | d0aa70371ca7645abf8609b53202ebb1808ca633 | [
"MIT"
] | 9 | 2016-09-22T20:30:22.000Z | 2016-09-22T21:00:53.000Z | web/controllers/auth_controller.ex | beccanelson/library | d0aa70371ca7645abf8609b53202ebb1808ca633 | [
"MIT"
] | null | null | null | defmodule Bookish.AuthController do
use Bookish.Web, :controller
plug Ueberauth
alias Ueberauth.Strategy.Helpers
alias Bookish.User
def request(conn, _params) do
render(conn, "request.html", callback_url: Helpers.callback_url(conn))
end
def delete(conn, _params) do
conn
|> configure_session(drop: true)
|> put_flash(:info, "You have been logged out!")
|> redirect(to: "/")
end
def callback(%{assigns: %{ueberauth_failure: fails}} = conn, params) do
IO.puts "Authentication failed"
IO.inspect fails
IO.inspect params
conn
|> put_flash(:error, "Failed to authenticate.")
|> redirect(to: "/")
end
def callback(%{assigns: %{ueberauth_auth: auth}} = conn, params) do
IO.puts "Authentication succeeded for #{auth.info.name}"
IO.inspect params
case User.find_or_create(auth) do
{:ok, user} ->
path = get_path(conn)
conn
|> put_flash(:info, "Authentication successful.")
|> put_session(:current_user, user)
|> redirect(to: path)
end
end
def get_user(conn) do
get_session(conn, :current_user) || conn.assigns[:current_user]
end
defp get_path(conn) do
if get_session(conn, :redirect_method) in ["POST", "PUT", "DELETE"] do
"/book_records"
else
get_session(conn, :redirect_url) || "/"
end
end
end
| 25.203704 | 74 | 0.649522 |
7361d0f68cb7c4fbb8a1b6b6925e6178f7a3c06b | 5,695 | exs | Elixir | mix.exs | starkeepers/phoenix | 3e04a29a90a0d256aae50f7953733a4f83177002 | [
"MIT"
] | null | null | null | mix.exs | starkeepers/phoenix | 3e04a29a90a0d256aae50f7953733a4f83177002 | [
"MIT"
] | null | null | null | mix.exs | starkeepers/phoenix | 3e04a29a90a0d256aae50f7953733a4f83177002 | [
"MIT"
] | null | null | null | defmodule Phoenix.MixProject do
use Mix.Project
@version "1.6.0-rc.0"
@scm_url "https://github.com/phoenixframework/phoenix"
# If the elixir requirement is updated, we need to make the installer
# use at least the minimum requirement used here. Although often the
# installer is ahead of Phoenix itself.
@elixir_requirement "~> 1.9"
def project do
[
app: :phoenix,
version: @version,
elixir: @elixir_requirement,
deps: deps(),
package: package(),
preferred_cli_env: [docs: :docs],
consolidate_protocols: Mix.env() != :test,
xref: [
exclude: [
{IEx, :started?, 0},
Ecto.Type,
:ranch,
:cowboy_req,
Plug.Cowboy.Conn,
Plug.Cowboy
]
],
elixirc_paths: elixirc_paths(Mix.env()),
name: "Phoenix",
docs: docs(),
aliases: aliases(),
source_url: @scm_url,
homepage_url: "https://www.phoenixframework.org",
description: """
Productive. Reliable. Fast. A productive web framework that
does not compromise speed or maintainability.
"""
]
end
defp elixirc_paths(:docs), do: ["lib", "installer/lib"]
defp elixirc_paths(_), do: ["lib"]
def application do
[
mod: {Phoenix, []},
extra_applications: [:logger, :eex, :crypto, :public_key],
env: [
logger: true,
stacktrace_depth: nil,
filter_parameters: ["password"],
serve_endpoints: false,
gzippable_exts: ~w(.js .map .css .txt .text .html .json .svg .eot .ttf),
static_compressors: [Phoenix.Digester.Gzip]
]
]
end
defp deps do
[
{:plug, "~> 1.10"},
{:plug_crypto, "~> 1.2"},
{:telemetry, "~> 0.4 or ~> 1.0"},
{:phoenix_pubsub, "~> 2.0"},
{:phoenix_view, "~> 1.0"},
# Optional deps
{:plug_cowboy, "~> 2.2", optional: true},
{:jason, "~> 1.0", optional: true},
# Docs dependencies (some for cross references)
{:ex_doc, "~> 0.24", only: :docs},
{:ecto, "~> 3.0", only: :docs},
{:ecto_sql, "~> 3.6", only: :docs},
{:gettext, "~> 0.18", only: :docs},
{:telemetry_poller, "~> 1.0", only: :docs},
{:telemetry_metrics, "~> 0.6", only: :docs},
# Test dependencies
{:phoenix_html, "~> 3.0", only: :test},
{:phx_new, path: "./installer", only: :test},
{:websocket_client, git: "https://github.com/jeremyong/websocket_client.git", only: :test},
# Dev dependencies
{:esbuild, "~> 0.1", only: :dev}
]
end
defp package do
[
maintainers: ["Chris McCord", "José Valim", "Gary Rennie", "Jason Stiebs"],
licenses: ["MIT"],
links: %{"GitHub" => @scm_url},
files:
~w(assets/js lib priv CHANGELOG.md LICENSE.md mix.exs package.json README.md .formatter.exs)
]
end
defp docs do
[
source_ref: "v#{@version}",
main: "overview",
logo: "logo.png",
extra_section: "GUIDES",
assets: "guides/assets",
formatters: ["html", "epub"],
groups_for_modules: groups_for_modules(),
extras: extras(),
groups_for_extras: groups_for_extras()
]
end
defp extras do
[
"guides/introduction/overview.md",
"guides/introduction/installation.md",
"guides/introduction/up_and_running.md",
"guides/introduction/community.md",
"guides/directory_structure.md",
"guides/request_lifecycle.md",
"guides/plug.md",
"guides/routing.md",
"guides/controllers.md",
"guides/views.md",
"guides/ecto.md",
"guides/contexts.md",
"guides/mix_tasks.md",
"guides/telemetry.md",
"guides/asset_management.md",
"guides/authentication/mix_phx_gen_auth.md",
"guides/channels/channels.md",
"guides/channels/presence.md",
"guides/testing/testing.md",
"guides/testing/testing_contexts.md",
"guides/testing/testing_controllers.md",
"guides/testing/testing_channels.md",
"guides/deployment/deployment.md",
"guides/deployment/releases.md",
"guides/deployment/gigalixir.md",
"guides/deployment/fly.md",
"guides/deployment/heroku.md",
"guides/howto/custom_error_pages.md",
"guides/howto/using_ssl.md"
]
end
defp groups_for_extras do
[
Introduction: ~r/guides\/introduction\/.?/,
Guides: ~r/guides\/[^\/]+\.md/,
Authentication: ~r/guides\/authentication\/.?/,
Channels: ~r/guides\/channels\/.?/,
Testing: ~r/guides\/testing\/.?/,
Deployment: ~r/guides\/deployment\/.?/,
"How-to's": ~r/guides\/howto\/.?/
]
end
defp groups_for_modules do
# Ungrouped Modules:
#
# Phoenix
# Phoenix.Channel
# Phoenix.Controller
# Phoenix.Endpoint
# Phoenix.Naming
# Phoenix.Logger
# Phoenix.Param
# Phoenix.Presence
# Phoenix.Router
# Phoenix.Token
[
Testing: [
Phoenix.ChannelTest,
Phoenix.ConnTest
],
"Adapters and Plugs": [
Phoenix.CodeReloader,
Phoenix.Endpoint.Cowboy2Adapter
],
"Socket and Transport": [
Phoenix.Socket,
Phoenix.Socket.Broadcast,
Phoenix.Socket.Message,
Phoenix.Socket.Reply,
Phoenix.Socket.Serializer,
Phoenix.Socket.Transport
]
]
end
defp aliases do
[
docs: ["docs", &generate_js_docs/1],
"assets.build": ["esbuild module", "esbuild cdn", "esbuild cdn_min"],
"assets.watch": "esbuild module --watch"
]
end
def generate_js_docs(_) do
Mix.Task.run("app.start")
System.cmd("npm", ["run", "docs"], cd: "assets")
end
end
| 27.248804 | 100 | 0.584021 |
7361d558d051e683bc0c334dbf52428622014061 | 173 | exs | Elixir | backend/apps/students_crm_v2/config/dev.exs | KyivKrishnaAcademy/students_crm_v2 | e0ad9b3c5e52dfef5ab8f9179f3c593f935786e6 | [
"MIT"
] | null | null | null | backend/apps/students_crm_v2/config/dev.exs | KyivKrishnaAcademy/students_crm_v2 | e0ad9b3c5e52dfef5ab8f9179f3c593f935786e6 | [
"MIT"
] | 50 | 2018-07-29T09:17:35.000Z | 2019-02-26T05:23:34.000Z | backend/apps/students_crm_v2/config/dev.exs | KyivKrishnaAcademy/students_crm_v2 | e0ad9b3c5e52dfef5ab8f9179f3c593f935786e6 | [
"MIT"
] | null | null | null | use Mix.Config
# Configure your database
config :students_crm_v2, StudentsCrmV2.Repo,
adapter: Ecto.Adapters.Postgres,
database: "students_crm_v2_dev",
pool_size: 10
| 21.625 | 44 | 0.786127 |
7361ee35f4708b441de5de3904ea8b25d33ec69e | 325 | ex | Elixir | lib/btrz_ex_api_client/http_poison.ex | Betterez/btrz-ex-api-client | 92e56fb8944de4cf4926aa0192525d33d77e87b4 | [
"MIT"
] | 2 | 2019-02-18T20:18:20.000Z | 2019-02-25T22:38:04.000Z | lib/btrz_ex_api_client/http_poison.ex | Betterez/btrz-ex-api-client | 92e56fb8944de4cf4926aa0192525d33d77e87b4 | [
"MIT"
] | null | null | null | lib/btrz_ex_api_client/http_poison.ex | Betterez/btrz-ex-api-client | 92e56fb8944de4cf4926aa0192525d33d77e87b4 | [
"MIT"
] | null | null | null | defmodule BtrzExApiClient.HTTPoison do
@moduledoc false
require Protocol
Protocol.derive(Jason.Encoder, HTTPoison.Error)
@behaviour BtrzExApiClient.HTTPClient
@impl true
def request(action, endpoint, encoded_body, headers, opts) do
HTTPoison.request(action, endpoint, encoded_body, headers, opts)
end
end
| 25 | 68 | 0.781538 |
73625bc0ec801d941e31270e5b56d6fbfff385e9 | 445 | exs | Elixir | mix.exs | adept-bits/adept | 214f71e1a5712f015def2068ee529e67cd970dac | [
"Apache-2.0"
] | 1 | 2022-01-06T08:24:23.000Z | 2022-01-06T08:24:23.000Z | mix.exs | adept-bits/adept | 214f71e1a5712f015def2068ee529e67cd970dac | [
"Apache-2.0"
] | null | null | null | mix.exs | adept-bits/adept | 214f71e1a5712f015def2068ee529e67cd970dac | [
"Apache-2.0"
] | null | null | null | defmodule Adept.MixProject do
use Mix.Project
def project do
[
app: :adept,
version: "0.1.0",
elixir: "~> 1.13",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger, :crypto]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[]
end
end
| 17.115385 | 59 | 0.586517 |
736264cf2aed3603c80e3d2233d5052a80b8bbaf | 1,720 | ex | Elixir | clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/update_active_breakpoint_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/update_active_breakpoint_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/update_active_breakpoint_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudDebugger.V2.Model.UpdateActiveBreakpointRequest do
@moduledoc """
Request to update an active breakpoint.
## Attributes
* `breakpoint` (*type:* `GoogleApi.CloudDebugger.V2.Model.Breakpoint.t`, *default:* `nil`) - Required. Updated breakpoint information. The field `id` must be set. The agent must echo all Breakpoint specification fields in the update.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:breakpoint => GoogleApi.CloudDebugger.V2.Model.Breakpoint.t() | nil
}
field(:breakpoint, as: GoogleApi.CloudDebugger.V2.Model.Breakpoint)
end
defimpl Poison.Decoder, for: GoogleApi.CloudDebugger.V2.Model.UpdateActiveBreakpointRequest do
def decode(value, options) do
GoogleApi.CloudDebugger.V2.Model.UpdateActiveBreakpointRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudDebugger.V2.Model.UpdateActiveBreakpointRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.595745 | 237 | 0.761628 |
73627319c487132d994873fd0a83c64579c05e3a | 155 | exs | Elixir | priv/repo/migrations/20180701214550_create_people.exs | jakewilkins/gexbot | b92cd5bae794becaedbee9c8884e4b66942198b7 | [
"WTFPL"
] | null | null | null | priv/repo/migrations/20180701214550_create_people.exs | jakewilkins/gexbot | b92cd5bae794becaedbee9c8884e4b66942198b7 | [
"WTFPL"
] | null | null | null | priv/repo/migrations/20180701214550_create_people.exs | jakewilkins/gexbot | b92cd5bae794becaedbee9c8884e4b66942198b7 | [
"WTFPL"
] | null | null | null | defmodule Gexbot.Repo.Migrations.CreatePeople do
use Ecto.Migration
def change do
create table(:people) do
timestamps()
end
end
end
| 12.916667 | 48 | 0.696774 |
736288ca1b4ee4afc44d2c65bedac1702f50f4c5 | 167 | ex | Elixir | lib/powit_web/views/pow_email_confirmation/mailer_view.ex | tenzil-rpx/powit | 0feebbfc11c7bd2a45ef0664632deb9b0537fb5c | [
"MIT"
] | null | null | null | lib/powit_web/views/pow_email_confirmation/mailer_view.ex | tenzil-rpx/powit | 0feebbfc11c7bd2a45ef0664632deb9b0537fb5c | [
"MIT"
] | null | null | null | lib/powit_web/views/pow_email_confirmation/mailer_view.ex | tenzil-rpx/powit | 0feebbfc11c7bd2a45ef0664632deb9b0537fb5c | [
"MIT"
] | null | null | null | defmodule PowitWeb.PowEmailConfirmation.MailerView do
use PowitWeb, :mailer_view
def subject(:email_confirmation, _assigns), do: "Confirm your email address"
end
| 27.833333 | 78 | 0.808383 |
73629e1d97d0d730138959d56533c9784fbd8704 | 2,251 | ex | Elixir | clients/health_care/lib/google_api/health_care/v1/model/google_cloud_healthcare_v1_fhir_big_query_destination.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/health_care/lib/google_api/health_care/v1/model/google_cloud_healthcare_v1_fhir_big_query_destination.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/health_care/lib/google_api/health_care/v1/model/google_cloud_healthcare_v1_fhir_big_query_destination.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.HealthCare.V1.Model.GoogleCloudHealthcareV1FhirBigQueryDestination do
@moduledoc """
The configuration for exporting to BigQuery.
## Attributes
* `datasetUri` (*type:* `String.t`, *default:* `nil`) - BigQuery URI to an existing dataset, up to 2000 characters long, in the format `bq://projectId.bqDatasetId`.
* `force` (*type:* `boolean()`, *default:* `nil`) - If this flag is `TRUE`, all tables are deleted from the dataset before the new exported tables are written. If the flag is not set and the destination dataset contains tables, the export call returns an error.
* `schemaConfig` (*type:* `GoogleApi.HealthCare.V1.Model.SchemaConfig.t`, *default:* `nil`) - The configuration for the exported BigQuery schema.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:datasetUri => String.t(),
:force => boolean(),
:schemaConfig => GoogleApi.HealthCare.V1.Model.SchemaConfig.t()
}
field(:datasetUri)
field(:force)
field(:schemaConfig, as: GoogleApi.HealthCare.V1.Model.SchemaConfig)
end
defimpl Poison.Decoder,
for: GoogleApi.HealthCare.V1.Model.GoogleCloudHealthcareV1FhirBigQueryDestination do
def decode(value, options) do
GoogleApi.HealthCare.V1.Model.GoogleCloudHealthcareV1FhirBigQueryDestination.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.HealthCare.V1.Model.GoogleCloudHealthcareV1FhirBigQueryDestination do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.810345 | 265 | 0.739227 |
7362a8fbc82d3f570c21fd5ccf0154e767273698 | 1,496 | ex | Elixir | clients/compute/lib/google_api/compute/v1/model/authorization_logging_options.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/compute/lib/google_api/compute/v1/model/authorization_logging_options.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/compute/lib/google_api/compute/v1/model/authorization_logging_options.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Compute.V1.Model.AuthorizationLoggingOptions do
@moduledoc """
This is deprecated and has no effect. Do not use.
## Attributes
* `permissionType` (*type:* `String.t`, *default:* `nil`) - This is deprecated and has no effect. Do not use.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:permissionType => String.t() | nil
}
field(:permissionType)
end
defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.AuthorizationLoggingOptions do
def decode(value, options) do
GoogleApi.Compute.V1.Model.AuthorizationLoggingOptions.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.AuthorizationLoggingOptions do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.829787 | 113 | 0.743316 |
7362b6f98da6e94bc0377a96f856a300be6b5bc7 | 666 | ex | Elixir | lib/broadway_kafka.ex | danielkv7/broadway_kafka | 4388117537ee81738ff4d6a89ed6a2c602d47d8c | [
"Apache-2.0"
] | 112 | 2020-01-20T22:04:30.000Z | 2022-03-25T10:41:47.000Z | lib/broadway_kafka.ex | danielkv7/broadway_kafka | 4388117537ee81738ff4d6a89ed6a2c602d47d8c | [
"Apache-2.0"
] | 71 | 2020-01-22T12:43:29.000Z | 2022-03-30T22:30:29.000Z | lib/broadway_kafka.ex | danielkv7/broadway_kafka | 4388117537ee81738ff4d6a89ed6a2c602d47d8c | [
"Apache-2.0"
] | 39 | 2020-02-21T15:10:42.000Z | 2022-02-11T17:34:09.000Z | defmodule BroadwayKafka do
@moduledoc """
Helpers for BroadwayKafka.
You can find the Broadway producer in `BroadwayKafka.Producer`.
"""
@doc """
Sequentially updates topics in all Broadway producers in the
pipeline given by `name`.
## Examples
BroadwayKafka.update_topics(MyBroadway, ["topic_a", "topic_b"])
:ok
BroadwayKafka.update_topics(MyBroadway, [])
:ok
"""
def update_topics(name, topics) do
each_producer(name, &GenServer.cast(&1, {:update_topics, topics}))
end
defp each_producer(server, fun) when is_function(fun, 1) do
server
|> Broadway.producer_names()
|> Enum.each(fun)
end
end
| 21.483871 | 70 | 0.68018 |
7362c1d9bf935c0edadbe7d11de34b336ecf2365 | 1,271 | ex | Elixir | bubblit/lib/bubblit_web/controllers/room_controller.ex | pula39/BubbLit | 12f5bc010ab67fc13797f786d1cd0f10e23bf327 | [
"MIT"
] | null | null | null | bubblit/lib/bubblit_web/controllers/room_controller.ex | pula39/BubbLit | 12f5bc010ab67fc13797f786d1cd0f10e23bf327 | [
"MIT"
] | 84 | 2020-04-03T08:06:06.000Z | 2022-02-13T12:45:15.000Z | bubblit/lib/bubblit_web/controllers/room_controller.ex | pula39/BubbLit | 12f5bc010ab67fc13797f786d1cd0f10e23bf327 | [
"MIT"
] | 1 | 2020-09-25T12:59:02.000Z | 2020-09-25T12:59:02.000Z | defmodule BubblitWeb.RoomController do
use BubblitWeb, :controller
alias Bubblit.BubbleRooms
alias Bubblit.BubbleRooms.Room
action_fallback BubblitWeb.FallbackController
# 전체적으로 권한 체크 필요.
def index(conn, _params) do
rooms = Bubblit.Db.list_rooms()
render(conn, "index.json", rooms: rooms)
end
def create(conn, %{"title" => title, "is_private" => is_private} = _room_params) do
with user_id = Plug.Conn.get_session(conn, :current_user_id),
%Room{} = room <- Bubblit.Db.create_room(title, user_id, is_private) do
conn
|> put_status(:created)
|> put_resp_header("location", Routes.room_path(conn, :show, room))
|> render("show.json", room: room)
end
end
def show(conn, %{"id" => id}) do
room = Bubblit.Db.get_room!(id)
render(conn, "show.json", room: room)
end
def update(conn, %{"id" => id, "room" => room_params}) do
room = Bubblit.Db.get_room!(id)
with {:ok, %Room{} = room} <- Bubblit.Db.update_room(room, room_params) do
render(conn, "show.json", room: room)
end
end
def delete(conn, %{"id" => id}) do
room = BubbleRooms.get_room!(id)
with {:ok, %Room{}} <- BubbleRooms.delete_room(room) do
send_resp(conn, :no_content, "")
end
end
end
| 27.042553 | 85 | 0.644375 |
7362e68d404de8f40c1812f6c7a1463355b0a254 | 170 | exs | Elixir | priv/repo/migrations/20201019015602_add_pg_stats_ext.exs | MorphicPro/morphic.pro | 9098da267344e025f262a344de6a2fb5cfea50a8 | [
"MIT"
] | 5 | 2020-04-23T21:12:17.000Z | 2020-09-30T00:16:58.000Z | priv/repo/migrations/20201019015602_add_pg_stats_ext.exs | joshchernoff/morphic.pro | 9098da267344e025f262a344de6a2fb5cfea50a8 | [
"MIT"
] | 232 | 2020-04-24T00:52:24.000Z | 2021-08-05T17:23:12.000Z | priv/repo/migrations/20201019015602_add_pg_stats_ext.exs | MorphicPro/morphic.pro | 9098da267344e025f262a344de6a2fb5cfea50a8 | [
"MIT"
] | 1 | 2020-04-04T02:19:44.000Z | 2020-04-04T02:19:44.000Z | defmodule MorphicPro.Repo.Migrations.AddPgStatsExt do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS pg_stat_statements", ""
end
end
| 21.25 | 67 | 0.776471 |
73630187567969a4c54a5d8bfd9c2178fc0db39b | 1,531 | exs | Elixir | test/blockfrost/cardano/ledger_test.exs | blockfrost/blockfrost-elixir | b1f8ea7ae47cd3a7037e1c9ed0d3691fc775bdec | [
"Apache-2.0"
] | 13 | 2021-08-31T03:54:37.000Z | 2022-01-30T17:39:40.000Z | test/blockfrost/cardano/ledger_test.exs | blockfrost/blockfrost-elixir | b1f8ea7ae47cd3a7037e1c9ed0d3691fc775bdec | [
"Apache-2.0"
] | 6 | 2021-08-30T04:45:52.000Z | 2021-09-23T09:15:08.000Z | test/blockfrost/cardano/ledger_test.exs | blockfrost/blockfrost-elixir | b1f8ea7ae47cd3a7037e1c9ed0d3691fc775bdec | [
"Apache-2.0"
] | null | null | null | defmodule Blockfrost.Cardano.LedgerTest do
use Blockfrost.Case
alias Blockfrost.Cardano.Ledger
alias Blockfrost.HTTPClientMock
alias Blockfrost.Response.BlockchainGenesisResponse
setup_all do
start_supervised!({Blockfrost, api_key: "apikey", network: :cardano_testnet})
:ok
end
describe "blockchain_genesis/0,1,2" do
test "properly decodes 200 response" do
expect(HTTPClientMock, :request, fn request, _finch, _opts ->
assert request.path == "/api/v0/genesis"
response(
200,
%{
active_slots_coefficient: 0.05,
update_quorum: 5,
max_lovelace_supply: "45000000000000000",
network_magic: 764_824_073,
epoch_length: 432_000,
system_start: 1_506_203_091,
slots_per_kes_period: 129_600,
slot_length: 1,
max_kes_evolutions: 62,
security_param: 2160
}
)
end)
assert {:ok,
%BlockchainGenesisResponse{
active_slots_coefficient: 0.05,
update_quorum: 5,
max_lovelace_supply: "45000000000000000",
network_magic: 764_824_073,
epoch_length: 432_000,
system_start: 1_506_203_091,
slots_per_kes_period: 129_600,
slot_length: 1,
max_kes_evolutions: 62,
security_param: 2160
}} == Ledger.blockchain_genesis(Blockfrost)
end
end
end
| 28.886792 | 81 | 0.594383 |
736319f77633b8aa232b2c5559613a424e67412e | 2,820 | ex | Elixir | lib/plaid/client.ex | ethangunderson/elixir-plaid | 53aa0a87a4a837df6a2d15684870e7a58a003db6 | [
"MIT"
] | null | null | null | lib/plaid/client.ex | ethangunderson/elixir-plaid | 53aa0a87a4a837df6a2d15684870e7a58a003db6 | [
"MIT"
] | null | null | null | lib/plaid/client.ex | ethangunderson/elixir-plaid | 53aa0a87a4a837df6a2d15684870e7a58a003db6 | [
"MIT"
] | null | null | null | defmodule Plaid.Client do
@moduledoc false
use HTTPoison.Base
require Logger
alias Plaid.Castable
def process_request_headers(headers) do
[{"Content-Type", "application/json"}] ++ headers
end
@doc """
Make a Plaid API call.
Takes in everything needed to complete the request and
return a well formed struct of the response.
## Examples
call(
"/categories/get",
%{},
Plaid.Categories.GetResponse,
client_id: "123",
secret: "abc"
)
{:ok, %Plaid.Categories.GetResponse{}}
"""
@spec call(String.t(), map(), module(), Plaid.config()) ::
{:ok, any()} | {:error, Plaid.Error.t()}
def call(endpoint, payload \\ %{}, castable_module, config) do
url = build_url(config, endpoint)
payload =
payload
|> add_auth(config)
|> Jason.encode!()
:post
|> request(url, payload, recv_timeout: 60_000)
|> handle_response(castable_module)
end
@spec build_url(Plaid.config(), String.t()) :: String.t()
defp build_url(config, endpoint) do
test_api_host = Keyword.get(config, :test_api_host)
if is_binary(test_api_host) do
test_api_host <> endpoint
else
env = Keyword.get(config, :env, :sandbox)
"https://#{env}.plaid.com#{endpoint}"
end
end
@spec add_auth(map(), Plaid.config()) :: map()
defp add_auth(payload, config) do
auth =
config
|> Map.new()
|> Map.take([:client_id, :secret])
Map.merge(payload, auth)
end
@spec handle_response(
{:ok,
HTTPoison.Response.t()
| HTTPoison.AsyncResponse.t()
| HTTPoison.MaybeRedirect.t()}
| {:error, HTTPoison.Error.t()},
module() | :raw
) :: {:ok, any()} | {:error, Plaid.Error.t()}
def handle_response({:ok, %{body: body, status_code: status_code}}, :raw)
when status_code in 200..299 do
{:ok, body}
end
def handle_response({:ok, %{body: json_body, status_code: status_code}}, castable_module)
when status_code in 200..299 do
case Jason.decode(json_body) do
{:ok, generic_map} -> {:ok, Castable.cast(castable_module, generic_map)}
_ -> {:error, Castable.cast(Plaid.Error, %{})}
end
end
def handle_response({:ok, %{body: json_body}}, _castable_module) do
case Jason.decode(json_body) do
{:ok, generic_map} -> {:error, Castable.cast(Plaid.Error, generic_map)}
_ -> {:error, Castable.cast(Plaid.Error, %{})}
end
end
def handle_response(res, _) do
Logger.warn([
"[#{__MODULE__}] un-",
" un-handled response.",
" #{inspect(res)}",
" Create an issue or pull request with the above response",
" at https://github.com/tylerwray/elixir-plaid."
])
{:error, Castable.cast(Plaid.Error, %{})}
end
end
| 26.111111 | 91 | 0.606028 |
736329e126bedde30768a71b612dc64d545b9be2 | 82 | exs | Elixir | teachme/test/teachme_web/views/layout_view_test.exs | kodeklubben-sandefjord/kodeklubben-sandefjord.github.io | 89351bceb132f87b1d2a0bcb325fb278d7ad48a4 | [
"MIT"
] | null | null | null | teachme/test/teachme_web/views/layout_view_test.exs | kodeklubben-sandefjord/kodeklubben-sandefjord.github.io | 89351bceb132f87b1d2a0bcb325fb278d7ad48a4 | [
"MIT"
] | 1 | 2020-07-17T10:07:44.000Z | 2020-07-17T10:07:44.000Z | teachme/test/teachme_web/views/layout_view_test.exs | kodeklubben-sandefjord/kodeklubben-sandefjord.github.io | 89351bceb132f87b1d2a0bcb325fb278d7ad48a4 | [
"MIT"
] | null | null | null | defmodule TeachmeWeb.LayoutViewTest do
use TeachmeWeb.ConnCase, async: true
end
| 20.5 | 38 | 0.829268 |
73632a9994d4114b9fee642d0620e1e51ad84f06 | 577 | exs | Elixir | apps/core/priv/repo/seeds/03_accounts.exs | michaeljguarino/forge | 50ee583ecb4aad5dee4ef08fce29a8eaed1a0824 | [
"Apache-2.0"
] | 59 | 2021-09-16T19:29:39.000Z | 2022-03-31T20:44:24.000Z | apps/core/priv/repo/seeds/03_accounts.exs | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | 111 | 2021-08-15T09:56:37.000Z | 2022-03-31T23:59:32.000Z | apps/core/priv/repo/seeds/03_accounts.exs | svilenkov/plural | ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026 | [
"Apache-2.0"
] | 4 | 2021-12-13T09:43:01.000Z | 2022-03-29T18:08:44.000Z | import Botanist
alias Core.Repo
alias Core.Schema.{User, Account}
alias Core.Services.Accounts
import Core.Services.Base
seed do
User.without_account()
|> Core.Repo.all()
|> Enum.map(fn user ->
{:ok, _} =
start_transaction()
|> add_operation(:account, fn _ ->
Accounts.create_account(user)
end)
|> add_operation(:final, fn %{account: %{account: account}} ->
account
|> Account.payment_changeset(%{billing_customer_id: user.customer_id})
|> Repo.update()
end)
|> execute(extract: :final)
end)
end | 24.041667 | 78 | 0.632582 |
7363991bca27672c989831718e77c3e38db4d1f2 | 918 | ex | Elixir | lib/mundum_web/views/path_helpers.ex | allen-garvey/mundum | 15719f6bca998a04f783206f4db2214ebd439e61 | [
"MIT"
] | null | null | null | lib/mundum_web/views/path_helpers.ex | allen-garvey/mundum | 15719f6bca998a04f783206f4db2214ebd439e61 | [
"MIT"
] | null | null | null | lib/mundum_web/views/path_helpers.ex | allen-garvey/mundum | 15719f6bca998a04f783206f4db2214ebd439e61 | [
"MIT"
] | null | null | null | defmodule MundumWeb.PathHelpers do
use Phoenix.HTML
@doc """
Used to generate name for path helper function
"""
def item_path_func_name(item_name_singular) do
String.to_atom(String.replace(item_name_singular, " ", "_") <> "_path")
end
@doc """
Returns path for item
(e.g. :index, :show, :new)
"""
def path_for_item(conn, item_name_singular, path_atom) do
apply(MundumWeb.Router.Helpers, item_path_func_name(item_name_singular), [conn, path_atom])
end
@doc """
Returns path for item instance
(e.g. :edit and :show)
"""
def path_for_item(conn, item_name_singular, path_atom, item_instance) do
apply(MundumWeb.Router.Helpers, item_path_func_name(item_name_singular), [conn, path_atom, item_instance])
end
@doc """
Used to turn a url that might be nil into a link
"""
def linkify(nil) do
nil
end
def linkify(url) do
link(url, to: url)
end
end | 24.810811 | 108 | 0.6939 |
7363b84c04acded07b70c1eac84b3efb25e92907 | 2,900 | ex | Elixir | lib/quest/web/controllers/option_controller.ex | ench0/quest | 844043205aa78e6937243f6993cbd560b6a5765b | [
"MIT"
] | null | null | null | lib/quest/web/controllers/option_controller.ex | ench0/quest | 844043205aa78e6937243f6993cbd560b6a5765b | [
"MIT"
] | null | null | null | lib/quest/web/controllers/option_controller.ex | ench0/quest | 844043205aa78e6937243f6993cbd560b6a5765b | [
"MIT"
] | null | null | null | defmodule Quest.Web.OptionController do
use Quest.Web, :controller
alias Quest.Main
def index(conn, _params) do
options = Main.list_options()
render(conn, "index.html", options: options)
end
def new(conn, option_params) do
questions = Main.list_questions()
question_id = option_params["question_id"]
question_list = Enum.map(questions, fn(x)-> ["#{x.title}": "#{Integer.to_string(x.id)}"] end)
|> List.flatten
changeset = Main.change_option(%Quest.Main.Option{})
render(conn, "new.html", changeset: changeset, question_list: question_list, question_id: question_id)
end
def create(conn, %{"option" => option_params}) do
questions = Main.list_questions()
question_id = option_params["question_id"]
questions_list = Enum.map(questions, fn(x)-> ["#{x.title}": "#{Integer.to_string(x.id)}"] end)
|> List.flatten
case Main.create_option(option_params) do
{:ok, option} ->
conn
|> put_flash(:info, "Option created successfully.")
|> redirect(to: question_path(conn, :edit, question_id))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "new.html", changeset: changeset, questions_list: questions_list, question_id: question_id)
end
end
def show(conn, %{"id" => id}) do
option = Main.get_option!(id)
render(conn, "show.html", option: option)
end
def edit(conn, option_params) do
id = option_params["id"]
question_id = option_params["question_id"]
option = Main.get_option!(id)
questions = Main.list_questions()
question = Main.get_question!(option.question_id)
questions_list = Enum.map(questions, fn(x)-> ["#{x.title}": "#{Integer.to_string(x.id)}"] end)
|> List.flatten
changeset = Main.change_option(option)
render(conn, "edit.html", option: option, changeset: changeset, questions_list: questions_list, question: question, question_id: question_id)
end
def update(conn, %{"id" => id, "option" => option_params}) do
option = Main.get_option!(id)
questions = Main.list_questions()
question = Main.get_question!(option.question_id)
questions_list = Enum.map(questions, fn(x)-> ["#{x.title}": "#{Integer.to_string(x.id)}"] end)
|> List.flatten
case Main.update_option(option, option_params) do
{:ok, option} ->
conn
|> put_flash(:info, "Option updated successfully.")
|> redirect(to: question_path(conn, :edit, question.id))
{:error, %Ecto.Changeset{} = changeset} ->
render(conn, "edit.html", option: option, changeset: changeset, questions_list: questions_list, question: question)
end
end
def delete(conn, %{"id" => id}) do
option = Main.get_option!(id)
{:ok, _option} = Main.delete_option(option)
conn
|> put_flash(:info, "Option deleted successfully.")
|> redirect(to: option_path(conn, :index))
end
end
| 35.365854 | 145 | 0.661724 |
7363c9f72de76196415a3008becb4382cfaab272 | 1,192 | ex | Elixir | lib/data_processor_web/channels/user_socket.ex | DylanGuedes/batch_processor | 2f3122a5f1a31557a39fac67aa62e297c39e8bf5 | [
"Apache-2.0"
] | null | null | null | lib/data_processor_web/channels/user_socket.ex | DylanGuedes/batch_processor | 2f3122a5f1a31557a39fac67aa62e297c39e8bf5 | [
"Apache-2.0"
] | 3 | 2018-08-17T13:42:45.000Z | 2018-08-17T17:05:11.000Z | lib/data_processor_web/channels/user_socket.ex | DylanGuedes/batch_processor | 2f3122a5f1a31557a39fac67aa62e297c39e8bf5 | [
"Apache-2.0"
] | null | null | null | defmodule DataProcessorWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", DataProcessorWeb.RoomChannel
## 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: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# DataProcessorWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31.368421 | 88 | 0.707215 |
7363cfd0fb45710c8b3ad039cd7b28c718171890 | 466 | ex | Elixir | lib/elaxto/actions/index_action.ex | secretworry/elaxto | d4e66dc554f7dfe7786d9caf2dc3def5d231d37f | [
"Apache-2.0"
] | 2 | 2016-12-13T05:51:13.000Z | 2017-02-18T18:29:09.000Z | lib/elaxto/actions/index_action.ex | secretworry/elaxto | d4e66dc554f7dfe7786d9caf2dc3def5d231d37f | [
"Apache-2.0"
] | null | null | null | lib/elaxto/actions/index_action.ex | secretworry/elaxto | d4e66dc554f7dfe7786d9caf2dc3def5d231d37f | [
"Apache-2.0"
] | null | null | null | defmodule Elaxto.IndexAction do
@docmodule """
Action to invoke Indeces API
"""
@type error :: {String.t, Keyword.t}
@type t :: %__MODULE__{
name: atom,
settings: Map.t,
alias: Map.t,
mappings: Map.t,
opts: Keyword.t,
valid?: boolean,
errors: [error]
}
@type diff_result_t :: Map.t | nil
@enforce_keys ~w{name mappings}a
defstruct [:name, :mappings, settings: nil, alias: nil, opts: [], valid?: true, errors: []]
end | 21.181818 | 93 | 0.618026 |
736405fc60478e374cfbb89c7375cad739521fd7 | 709 | ex | Elixir | apps/legion/lib/identity/auth/concrete/viewdecl/active_passphrase.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 1 | 2021-01-04T11:06:12.000Z | 2021-01-04T11:06:12.000Z | apps/legion/lib/identity/auth/concrete/viewdecl/active_passphrase.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | 3 | 2021-01-30T06:40:37.000Z | 2021-01-30T06:41:08.000Z | apps/legion/lib/identity/auth/concrete/viewdecl/active_passphrase.ex | i386-64/legion | 41ae99af9be962d7fb38726ddf4bb0456edb5ca4 | [
"Apache-2.0"
] | null | null | null | defmodule Legion.Identity.Auth.Concrete.ActivePassphrase.ViewDecl do
@moduledoc false
use Legion.Stereotype, :viewdecl
@concrete_env Application.get_env(:legion, Legion.Identity.Auth.Concrete)
@passphrase_lifetime Keyword.fetch!(@concrete_env, :passphrase_lifetime)
create do
"""
CREATE OR REPLACE VIEW active_passphrases AS
SELECT p.*
FROM passphrases p
LEFT OUTER JOIN passphrase_invalidations pi
ON p.id = pi.target_passphrase_id
WHERE
pi.id IS NULL AND
p.inserted_at > now()::timestamp without time zone - interval '#{@passphrase_lifetime} seconds';
"""
end
drop do
"""
DROP VIEW active_passphrases;
"""
end
end
| 26.259259 | 104 | 0.696756 |
7364116a259d2d7cd90716ffa188c35d985be443 | 21,023 | ex | Elixir | apps/evm/lib/block/header.ex | wolflee/mana | db66dac85addfaad98d40da5bd4082b3a0198bb1 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 152 | 2018-10-27T04:52:03.000Z | 2022-03-26T10:34:00.000Z | apps/evm/lib/block/header.ex | wolflee/mana | db66dac85addfaad98d40da5bd4082b3a0198bb1 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 270 | 2018-04-14T07:34:57.000Z | 2018-10-25T18:10:45.000Z | apps/evm/lib/block/header.ex | wolflee/mana | db66dac85addfaad98d40da5bd4082b3a0198bb1 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 25 | 2018-10-27T12:15:13.000Z | 2022-01-25T20:31:14.000Z | defmodule Block.Header do
@moduledoc """
This structure codifies the header of a block in the blockchain.
For more information, see Section 4.3 of the Yellow Paper.
"""
alias ExthCrypto.Hash.Keccak
@empty_trie MerklePatriciaTree.Trie.empty_trie_root_hash()
@empty_keccak [] |> ExRLP.encode() |> Keccak.kec()
@frontier_difficulty_adjustment 13
defstruct parent_hash: nil,
ommers_hash: @empty_keccak,
beneficiary: nil,
state_root: @empty_trie,
transactions_root: @empty_trie,
receipts_root: @empty_trie,
logs_bloom: <<0::2048>>,
difficulty: nil,
number: nil,
gas_limit: 0,
gas_used: 0,
timestamp: nil,
extra_data: <<>>,
mix_hash: <<0::256>>,
nonce: <<0::64>>,
total_difficulty: 0,
size: 0
@typedoc """
As defined in section 4.3 of Yellow Paper:
* H_p P(B_H)H_r = parent_hash
* H_o KEC(RLP(L∗H(B_U))) = ommers_hash
* H_c = beneficiary
* H_r TRIE(LS(Π(σ, B))) = state_root
* H_t TRIE({∀i < kBTk, i ∈ P : p(i, LT(B_T[i]))}) = transactions_root
* H_e TRIE({∀i < kBRk, i ∈ P : p(i, LR(B_R[i]))}) = receipts_root
* H_b bloom = logs_bloom
* H_d = difficulty
* H_i = number
* H_l = gas_limit
* H_g = gas_used
* H_s = timestamp
* H_x = extra_data
* H_m = mix_hash
* H_n = nonce
"""
@type t :: %__MODULE__{
parent_hash: EVM.hash() | nil,
ommers_hash: EVM.trie_root(),
beneficiary: EVM.address() | nil,
state_root: EVM.trie_root(),
transactions_root: EVM.trie_root(),
receipts_root: EVM.trie_root(),
logs_bloom: binary(),
difficulty: integer() | nil,
number: integer() | nil,
gas_limit: EVM.val(),
gas_used: EVM.val(),
timestamp: EVM.timestamp() | nil,
extra_data: binary(),
mix_hash: EVM.hash() | nil,
# TODO: 64-bit hash?
nonce: <<_::64>> | nil
}
# The start of the Homestead block, as defined in EIP-606:
# https://github.com/ethereum/EIPs/blob/master/EIPS/eip-606.md
@homestead_block 1_150_000
# D_0 is the difficulty of the genesis block.
# As defined in Eq.(42)
@initial_difficulty 131_072
# Mimics d_0 in Eq.(42), but variable on different chains
@minimum_difficulty @initial_difficulty
# Eq.(43)
@difficulty_bound_divisor 2048
# Must be 32 bytes or fewer. See H_e in Eq.(37)
@max_extra_data_bytes 32
# Constant from Eq.(47)
@gas_limit_bound_divisor 1024
# Eq.(47)
@min_gas_limit 125_000
@dao_extra_data "dao-hard-fork"
@spec to_string(t) :: String.t()
def to_string(header) do
"""
Header {
hash: #{Exth.encode_hex(hash(header))},
parent_hash: #{Exth.encode_hex(header.parent_hash)},
ommers_hash: #{Exth.encode_hex(header.ommers_hash)},
beneficiary: #{Exth.encode_hex(header.beneficiary)},
state_root: #{Exth.encode_hex(header.state_root)},
transactions_root: #{Exth.encode_hex(header.transactions_root)},
receipts_root: #{Exth.encode_hex(header.receipts_root)},
logs_bloom: #{Exth.encode_hex(header.logs_bloom)},
difficulty: #{header.difficulty},
number: #{header.number},
gas_limit: #{header.gas_limit},
gas_used: #{header.gas_used},
timestamp: #{header.timestamp},
extra_data: #{Exth.encode_hex(header.extra_data)},
mix_hash: #{Exth.encode_hex(header.mix_hash)},
nonce: #{Exth.encode_hex(header.nonce)},
}
"""
end
@doc """
Returns the block that defines the start of Homestead.
This should be a constant, but it's configurable on different
chains, and as such, as allow you to pass that configuration
variable (which ends up making this the identity function, if so).
"""
@spec homestead(integer()) :: integer()
def homestead(homestead_block \\ @homestead_block), do: homestead_block
@doc """
This functions encode a header into a value that can
be RLP encoded. This is defined as L_H Eq.(34) in the Yellow Paper.
## Examples
iex> Block.Header.serialize(%Block.Header{parent_hash: <<1::256>>, ommers_hash: <<2::256>>, beneficiary: <<3::160>>, state_root: <<4::256>>, transactions_root: <<5::256>>, receipts_root: <<6::256>>, logs_bloom: <<>>, difficulty: 5, number: 1, gas_limit: 5, gas_used: 3, timestamp: 6, extra_data: "Hi mom", mix_hash: <<7::256>>, nonce: <<8::64>>})
[<<1::256>>, <<2::256>>, <<3::160>>, <<4::256>>, <<5::256>>, <<6::256>>, <<>>, 5, 1, 5, 3, 6, "Hi mom", <<7::256>>, <<8::64>>]
"""
@spec serialize(t) :: ExRLP.t()
def serialize(h) do
[
# H_p
h.parent_hash,
# H_o
h.ommers_hash,
# H_c
h.beneficiary,
# H_r
h.state_root,
# H_t
h.transactions_root,
# H_e
h.receipts_root,
# H_b
h.logs_bloom,
# H_d
h.difficulty,
# H_i
if(h.number == 0, do: <<>>, else: h.number),
# H_l
h.gas_limit,
# H_g
if(h.number == 0, do: <<>>, else: h.gas_used),
# H_s
h.timestamp,
# H_x
h.extra_data,
# H_m
h.mix_hash,
# H_n
h.nonce
]
end
@doc """
Deserializes a block header from an RLP encodable structure.
This effectively undoes the encoding defined in L_H Eq.(34) of the
Yellow Paper.
## Examples
iex> Block.Header.deserialize([<<1::256>>, <<2::256>>, <<3::160>>, <<4::256>>, <<5::256>>, <<6::256>>, <<>>, <<5>>, <<1>>, <<5>>, <<3>>, <<6>>, "Hi mom", <<7::256>>, <<8::64>>])
%Block.Header{parent_hash: <<1::256>>, ommers_hash: <<2::256>>, beneficiary: <<3::160>>, state_root: <<4::256>>, transactions_root: <<5::256>>, receipts_root: <<6::256>>, logs_bloom: <<>>, difficulty: 5, number: 1, gas_limit: 5, gas_used: 3, timestamp: 6, extra_data: "Hi mom", mix_hash: <<7::256>>, nonce: <<8::64>>}
"""
@spec deserialize(ExRLP.t()) :: t
def deserialize(rlp) do
[
parent_hash,
ommers_hash,
beneficiary,
state_root,
transactions_root,
receipts_root,
logs_bloom,
difficulty,
number,
gas_limit,
gas_used,
timestamp,
extra_data,
mix_hash,
nonce
] = rlp
%__MODULE__{
parent_hash: parent_hash,
ommers_hash: ommers_hash,
beneficiary: beneficiary,
state_root: state_root,
transactions_root: transactions_root,
receipts_root: receipts_root,
logs_bloom: logs_bloom,
difficulty: Exth.maybe_decode_unsigned(difficulty),
number: Exth.maybe_decode_unsigned(number),
gas_limit: Exth.maybe_decode_unsigned(gas_limit),
gas_used: Exth.maybe_decode_unsigned(gas_used),
timestamp: Exth.maybe_decode_unsigned(timestamp),
extra_data: extra_data,
mix_hash: mix_hash,
nonce: nonce
}
end
@doc """
Computes hash of a block header,
which is simply the hash of the serialized block header.
This is defined in Eq.(33) of the Yellow Paper.
## Examples
iex> %Block.Header{number: 5, parent_hash: <<1, 2, 3>>, beneficiary: <<2, 3, 4>>, difficulty: 100, timestamp: 11, mix_hash: <<1>>, nonce: <<2>>}
...> |> Block.Header.hash()
<<78, 28, 127, 10, 192, 253, 127, 239, 254, 179, 39, 34, 245, 44, 152, 98, 128, 71, 238, 155, 100, 161, 199, 71, 243, 223, 172, 191, 74, 99, 128, 63>>
iex> %Block.Header{number: 0, parent_hash: <<1, 2, 3>>, beneficiary: <<2, 3, 4>>, difficulty: 100, timestamp: 11, mix_hash: <<1>>, nonce: <<2>>}
...> |> Block.Header.hash()
<<218, 225, 46, 241, 196, 160, 136, 96, 109, 216, 73, 167, 92, 174, 91, 228, 85, 112, 234, 129, 99, 200, 158, 61, 223, 166, 165, 132, 187, 24, 142, 193>>
"""
@spec hash(t) :: EVM.hash()
def hash(header) do
header
|> serialize()
|> ExRLP.encode()
|> Keccak.kec()
end
@doc """
Returns true if the block header is valid.
This defines Eq.(50) of the Yellow Paper,
commonly referred to as V(H).
## Examples
iex> Block.Header.validate(%Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000}, nil, 131_072)
:valid
iex> Block.Header.validate(%Block.Header{number: 0, difficulty: 5, gas_limit: 5}, nil, 15)
{:invalid, [:invalid_difficulty, :invalid_gas_limit]}
iex> Block.Header.validate(%Block.Header{number: 1, difficulty: 131_136, gas_limit: 200_000, timestamp: 65}, %Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000, timestamp: 55}, 131_136)
:valid
iex> Block.Header.validate(%Block.Header{number: 1, difficulty: 131_000, gas_limit: 200_000, timestamp: 65}, %Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000, timestamp: 55}, 131_100)
{:invalid, [:invalid_difficulty]}
iex> Block.Header.validate(%Block.Header{number: 1, difficulty: 131_136, gas_limit: 200_000, timestamp: 45}, %Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000, timestamp: 55}, 131_136)
{:invalid, [:child_timestamp_invalid]}
iex> Block.Header.validate(%Block.Header{number: 1, difficulty: 131_136, gas_limit: 300_000, timestamp: 65}, %Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000, timestamp: 55}, 131_136)
{:invalid, [:invalid_gas_limit]}
iex> Block.Header.validate(%Block.Header{number: 2, difficulty: 131_136, gas_limit: 200_000, timestamp: 65}, %Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000, timestamp: 55}, 131_136)
{:invalid, [:child_number_invalid]}
iex> Block.Header.validate(%Block.Header{number: 1, difficulty: 131_136, gas_limit: 200_000, timestamp: 65, extra_data: "0123456789012345678901234567890123456789"}, %Block.Header{number: 0, difficulty: 131_072, gas_limit: 200_000, timestamp: 55}, 131_136)
{:invalid, [:extra_data_too_large]}
"""
@spec validate(t, t | nil, integer(), integer(), integer()) :: :valid | {:invalid, [atom()]}
def validate(
header,
parent_header,
expected_difficulty,
gas_limit_bound_divisor \\ @gas_limit_bound_divisor,
min_gas_limit \\ @min_gas_limit,
validate_dao_extra_data \\ false
) do
parent_gas_limit = if parent_header, do: parent_header.gas_limit, else: nil
errors =
[]
|> extra_data_validity(header)
|> check_child_number_validity(header, parent_header)
|> check_child_timestamp_validity(header, parent_header)
|> check_gas_limit_validity(
header,
parent_gas_limit,
gas_limit_bound_divisor,
min_gas_limit
)
|> check_gas_limit(header)
|> check_difficulty_validity(header, expected_difficulty)
|> check_extra_data_validity(header, validate_dao_extra_data)
if errors == [], do: :valid, else: {:invalid, errors}
end
@doc """
Returns the total available gas left for all transactions in
this block. This is the total gas limit minus the gas used
in transactions.
## Examples
iex> Block.Header.available_gas(%Block.Header{gas_limit: 50_000, gas_used: 30_000})
20_000
"""
@spec available_gas(t) :: EVM.Gas.t()
def available_gas(header) do
header.gas_limit - header.gas_used
end
@doc """
Calculates the difficulty of a new block header for Byzantium. This implements
Eq.(41), Eq.(42), Eq.(43), Eq.(44), Eq.(45) and Eq.(46) of the Yellow Paper.
## Examples
iex> Block.Header.get_byzantium_difficulty(
...> %Block.Header{number: 1, timestamp: 1479642530},
...> %Block.Header{number: 0, timestamp: 0, difficulty: 1_048_576},
...> 3_000_000
...> )
997_888
"""
def get_byzantium_difficulty(
header,
parent_header,
delay_factor,
initial_difficulty \\ @initial_difficulty,
minimum_difficulty \\ @minimum_difficulty,
difficulty_bound_divisor \\ @difficulty_bound_divisor
) do
if header.number == 0 do
initial_difficulty
else
difficulty_delta =
difficulty_x(parent_header.difficulty, difficulty_bound_divisor) *
byzantium_difficulty_parameter(header, parent_header)
next_difficulty =
parent_header.difficulty + difficulty_delta + byzantium_difficulty_e(header, delay_factor)
max(minimum_difficulty, next_difficulty)
end
end
@doc """
Calculates the difficulty of a new block header for Homestead. This implements
Eq.(41), Eq.(42), Eq.(43), Eq.(44), Eq.(45) and Eq.(46) of the Yellow Paper.
## Examples
iex> Block.Header.get_homestead_difficulty(
...> %Block.Header{number: 3_000_001, timestamp: 66},
...> %Block.Header{number: 3_000_000, timestamp: 55, difficulty: 300_000}
...> )
268_735_456
iex> Block.Header.get_homestead_difficulty(
...> %Block.Header{number: 3_000_001, timestamp: 155},
...> %Block.Header{number: 3_000_000, timestamp: 55, difficulty: 300_000}
...> )
268_734_142
"""
@spec get_homestead_difficulty(t, t | nil, integer(), integer(), integer()) :: integer()
def get_homestead_difficulty(
header,
parent_header,
initial_difficulty \\ @initial_difficulty,
minimum_difficulty \\ @minimum_difficulty,
difficulty_bound_divisor \\ @difficulty_bound_divisor
) do
if header.number == 0 do
initial_difficulty
else
difficulty_delta =
difficulty_x(parent_header.difficulty, difficulty_bound_divisor) *
homestead_difficulty_parameter(header, parent_header)
next_difficulty = parent_header.difficulty + difficulty_delta + difficulty_e(header)
max(minimum_difficulty, next_difficulty)
end
end
@doc """
Calculates the difficulty of a new block header for Frontier. This implements
Eq.(41), Eq.(42), Eq.(43), Eq.(44), Eq.(45) and Eq.(46) of the Yellow Paper.
## Examples
iex> Block.Header.get_frontier_difficulty(
...> %Block.Header{number: 0, timestamp: 55},
...> nil
...> )
131_072
iex> Block.Header.get_frontier_difficulty(
...> %Block.Header{number: 1, timestamp: 1479642530},
...> %Block.Header{number: 0, timestamp: 0, difficulty: 1_048_576}
...> )
1_048_064
iex> Block.Header.get_frontier_difficulty(
...> %Block.Header{number: 33, timestamp: 66},
...> %Block.Header{number: 32, timestamp: 55, difficulty: 300_000}
...> )
300_146
iex> Block.Header.get_frontier_difficulty(
...> %Block.Header{number: 33, timestamp: 88},
...> %Block.Header{number: 32, timestamp: 55, difficulty: 300_000}
...> )
299_854
"""
@spec get_frontier_difficulty(t, t | nil, integer(), integer(), integer()) :: integer()
def get_frontier_difficulty(
header,
parent_header,
initial_difficulty \\ @initial_difficulty,
minimum_difficulty \\ @minimum_difficulty,
difficulty_bound_divisor \\ @difficulty_bound_divisor
) do
if header.number == 0 do
initial_difficulty
else
difficulty_delta =
difficulty_x(parent_header.difficulty, difficulty_bound_divisor) *
delta_sign(header, parent_header)
next_difficulty = parent_header.difficulty + difficulty_delta + difficulty_e(header)
max(minimum_difficulty, next_difficulty)
end
end
# Eq.(42) ς1 - Effectively decides if blocks are being mined too quicky or too slowly
@spec delta_sign(t, t) :: integer()
defp delta_sign(header, parent_header) do
if header.timestamp < parent_header.timestamp + @frontier_difficulty_adjustment,
do: 1,
else: -1
end
# Eq.(43) ς2
@spec homestead_difficulty_parameter(t, t) :: integer()
defp homestead_difficulty_parameter(header, parent_header) do
s = div(header.timestamp - parent_header.timestamp, 10)
max(1 - s, -99)
end
@spec byzantium_difficulty_parameter(t, t) :: integer()
defp byzantium_difficulty_parameter(header, parent_header) do
s = div(header.timestamp - parent_header.timestamp, 9)
y = if parent_header.ommers_hash == @empty_keccak, do: 1, else: 2
max(y - s, -99)
end
# Eq.(41) x - Creates some multiplier for how much we should change difficulty based on previous difficulty
@spec difficulty_x(integer(), integer()) :: integer()
defp difficulty_x(parent_difficulty, difficulty_bound_divisor),
do: div(parent_difficulty, difficulty_bound_divisor)
# Eq.(46) H' - ε non negative
@spec byzantium_difficulty_e(t, integer()) :: integer()
defp byzantium_difficulty_e(header, delay_factor) do
fake_block_number_to_delay_ice_age = max(header.number - delay_factor, 0)
difficulty_exponent_calculation(fake_block_number_to_delay_ice_age)
end
# Eq.(44) ε - Adds a delta to ensure we're increasing difficulty over time
@spec difficulty_e(t) :: integer()
defp difficulty_e(header) do
difficulty_exponent_calculation(header.number)
end
defp difficulty_exponent_calculation(block_number) do
MathHelper.floor(:math.pow(2, div(block_number, 100_000) - 2))
end
@spec check_difficulty_validity([atom()], t, integer()) :: [atom()]
defp check_difficulty_validity(
errors,
header,
expected_difficulty
) do
if header.difficulty == expected_difficulty do
errors
else
[:invalid_difficulty | errors]
end
end
def check_extra_data_validity(errors, _header, false), do: errors
def check_extra_data_validity(errors, header, true) do
if header.extra_data == @dao_extra_data do
errors
else
[:invalid_extra_data | errors]
end
end
# Eq.(52)
@spec check_gas_limit([atom()], t) :: [atom()]
defp check_gas_limit(errors, header) do
if header.gas_used <= header.gas_limit do
errors
else
[:exceeded_gas_limit | errors]
end
end
# Eq.(53), Eq.(54) and Eq.(55)
@spec check_gas_limit_validity([atom()], t, EVM.Gas.t(), EVM.Gas.t(), EVM.Gas.t()) :: [atom()]
defp check_gas_limit_validity(
errors,
header,
parent_gas_limit,
gas_limit_bound_divisor,
min_gas_limit
) do
if is_gas_limit_valid?(
header.gas_limit,
parent_gas_limit,
gas_limit_bound_divisor,
min_gas_limit
) do
errors
else
[:invalid_gas_limit | errors]
end
end
# Eq.(56)
@spec check_child_timestamp_validity([atom()], t, t | nil) :: [atom()]
defp check_child_timestamp_validity(errors, header, parent_header) do
if is_nil(parent_header) or header.timestamp > parent_header.timestamp do
errors
else
[:child_timestamp_invalid | errors]
end
end
# Eq.(57)
@spec check_child_number_validity([atom()], t, t | nil) :: [atom()]
defp check_child_number_validity(errors, header, parent_header) do
if header.number == 0 or header.number == parent_header.number + 1 do
errors
else
[:child_number_invalid | errors]
end
end
@spec extra_data_validity([atom()], t) :: [atom()]
defp extra_data_validity(errors, header) do
if byte_size(header.extra_data) <= @max_extra_data_bytes do
errors
else
[:extra_data_too_large | errors]
end
end
@doc """
Function to determine if the gas limit set is valid.
The miner gets to specify a gas limit, so long as it's in range.
This allows about a 0.1% change per block.
This function directly implements Eq.(47).
## Examples
iex> Block.Header.is_gas_limit_valid?(1_000_000, nil)
true
iex> Block.Header.is_gas_limit_valid?(1_000, nil)
false
iex> Block.Header.is_gas_limit_valid?(1_000_000, 1_000_000)
true
iex> Block.Header.is_gas_limit_valid?(1_000_000, 2_000_000)
false
iex> Block.Header.is_gas_limit_valid?(1_000_000, 500_000)
false
iex> Block.Header.is_gas_limit_valid?(1_000_000, 999_500)
true
iex> Block.Header.is_gas_limit_valid?(1_000_000, 999_000)
false
iex> Block.Header.is_gas_limit_valid?(1_000_000, 2_000_000, 1)
true
iex> Block.Header.is_gas_limit_valid?(1_000, nil, 1024, 500)
true
"""
@spec is_gas_limit_valid?(EVM.Gas.t(), EVM.Gas.t() | nil) :: boolean()
def is_gas_limit_valid?(
gas_limit,
parent_gas_limit,
gas_limit_bound_divisor \\ @gas_limit_bound_divisor,
min_gas_limit \\ @min_gas_limit
) do
if parent_gas_limit == nil do
# It's not entirely clear from the Yellow Paper
# whether a genesis block should have any limits
# on gas limit, other than min gas limit.
gas_limit >= min_gas_limit
else
max_delta = MathHelper.floor(parent_gas_limit / gas_limit_bound_divisor)
gas_limit < parent_gas_limit + max_delta and gas_limit > parent_gas_limit - max_delta and
gas_limit >= min_gas_limit
end
end
@spec mined_by?(t, EVM.address()) :: boolean()
def mined_by?(header, address), do: header.beneficiary == address
end
| 33.21169 | 352 | 0.644627 |
736437b50af4498a2e2ed651931a618563b34abe | 453 | exs | Elixir | test/krasukha/iterative_gen_test.exs | Zatvobor/krasukha | ac6d2aa1dbd14039817a606c1347058bf1deab31 | [
"MIT"
] | 6 | 2017-01-28T01:11:58.000Z | 2021-12-19T22:45:49.000Z | test/krasukha/iterative_gen_test.exs | Zatvobor/krasukha | ac6d2aa1dbd14039817a606c1347058bf1deab31 | [
"MIT"
] | null | null | null | test/krasukha/iterative_gen_test.exs | Zatvobor/krasukha | ac6d2aa1dbd14039817a606c1347058bf1deab31 | [
"MIT"
] | null | null | null | alias Krasukha.{IterativeGen}
defmodule Krasukha.IterativeGenTest do
use ExUnit.Case, async: true
setup do
{:ok, pid} = IterativeGen.start_link(%{server: :untitled, request: :empty})
{:ok, [server: pid]}
end
describe "server behavior" do
test "process is alive", %{server: pid} do
assert Process.alive?(pid)
end
test "process terminates", %{server: pid} do
assert :ok == GenServer.stop(pid)
end
end
end
| 21.571429 | 79 | 0.657837 |
7364a2ac4110376b5e86f84fddb34af5b85a1b13 | 522 | exs | Elixir | apps/repository/priv/repo/migrations/20180103193234_create_notifications.exs | gitter-badger/opensubs.io | 76d5b4d355a530c8f496efe3ac2095d87f078997 | [
"MIT"
] | 36 | 2018-02-03T10:58:51.000Z | 2020-09-19T20:52:17.000Z | apps/repository/priv/repo/migrations/20180103193234_create_notifications.exs | joaquimadraz/subs | 9a26144ed660d5ece849ee447a9e5de53a311408 | [
"MIT"
] | 8 | 2018-01-17T17:15:48.000Z | 2020-07-06T08:56:54.000Z | apps/repository/priv/repo/migrations/20180103193234_create_notifications.exs | joaquimadraz/subs | 9a26144ed660d5ece849ee447a9e5de53a311408 | [
"MIT"
] | 10 | 2018-05-21T18:20:32.000Z | 2022-01-29T14:25:48.000Z | defmodule Repository.Repo.Migrations.CreateNotifications do
use Ecto.Migration
def change do
create table(:notifications) do
add(:to, :string, null: false)
add(:title, :string, null: false)
add(:body, :text, null: false)
add(:notify_at, :naive_datetime, null: false)
add(:status, :integer, default: 0, null: false)
add(:failure_reason, :string)
add(:try_deliver_at, :naive_datetime)
timestamps()
end
create(index("notifications", [:notify_at]))
end
end
| 26.1 | 59 | 0.659004 |
7364fae604eb0dfc1c390d0572ad3342bd62ee45 | 894 | exs | Elixir | bench/basic_bench.exs | minibikini/paasaa | 7ba881492a4102e036458a7bd232132db1271869 | [
"MIT"
] | 96 | 2016-08-31T18:31:23.000Z | 2022-02-06T18:49:19.000Z | bench/basic_bench.exs | minibikini/paasaa | 7ba881492a4102e036458a7bd232132db1271869 | [
"MIT"
] | 13 | 2016-09-05T13:30:09.000Z | 2020-07-07T10:55:42.000Z | bench/basic_bench.exs | minibikini/paasaa | 7ba881492a4102e036458a7bd232132db1271869 | [
"MIT"
] | 12 | 2016-09-04T18:16:08.000Z | 2021-10-17T15:03:57.000Z | defmodule BasicBench do
use Benchfella
@fixtures Paasaa.Support.Fixtures.fixtures()
@support Paasaa.Support.Fixtures.support()
|> Enum.take(10)
|> Enum.with_index()
Enum.each(@support, fn {language, index} ->
@index index
@input Enum.at(@fixtures, @index)
bench "[#{index}] #{language["name"]} (#{language["udhr"]})" do
Paasaa.detect(@input)
end
end)
@english_short Enum.at(@fixtures, 2)
@english_long File.read!("./bench/english.txt")
bench "English (Short Text)" do
Paasaa.detect(@english_short)
end
bench "English (Long Text)" do
Paasaa.detect(@english_long)
end
bench "detect_script English (Short Text)" do
Paasaa.detect_script(@english_short)
end
@english_max String.slice(@english_long, 0, 2048)
bench "detect_script English (Long Text)" do
Paasaa.detect_script(@english_max)
end
end
| 21.804878 | 67 | 0.667785 |
736504c064e77341f579a918fad52ea7692fc438 | 334 | ex | Elixir | lib/infinity_one_web/views/sidebar_view.ex | smpallen99/ucx_ucc | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 11 | 2017-05-15T18:35:05.000Z | 2018-02-05T18:27:40.000Z | lib/infinity_one_web/views/sidebar_view.ex | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 15 | 2017-11-27T10:38:05.000Z | 2018-02-09T20:42:08.000Z | lib/infinity_one_web/views/sidebar_view.ex | anndream/infinity_one | 47225f205a6ac4aacdb9bb4f7512dcf4092576ad | [
"MIT"
] | 4 | 2017-09-13T11:34:16.000Z | 2018-02-26T13:37:06.000Z | defmodule InfinityOneWeb.SidebarView do
use InfinityOneWeb, :view
def username(conn) do
Coherence.current_user(conn) |> Map.get(:username)
end
# def avatar_url(username) when is_binary(username) do
# "/avatar/" <> username
# end
def current_user_avatar_url(conn) do
conn |> username |> avatar_url
end
end
| 20.875 | 56 | 0.709581 |
73652ec7e758d4d77e29fd53b0e3788212ecdcb9 | 61 | ex | Elixir | lib/mipha_web/views/location_view.ex | ZPVIP/mipha | a7df054f72eec7de88b60d94c501488375bdff6a | [
"MIT"
] | 156 | 2018-06-01T19:52:32.000Z | 2022-02-03T10:58:10.000Z | lib/mipha_web/views/location_view.ex | ZPVIP/mipha | a7df054f72eec7de88b60d94c501488375bdff6a | [
"MIT"
] | 139 | 2018-07-10T01:57:23.000Z | 2021-08-02T21:29:24.000Z | lib/mipha_web/views/location_view.ex | ZPVIP/mipha | a7df054f72eec7de88b60d94c501488375bdff6a | [
"MIT"
] | 29 | 2018-07-17T08:43:45.000Z | 2021-12-14T13:45:30.000Z | defmodule MiphaWeb.LocationView do
use MiphaWeb, :view
end
| 15.25 | 34 | 0.803279 |
736536136cde8c6516520221054e4145888972c2 | 1,565 | ex | Elixir | clients/content/lib/google_api/content/v2/model/shippingsettings_custom_batch_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/shippingsettings_custom_batch_request.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/shippingsettings_custom_batch_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 "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.Content.V2.Model.ShippingsettingsCustomBatchRequest do
@moduledoc """
## Attributes
- entries (List[ShippingsettingsCustomBatchRequestEntry]): The request entries to be processed in the batch. Defaults to: `null`.
"""
defstruct [
:"entries"
]
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.ShippingsettingsCustomBatchRequest do
import GoogleApi.Content.V2.Deserializer
def decode(value, options) do
value
|> deserialize(:"entries", :list, GoogleApi.Content.V2.Model.ShippingsettingsCustomBatchRequestEntry, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.ShippingsettingsCustomBatchRequest do
def encode(value, options) do
GoogleApi.Content.V2.Deserializer.serialize_non_nil(value, options)
end
end
| 32.604167 | 131 | 0.76869 |
7365419f891310856461ea681f656107fa24429f | 496 | exs | Elixir | test/go_champs_api_web/views/error_view_test.exs | lairjr/go_champs_api | 01cb3ff2c655910839e5caf4282a8e50543e32a1 | [
"MIT"
] | null | null | null | test/go_champs_api_web/views/error_view_test.exs | lairjr/go_champs_api | 01cb3ff2c655910839e5caf4282a8e50543e32a1 | [
"MIT"
] | 5 | 2021-09-29T04:01:54.000Z | 2021-11-02T03:11:52.000Z | test/go_champs_api_web/views/error_view_test.exs | lairjr/tournamentsapi | dde8f8f659074527d3861391af3ab29f070179f2 | [
"MIT"
] | 1 | 2021-11-02T14:43:15.000Z | 2021-11-02T14:43:15.000Z | defmodule GoChampsApiWeb.ErrorViewTest do
use GoChampsApiWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.json" do
assert render(GoChampsApiWeb.ErrorView, "404.json", []) == %{
errors: %{detail: "Not Found"}
}
end
test "renders 500.json" do
assert render(GoChampsApiWeb.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| 27.555556 | 66 | 0.657258 |
73657525ec51e1ea840583d69b85cb7a98563548 | 1,022 | ex | Elixir | lib/changelog/data/data.ex | boneskull/changelog.com | 2fa2e356bb0e8fcf038c46a4a947fef98822e37d | [
"MIT"
] | null | null | null | lib/changelog/data/data.ex | boneskull/changelog.com | 2fa2e356bb0e8fcf038c46a4a947fef98822e37d | [
"MIT"
] | null | null | null | lib/changelog/data/data.ex | boneskull/changelog.com | 2fa2e356bb0e8fcf038c46a4a947fef98822e37d | [
"MIT"
] | null | null | null | defmodule Changelog.Data do
defmacro __using__(opts) do
opts = Keyword.merge([default_sort: :inserted_at], opts)
quote do
use Ecto.Schema
use Changelog.Arc.Ecto.Schema
use Timex.Ecto.Timestamps
import Ecto
import Ecto.Changeset
import Ecto.Query, only: [from: 1, from: 2]
import EctoEnum, only: [defenum: 2]
alias Changelog.Repo
def by_position(query \\ __MODULE__), do: from(q in query, order_by: q.position)
def limit(query \\ __MODULE__, count), do: from(q in query, limit: ^count)
def newest_first(query \\ __MODULE__, field \\ unquote(opts[:default_sort])), do: from(q in query, order_by: [desc: ^field])
def newest_last(query \\ __MODULE__, field \\ unquote(opts[:default_sort])), do: from(q in query, order_by: [asc: ^field])
defp mark_for_deletion(changeset) do
if get_change(changeset, :delete) do
%{changeset | action: :delete}
else
changeset
end
end
end
end
end
| 31.9375 | 130 | 0.642857 |
736589bc32cecf4660c353eaefb9b137d9029a5a | 1,062 | ex | Elixir | lib/mix/tasks/bootstrap.ex | NeoArcanjo/aws-lambda-runtime-boilerplate | dcd3beded406b3b98f624c50e56f92235381f0b1 | [
"MIT-0"
] | null | null | null | lib/mix/tasks/bootstrap.ex | NeoArcanjo/aws-lambda-runtime-boilerplate | dcd3beded406b3b98f624c50e56f92235381f0b1 | [
"MIT-0"
] | null | null | null | lib/mix/tasks/bootstrap.ex | NeoArcanjo/aws-lambda-runtime-boilerplate | dcd3beded406b3b98f624c50e56f92235381f0b1 | [
"MIT-0"
] | null | null | null | # Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
defmodule Mix.Tasks.Bootstrap do
@moduledoc """
Generate a bootstrap script for the project in the release directory.
This task will fail if it's run before `mix release`.
"""
use Mix.Task
@runtime_libs "elixir_runtime-0.1.0/priv"
@shortdoc "Generate a bootstrap script for the project"
def run(_) do
name =
Mix.Project.config()
|> Keyword.fetch!(:app)
|> to_string
path = "_build/#{Mix.env()}/rel/#{name}/bootstrap"
Mix.Generator.create_file(path, bootstrap(name))
File.chmod!(path, 0o777)
end
# The bootstrap script contents
defp bootstrap(app) when is_binary(app) do
"""
\#!/bin/bash
set -x
BASE=$(dirname "$0")
EXE=$BASE/bin/#{app}
HOME=/tmp
export HOME
\# So that distillery doesn't try to write any files
export RELEASE_READ_ONLY=true
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$BASE/lib/#{@runtime_libs}
$EXE foreground
"""
end
end
| 21.673469 | 73 | 0.663842 |
7365b004f11a7637383fdf843b332d2e27e49047 | 1,889 | exs | Elixir | deps/postgrex/mix.exs | matin360/TaksoWebApp | 4dd8fef625ecc2364fe1d6e18e73c96c59d15349 | [
"MIT"
] | null | null | null | deps/postgrex/mix.exs | matin360/TaksoWebApp | 4dd8fef625ecc2364fe1d6e18e73c96c59d15349 | [
"MIT"
] | null | null | null | deps/postgrex/mix.exs | matin360/TaksoWebApp | 4dd8fef625ecc2364fe1d6e18e73c96c59d15349 | [
"MIT"
] | null | null | null | defmodule Postgrex.Mixfile do
use Mix.Project
@source_url "https://github.com/elixir-ecto/postgrex"
@version "0.15.11"
def project do
[
app: :postgrex,
version: @version,
elixir: "~> 1.6",
deps: deps(),
name: "Postgrex",
description: "PostgreSQL driver for Elixir",
docs: docs(),
package: package(),
xref: [exclude: [Jason, :ssl]]
]
end
# Configuration for the OTP application
def application do
[
extra_applications: [:logger, :crypto],
mod: {Postgrex.App, []},
env: [type_server_reap_after: 3 * 60_000, json_library: Jason]
]
end
defp deps do
[
{:ex_doc, ">= 0.0.0", only: :docs},
{:jason, "~> 1.0", optional: true},
{:decimal, "~> 1.5 or ~> 2.0"},
{:db_connection, "~> 2.1"},
{:connection, "~> 1.0"}
]
end
defp docs do
[
source_url: @source_url,
source_ref: "v#{@version}",
main: "readme",
extras: ["README.md", "CHANGELOG.md"],
skip_undefined_reference_warnings_on: ["CHANGELOG.md"],
groups_for_modules: [
# Postgrex
# Postgrex.Notifications
# Postgrex.Query
# Postgrex.Result
"Data Types": [
Postgrex.Box,
Postgrex.Circle,
Postgrex.INET,
Postgrex.Interval,
Postgrex.Lexeme,
Postgrex.Line,
Postgrex.LineSegment,
Postgrex.MACADDR,
Postgrex.Path,
Postgrex.Point,
Postgrex.Polygon,
Postgrex.Range
],
"Custom types and Extensions": [
Postgrex.Extension,
Postgrex.TypeInfo,
Postgrex.Types
]
]
]
end
defp package do
[
maintainers: ["Eric Meadows-Jönsson", "James Fish"],
licenses: ["Apache-2.0"],
links: %{"GitHub" => @source_url}
]
end
end
| 22.759036 | 68 | 0.538909 |
7365cde01f6eb8431972439312a23d32222728bb | 1,619 | exs | Elixir | mix.exs | davejlong/ueberauth_spotify | 2e44e4136a8236ce85f4cde4599f2d6f414a5314 | [
"MIT"
] | 2 | 2017-12-02T18:55:13.000Z | 2019-05-16T09:27:51.000Z | mix.exs | davejlong/ueberauth_spotify | 2e44e4136a8236ce85f4cde4599f2d6f414a5314 | [
"MIT"
] | 2 | 2017-12-02T21:09:33.000Z | 2019-01-22T02:04:50.000Z | mix.exs | davejlong/ueberauth_spotify | 2e44e4136a8236ce85f4cde4599f2d6f414a5314 | [
"MIT"
] | 3 | 2017-12-06T15:13:10.000Z | 2019-01-21T02:14:40.000Z | defmodule UeberauthSpotify.Mixfile do
use Mix.Project
@url "https://github.com/davejlong/ueberauth_spotify"
@version "0.0.2"
def project do
[app: :ueberauth_spotify,
version: @version,
elixir: "~> 1.4",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
name: "Ueberauth Spotify Strategy",
source_url: @url,
homepage_url: @url,
description: description(),
deps: deps(),
docs: docs(),
package: package()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
# Specify extra applications you'll use from Erlang/Elixir
[extra_applications: [:logger, :oauth2, :ueberauth]]
end
# Dependencies can be Hex packages:
#
# {:my_dep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:my_dep, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[{:ueberauth, "~> 0.4"},
{:oauth2, "~> 0.9"},
{:credo, "~> 0.8", only: :dev, runtime: false},
{:ex_doc, "~> 0.14", only: :dev, runtime: false}]
end
defp docs do
[extras: ["README.md", "CONTRIBUTING.md"]]
end
defp package do
[name: :ueberauth_spotify_oauth,
files: ["lib", "mix.exs", "README.md", "LICENSE"],
maintainers: ["Dave Long"],
licenses: ["MIT"],
links: %{"GitHub": @url}]
end
defp description do
"""
An Ueberauth strategy for Spotify authentication
"""
end
end
| 24.907692 | 80 | 0.584929 |
73660aef29ead81ab02ad01f0d96b500052781ed | 1,865 | ex | Elixir | lib/web/controllers/admin/item_aspect_controller.ex | stevegrossi/ex_venture | e02d5a63fdb882d92cfb4af3e15f7b48ad7054aa | [
"MIT"
] | 2 | 2019-05-14T11:36:44.000Z | 2020-07-01T08:54:04.000Z | lib/web/controllers/admin/item_aspect_controller.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | null | null | null | lib/web/controllers/admin/item_aspect_controller.ex | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | 1 | 2021-01-29T14:12:40.000Z | 2021-01-29T14:12:40.000Z | defmodule Web.Admin.ItemAspectController do
use Web.AdminController
alias Web.ItemAspect
def index(conn, _params) do
item_aspects = ItemAspect.all()
conn
|> assign(:item_aspects, item_aspects)
|> render("index.html")
end
def show(conn, %{"id" => id}) do
item_aspect = ItemAspect.get(id)
conn
|> assign(:item_aspect, item_aspect)
|> render("show.html")
end
def new(conn, _params) do
changeset = ItemAspect.new()
conn
|> assign(:changeset, changeset)
|> render("new.html")
end
def create(conn, %{"item_aspect" => params}) do
case ItemAspect.create(params) do
{:ok, item_aspect} ->
conn
|> put_flash(:info, "Created #{item_aspect.name}!")
|> redirect(to: item_aspect_path(conn, :show, item_aspect.id))
{:error, changeset} ->
conn
|> put_flash(:error, "There was an issue creating the item aspect. Please try again.")
|> assign(:changeset, changeset)
|> render("new.html")
end
end
def edit(conn, %{"id" => id}) do
item_aspect = ItemAspect.get(id)
changeset = ItemAspect.edit(item_aspect)
conn
|> assign(:item_aspect, item_aspect)
|> assign(:changeset, changeset)
|> render("edit.html")
end
def update(conn, %{"id" => id, "item_aspect" => params}) do
case ItemAspect.update(id, params) do
{:ok, item_aspect} ->
conn
|> put_flash(:info, "#{item_aspect.name} updated!")
|> redirect(to: item_aspect_path(conn, :show, item_aspect.id))
{:error, changeset} ->
item_aspect = ItemAspect.get(id)
conn
|> put_flash(:error, "There was an issue updating #{item_aspect.name}. Please try again.")
|> assign(:item_aspect, item_aspect)
|> assign(:changeset, changeset)
|> render("edit.html")
end
end
end
| 25.547945 | 98 | 0.609651 |
7366206a39a4c68ff57036b936093e7e99ef0225 | 901 | exs | Elixir | test/authex/load_current_resource_test.exs | Waasi/authex | 8e1c55ccbbbcef72bd958080e42c1e1b53359029 | [
"MIT"
] | 3 | 2016-12-17T13:36:16.000Z | 2017-01-28T11:17:23.000Z | test/authex/load_current_resource_test.exs | Waasi/authex | 8e1c55ccbbbcef72bd958080e42c1e1b53359029 | [
"MIT"
] | null | null | null | test/authex/load_current_resource_test.exs | Waasi/authex | 8e1c55ccbbbcef72bd958080e42c1e1b53359029 | [
"MIT"
] | null | null | null | defmodule Authex.LoadCurrentResourceTest do
use ExUnit.Case, async: true
use Plug.Test
alias Authex.TokenAuth
alias Authex.LoadCurrentResource
setup do
Application.put_env(:authex, :auth_id, TestHelpers.audience)
Application.put_env(:authex, :auth_secret, Base.url_encode64(TestHelpers.secret))
valid_conn = conn(:get, "/test") |> put_req_header("authorization", TestHelpers.token) |> TokenAuth.call(%{})
invalid_conn = conn(:get, "/test")
{:ok, valid: valid_conn, invalid: invalid_conn}
end
test "with valid token", %{valid: valid} do
conn = valid |> LoadCurrentResource.call(model: User, repo: Repo)
assert conn.assigns[:current_resource] == Repo.get(User, 1)
end
test "with invalid token", %{invalid: invalid} do
conn = invalid |> LoadCurrentResource.call(model: User, repo: Repo)
assert conn.assigns[:current_resource] == nil
end
end
| 31.068966 | 113 | 0.713651 |
73666b3399493ced79a70e242c8f48b2ef6f4caa | 1,416 | exs | Elixir | test/wabanex_web/schema_test.exs | EternalLearnerProgramming/Wabanex-NLW | a6fb37af9867d15b723c928ee6eb1a9a24b40925 | [
"MIT"
] | 61 | 2021-06-22T00:15:59.000Z | 2022-01-31T15:13:51.000Z | test/wabanex_web/schema_test.exs | EternalLearnerProgramming/Wabanex-NLW | a6fb37af9867d15b723c928ee6eb1a9a24b40925 | [
"MIT"
] | null | null | null | test/wabanex_web/schema_test.exs | EternalLearnerProgramming/Wabanex-NLW | a6fb37af9867d15b723c928ee6eb1a9a24b40925 | [
"MIT"
] | 56 | 2021-06-21T17:17:36.000Z | 2022-03-15T02:48:59.000Z | defmodule WabanexWeb.SchemaTest do
use WabanexWeb.ConnCase, async: true
alias Wabanex.User
alias Wabanex.Users.Create
describe "users queries" do
test "when a valid id is give, returns the user", %{conn: conn} do
params = %{email: "[email protected]", name: "Jp", password: "123456"}
{:ok, %User{id: user_id}} = Create.call(params)
query = """
{
getUser(id: "#{user_id}"){
id
name
email
}
}
"""
response =
conn
|> post("/api/graphql", %{query: query})
|> json_response(:ok)
expected_response = %{
"data" => %{
"getUser" => %{
"email" => "[email protected]",
"id" => user_id,
"name" => "Jp"
}
}
}
assert response == expected_response
end
end
describe "users mutations" do
test "when all params are valid, creates the user", %{conn: conn} do
mutation = """
mutation {
createUser(input: {
name: "Joao", email: "[email protected]", password: "123456"
}){
id
name
}
}
"""
response =
conn
|> post("/api/graphql", %{query: mutation})
|> json_response(:ok)
assert %{"data" => %{"createUser" => %{"id" => _id, "name" => "Joao"}}} = response
end
end
end
| 22.125 | 88 | 0.475989 |
7366903ed0edc5638210224808cedc8688d34bb3 | 5,147 | exs | Elixir | test/web/controllers/submission_invite_controller_test.exs | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | null | null | null | test/web/controllers/submission_invite_controller_test.exs | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | null | null | null | test/web/controllers/submission_invite_controller_test.exs | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | null | null | null | defmodule Web.SubmissionInviteControllerTest do
use Web.ConnCase
alias ChallengeGov.Submissions
alias ChallengeGov.SubmissionInvites
alias ChallengeGov.TestHelpers.AccountHelpers
alias ChallengeGov.TestHelpers.ChallengeHelpers
alias ChallengeGov.TestHelpers.SubmissionHelpers
describe "index" do
test "success: as super admin", %{conn: conn} do
user = AccountHelpers.create_user(%{role: "super_admin"})
conn = prep_conn(conn, user)
user2 = AccountHelpers.create_user(%{email: "[email protected]", role: "challenge_owner"})
challenge = ChallengeHelpers.create_single_phase_challenge(user2, %{user_id: user2.id})
phase = Enum.at(challenge.phases, 0)
submissions =
Submissions.all(filter: %{"phase_id" => phase.id, "judging_status" => "winner"})
conn = get(conn, Routes.submission_invite_path(conn, :index, phase.id))
%{
user: user_in_assigns,
challenge: _challenge,
submissions: submissions_in_assigns
} = conn.assigns
assert user === user_in_assigns
assert submissions === submissions_in_assigns
assert html_response(conn, 200)
end
end
describe "show" do
test "success: as super admin", %{conn: conn} do
user = AccountHelpers.create_user(%{role: "super_admin"})
conn = prep_conn(conn, user)
challenge = ChallengeHelpers.create_single_phase_challenge(user, %{user_id: user.id})
phase = Enum.at(challenge.phases, 0)
solver = AccountHelpers.create_user(%{email: "[email protected]"})
submission = SubmissionHelpers.create_submitted_submission(%{}, solver, challenge)
params = %{
"message" => "message text",
"message_delta" => "message delta"
}
{:ok, submission_invite} = SubmissionInvites.create(params, submission)
conn = get(conn, Routes.submission_invite_path(conn, :show, phase.id, submission_invite.id))
assert html_response(conn, 200)
end
end
describe "bulk create" do
test "success: as super admin", %{conn: conn} do
user = AccountHelpers.create_user(%{role: "super_admin"})
conn = prep_conn(conn, user)
challenge = ChallengeHelpers.create_single_phase_challenge(user, %{user_id: user.id})
phase = Enum.at(challenge.phases, 0)
solver = AccountHelpers.create_user(%{email: "[email protected]"})
submission1 = SubmissionHelpers.create_submitted_submission(%{}, solver, challenge)
submission2 = SubmissionHelpers.create_submitted_submission(%{}, solver, challenge)
submission3 = SubmissionHelpers.create_submitted_submission(%{}, solver, challenge)
submission_ids = [
submission1.id,
submission2.id,
submission3.id
]
params = %{
"message" => "message text",
"message_delta" => "message delta",
"submission_ids" => submission_ids
}
conn = post(conn, Routes.submission_invite_path(conn, :create, phase.id, params))
assert redirected_to(conn) == Routes.submission_invite_path(conn, :index, phase.id)
end
end
describe "accept" do
test "success", %{conn: conn} do
user = AccountHelpers.create_user(%{role: "super_admin"})
challenge = ChallengeHelpers.create_single_phase_challenge(user, %{user_id: user.id})
phase = Enum.at(challenge.phases, 0)
solver = AccountHelpers.create_user(%{email: "[email protected]"})
submission = SubmissionHelpers.create_submitted_submission(%{}, solver, challenge, phase)
conn = prep_conn(conn, solver)
params = %{
"message" => "message text",
"message_delta" => "message delta"
}
{:ok, submission_invite} = SubmissionInvites.create(params, submission)
conn = post(conn, Routes.submission_invite_path(conn, :accept, submission_invite.id))
{:ok, submission_invite} = SubmissionInvites.get(submission_invite.id)
assert submission_invite.status === "accepted"
assert html_response(conn, 200)
end
end
describe "revoke" do
test "success", %{conn: conn} do
user = AccountHelpers.create_user(%{role: "super_admin"})
conn = prep_conn(conn, user)
challenge = ChallengeHelpers.create_single_phase_challenge(user, %{user_id: user.id})
phase = Enum.at(challenge.phases, 0)
solver = AccountHelpers.create_user(%{email: "[email protected]"})
submission = SubmissionHelpers.create_submitted_submission(%{}, solver, challenge, phase)
params = %{
"message" => "message text",
"message_delta" => "message delta"
}
{:ok, submission_invite} = SubmissionInvites.create(params, submission)
conn = post(conn, Routes.submission_invite_path(conn, :revoke, submission_invite.id))
{:ok, submission_invite} = SubmissionInvites.get(submission_invite.id)
assert submission_invite.status === "revoked"
assert get_flash(conn, :error) == "Invite revoked"
assert redirected_to(conn) == Routes.submission_invite_path(conn, :index, phase.id)
end
end
defp prep_conn(conn, user) do
assign(conn, :current_user, user)
end
end
| 34.086093 | 98 | 0.682145 |
736696a92ee834c1caade0b71e2b10794dd83a5a | 608 | exs | Elixir | mix.exs | sjanota/castles | a890a1acf8c33a7cf7d6c49759387ea4dd4ce37a | [
"Apache-2.0"
] | null | null | null | mix.exs | sjanota/castles | a890a1acf8c33a7cf7d6c49759387ea4dd4ce37a | [
"Apache-2.0"
] | null | null | null | mix.exs | sjanota/castles | a890a1acf8c33a7cf7d6c49759387ea4dd4ce37a | [
"Apache-2.0"
] | null | null | null | defmodule Castles.Mixfile do
use Mix.Project
def project do
[apps_path: "apps",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps()]
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.
#
# Dependencies listed here are available only for this project
# and cannot be accessed from applications inside the apps folder
defp deps do
[]
end
end
| 22.518519 | 77 | 0.638158 |
73669dd3d3b63b3581ef2a5635a9da4e6910d459 | 699 | exs | Elixir | mix.exs | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | 7 | 2016-12-25T08:26:08.000Z | 2021-08-15T01:23:53.000Z | mix.exs | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | null | null | null | mix.exs | youroff/monex | fe7d78880e41dc946fc9e2e3a0a133f3b380a39a | [
"MIT"
] | 1 | 2020-09-07T06:59:55.000Z | 2020-09-07T06:59:55.000Z | defmodule Monex.Mixfile do
use Mix.Project
def project do
[app: :monex,
version: "0.1.17",
elixir: "~> 1.4",
description: description(),
package: package(),
deps: deps()]
end
def application, do: []
defp deps, do: [
{:dialyxir, "~> 1.0.0-rc.4", only: [:dev], runtime: false},
{:ex_doc, "~> 0.19", only: :dev}
]
defp description do
"""
Monadic types collection. Option (Maybe) - some(val)/none(). Result - ok(val)/error(err).
"""
end
defp package, do: [
files: ["lib", "mix.exs", "README*", "LICENSE*"],
maintainers: ["Ivan Yurov"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/youroff/monex"}
]
end
| 21.84375 | 93 | 0.559371 |
73669f8186c75062b816e242a5ce31aeca6d1bd8 | 1,687 | exs | Elixir | test/silicon/hmac_test.exs | LanfordCai/silicon | 2a4f99f410a6f64b6300e1f12aa38dd535c08a81 | [
"MIT"
] | 2 | 2019-04-17T14:51:19.000Z | 2019-04-18T04:21:16.000Z | test/silicon/hmac_test.exs | LanfordCai/silicon | 2a4f99f410a6f64b6300e1f12aa38dd535c08a81 | [
"MIT"
] | null | null | null | test/silicon/hmac_test.exs | LanfordCai/silicon | 2a4f99f410a6f64b6300e1f12aa38dd535c08a81 | [
"MIT"
] | null | null | null | defmodule Silicon.HmacTest do
@moduledoc """
1. HMAC_SHA256/SHA512
https://cryptii.com
"""
use ExUnit.Case
import Silicon.Hmac
describe "hmac" do
test "hmac sha256" do
key = "silicon"
msg = ""
assert Base.encode16(hmac_sha256(key, msg), case: :lower) ==
"5e904c41231f5879543f6846efc9b7438e5d150835256ce5fbc0eeba5f5d1d65"
msg = "The quick brown fox jumps over the lazy dog"
assert Base.encode16(hmac_sha256(key, msg), case: :lower) ==
"5f6f68a9496c0c508d17ea63fa4b22ad44879f69ce0e3e40cd8c1bbbbf539055"
msg = "How many roads must a man walk down, before you call him a man?"
assert Base.encode16(hmac_sha256(key, msg), case: :lower) ==
"e3178e7f4167c85e0429ca1a62a702266178281f19202048d06886a2650a4fc9"
end
test "hmac sha512" do
key = "silicon"
msg = ""
assert Base.encode16(hmac_sha512(key, msg), case: :lower) ==
"fdd101342d060493af38a586d6a7870523f1086b607ba4972d088141f966f89376d313cdeb2a3d4583e15db3dea331c24939449c21959fcc0b4cfed5e2ee0f99"
msg = "The quick brown fox jumps over the lazy dog"
assert Base.encode16(hmac_sha512(key, msg), case: :lower) ==
"d780d28706f5f3fb72ee098ddb38846a8f640947c698a314ac478945c35871661596d632fd1640d24ae1dac5c94d36fe24d3c554220e033174f2be0bb62ac607"
msg = "How many roads must a man walk down, before you call him a man?"
assert Base.encode16(hmac_sha512(key, msg), case: :lower) ==
"6b8ac9a041586b269888778d0f938856d132dbc1cf186606e104f57552190490564919b35886620739a8e03739bf0fd49ab212f90f9a76164ac78d904f75cca6"
end
end
end
| 33.74 | 145 | 0.711322 |
7366bc289271d9a73f1423d4163636222184840f | 1,445 | exs | Elixir | mix.exs | c-kaieong/caravan | e639364e0e725eb5b5c80aeac473c2151db47165 | [
"Apache-2.0"
] | 55 | 2018-01-16T16:42:15.000Z | 2022-03-10T09:16:57.000Z | mix.exs | c-kaieong/caravan | e639364e0e725eb5b5c80aeac473c2151db47165 | [
"Apache-2.0"
] | 7 | 2018-03-29T13:21:46.000Z | 2021-05-07T18:33:43.000Z | mix.exs | c-kaieong/caravan | e639364e0e725eb5b5c80aeac473c2151db47165 | [
"Apache-2.0"
] | 5 | 2018-03-27T15:01:22.000Z | 2021-05-27T14:50:48.000Z | defmodule Caravan.Mixfile do
use Mix.Project
def project do
[
app: :caravan,
version: "1.0.0",
elixir: "~> 1.6",
start_permanent: Mix.env() == :prod,
description: description(),
package: package(),
docs: docs(),
deps: deps(),
dialyzer: [plt_add_apps: [:libcluster]],
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
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
[
{:ex_doc, "~> 0.19-rc", only: :dev, runtime: false},
{:excoveralls, "~> 0.8", only: :test},
{:libcluster, "~> 3.0", optional: true},
{:recon, "~> 2.3", optional: true},
{:dialyxir, "~> 1.0.0-rc.3", only: [:dev], runtime: false}
]
end
defp docs do
[main: Caravan]
end
defp package do
[
files: ["lib", "mix.exs", "README.md", "LICENSE"],
maintainers: ["Chris Brodt"],
licenses: ["Apache 2.0"],
source_url: "https://github.com/uberbrodt/caravan",
links: %{"Github" => "https://github.com/uberbrodt/caravan"}
]
end
defp description, do: "Tools for running Distributed Elixir with Nomad and Consul"
end
| 24.491525 | 84 | 0.568166 |
7366f793fcbd055ecf4542a3a887a41b791c2e45 | 1,724 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_reload_document_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_reload_document_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_v2_reload_document_request.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2ReloadDocumentRequest do
@moduledoc """
Request message for Documents.ReloadDocument.
## Attributes
* `contentUri` (*type:* `String.t`, *default:* `nil`) - Optional. The path of gcs source file for reloading document content. For now, only gcs uri is supported. For documents stored in Google Cloud Storage, these URIs must have the form `gs:///`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:contentUri => String.t() | nil
}
field(:contentUri)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2ReloadDocumentRequest do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2ReloadDocumentRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowV2ReloadDocumentRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.153846 | 251 | 0.74942 |
73670005709d398427a7861f51312dcff61fde57 | 20,588 | exs | Elixir | test/ecto/changeset/belongs_to_test.exs | adbatista/ecto | ab63701cf9b3ceab6ddf54c87d549abe24e1248a | [
"Apache-2.0"
] | 2 | 2021-02-25T15:51:16.000Z | 2021-02-25T18:42:35.000Z | test/ecto/changeset/belongs_to_test.exs | adbatista/ecto | ab63701cf9b3ceab6ddf54c87d549abe24e1248a | [
"Apache-2.0"
] | 1 | 2021-03-09T16:43:23.000Z | 2021-03-09T16:43:23.000Z | test/ecto/changeset/belongs_to_test.exs | adbatista/ecto | ab63701cf9b3ceab6ddf54c87d549abe24e1248a | [
"Apache-2.0"
] | 1 | 2018-06-18T14:47:58.000Z | 2018-06-18T14:47:58.000Z | defmodule Ecto.Changeset.BelongsToTest do
use ExUnit.Case, async: true
alias Ecto.Changeset
alias Ecto.Changeset.Relation
alias Ecto.TestRepo
alias __MODULE__.Author
alias __MODULE__.Profile
defmodule Author do
use Ecto.Schema
schema "authors" do
field :title, :string
belongs_to :profile, {"authors_profiles", Profile},
on_replace: :delete, defaults: [name: "default"]
belongs_to :raise_profile, Profile, on_replace: :raise
belongs_to :invalid_profile, Profile, on_replace: :mark_as_invalid
belongs_to :update_profile, Profile, on_replace: :update, defaults: {__MODULE__, :send_to_self, [:extra]}
end
def send_to_self(struct, owner, extra) do
send(self(), {:defaults, struct, owner, extra})
%{struct | id: 13}
end
end
defmodule Profile do
use Ecto.Schema
schema "profiles" do
field :name
has_one :author, Author
end
def changeset(schema, params) do
Changeset.cast(schema, params, ~w(name id)a)
|> Changeset.validate_required(:name)
end
def optional_changeset(schema, params) do
Changeset.cast(schema, params, ~w(name)a)
end
def set_action(schema, params) do
changeset(schema, params)
|> Map.put(:action, Map.get(params, :action, :update))
end
end
defp cast(schema, params, assoc, opts \\ []) do
schema
|> Changeset.cast(params, ~w())
|> Changeset.cast_assoc(assoc, opts)
end
## cast belongs_to
test "cast belongs_to with valid params" do
changeset = cast(%Author{}, %{"profile" => %{"name" => "michal"}}, :profile)
profile = changeset.changes.profile
assert profile.changes == %{name: "michal"}
assert profile.errors == []
assert profile.action == :insert
assert profile.valid?
assert changeset.valid?
end
test "cast belongs_to with invalid params" do
changeset = cast(%Author{}, %{"profile" => %{name: nil}}, :profile)
assert changeset.changes.profile.changes == %{}
assert changeset.changes.profile.errors == [name: {"can't be blank", [validation: :required]}]
assert changeset.changes.profile.action == :insert
refute changeset.changes.profile.valid?
refute changeset.valid?
changeset = cast(%Author{}, %{"profile" => "value"}, :profile)
assert changeset.errors == [profile: {"is invalid", [validation: :assoc, type: :map]}]
refute changeset.valid?
end
test "cast belongs_to with existing struct updating" do
changeset = cast(%Author{profile: %Profile{name: "michal", id: 1}},
%{"profile" => %{"name" => "new", "id" => 1}}, :profile)
profile = changeset.changes.profile
assert profile.changes == %{name: "new"}
assert profile.errors == []
assert profile.action == :update
assert profile.valid?
assert changeset.valid?
end
test "cast belongs_to with empty value" do
assert cast(%Author{}, %{"profile" => nil}, :profile).changes == %{profile: nil}
assert cast(%Author{profile: nil}, %{"profile" => nil}, :profile).changes == %{}
assert cast(%Author{}, %{"profile" => ""}, :profile).changes == %{}
assert cast(%Author{profile: nil}, %{"profile" => ""}, :profile).changes == %{}
loaded = put_in %Author{}.__meta__.state, :loaded
assert_raise RuntimeError, ~r"attempting to cast or change association `profile` .* that was not loaded", fn ->
cast(loaded, %{"profile" => nil}, :profile)
end
assert_raise RuntimeError, ~r"attempting to cast or change association `profile` .* that was not loaded", fn ->
cast(loaded, %{"profile" => ""}, :profile)
end
assert cast(loaded, %{}, :profile).changes == %{}
end
test "cast belongs_to discards changesets marked as ignore" do
changeset = cast(%Author{},
%{"profile" => %{name: "michal", id: "id", action: :ignore}},
:profile, with: &Profile.set_action/2)
assert changeset.changes == %{}
end
test "cast belongs_to with existing struct replacing" do
changeset = cast(%Author{profile: %Profile{name: "michal", id: 1}},
%{"profile" => %{"name" => "new"}}, :profile)
profile = changeset.changes.profile
assert profile.changes == %{name: "new"}
assert profile.errors == []
assert profile.action == :insert
assert profile.valid?
assert changeset.valid?
changeset = cast(%Author{profile: %Profile{name: "michal", id: 2}},
%{"profile" => %{"name" => "new", "id" => 5}}, :profile)
profile = changeset.changes.profile
assert profile.changes == %{name: "new", id: 5}
assert profile.errors == []
assert profile.action == :insert
assert profile.valid?
assert changeset.valid?
assert_raise RuntimeError, ~r"cannot update related", fn ->
cast(%Author{profile: %Profile{name: "michal", id: "michal"}},
%{"profile" => %{"name" => "new", "id" => "new"}},
:profile, with: &Profile.set_action/2)
end
end
test "cast belongs_to without changes skips" do
changeset = cast(%Author{profile: %Profile{name: "michal", id: 1}},
%{"profile" => %{"id" => 1}}, :profile)
assert changeset.changes == %{}
assert changeset.errors == []
changeset = cast(%Author{profile: %Profile{name: "michal", id: 1}},
%{"profile" => %{"id" => "1"}}, :profile)
assert changeset.changes == %{}
assert changeset.errors == []
end
test "cast belongs_to when required" do
changeset = cast(%Author{}, %{}, :profile, required: true)
assert changeset.required == [:profile]
assert changeset.changes == %{}
assert changeset.errors == [profile: {"can't be blank", [validation: :required]}]
changeset = cast(%Author{}, %{}, :profile, required: true, required_message: "a custom message")
assert changeset.required == [:profile]
assert changeset.changes == %{}
assert changeset.errors == [profile: {"a custom message", [validation: :required]}]
changeset = cast(%Author{profile: nil}, %{}, :profile, required: true)
assert changeset.required == [:profile]
assert changeset.changes == %{}
assert changeset.errors == [profile: {"can't be blank", [validation: :required]}]
changeset = cast(%Author{profile: %Profile{}}, %{}, :profile, required: true)
assert changeset.required == [:profile]
assert changeset.changes == %{}
assert changeset.errors == []
changeset = cast(%Author{profile: nil}, %{"profile" => nil}, :profile, required: true)
assert changeset.required == [:profile]
assert changeset.changes == %{}
assert changeset.errors == [profile: {"can't be blank", [validation: :required]}]
changeset = cast(%Author{profile: %Profile{}}, %{"profile" => nil}, :profile, required: true)
assert changeset.required == [:profile]
assert changeset.changes == %{profile: nil}
assert changeset.errors == [profile: {"can't be blank", [validation: :required]}]
end
test "cast belongs_to with optional" do
changeset = cast(%Author{profile: %Profile{id: "id"}}, %{"profile" => nil}, :profile)
assert changeset.changes.profile == nil
assert changeset.valid?
end
test "cast belongs_to with custom changeset" do
changeset = cast(%Author{}, %{"profile" => %{}}, :profile, with: &Profile.optional_changeset/2)
assert (changeset.types.profile |> elem(1)).on_cast == &Profile.optional_changeset/2
profile = changeset.changes.profile
assert profile.data.__meta__.source == "authors_profiles"
assert profile.changes == %{}
assert profile.errors == []
assert profile.action == :insert
assert profile.valid?
assert changeset.valid?
end
test "cast belongs_to keeps appropriate action from changeset" do
changeset = cast(%Author{profile: %Profile{id: "id"}},
%{"profile" => %{"name" => "michal", "id" => "id"}},
:profile, with: &Profile.set_action/2)
assert changeset.changes.profile.action == :update
assert_raise RuntimeError, ~r"cannot update related", fn ->
cast(%Author{profile: %Profile{id: "old"}},
%{"profile" => %{"name" => "michal", "id" => "new"}},
:profile, with: &Profile.set_action/2)
end
end
test "cast belongs_to with empty parameters" do
changeset = cast(%Author{profile: nil}, %{}, :profile)
assert changeset.changes == %{}
changeset = cast(%Author{}, %{}, :profile, required: true)
assert changeset.changes == %{}
changeset = cast(%Author{profile: %Profile{}}, %{}, :profile, required: true)
assert changeset.changes == %{}
end
test "cast belongs_to with on_replace: :raise" do
schema = %Author{raise_profile: %Profile{id: 1}}
params = %{"raise_profile" => %{"name" => "jose", "id" => "1"}}
changeset = cast(schema, params, :raise_profile)
assert changeset.changes.raise_profile.action == :update
params = %{"raise_profile" => nil}
assert_raise RuntimeError, ~r"you are attempting to change relation", fn ->
cast(schema, params, :raise_profile)
end
params = %{"raise_profile" => %{"name" => "new", "id" => 2}}
assert_raise RuntimeError, ~r"you are attempting to change relation", fn ->
cast(schema, params, :raise_profile)
end
end
test "cast belongs_to with on_replace: :mark_as_invalid" do
schema = %Author{invalid_profile: %Profile{id: 1}}
changeset = cast(schema, %{"invalid_profile" => nil}, :invalid_profile)
assert changeset.changes == %{}
assert changeset.errors == [invalid_profile: {"is invalid", [validation: :assoc, type: :map]}]
refute changeset.valid?
changeset = cast(schema, %{"invalid_profile" => %{"id" => 2}}, :invalid_profile)
assert changeset.changes == %{}
assert changeset.errors == [invalid_profile: {"is invalid", [validation: :assoc, type: :map]}]
refute changeset.valid?
changeset = cast(schema, %{"invalid_profile" => nil}, :invalid_profile, invalid_message: "a custom message")
assert changeset.changes == %{}
assert changeset.errors == [invalid_profile: {"a custom message", [validation: :assoc, type: :map]}]
refute changeset.valid?
end
test "cast belongs_to with keyword defaults" do
{:ok, schema} = TestRepo.insert(%Author{title: "Title", profile: nil})
changeset = cast(schema, %{"profile" => %{id: 1}}, :profile)
assert changeset.changes.profile.data.name == "default"
assert changeset.changes.profile.changes == %{id: 1}
end
test "cast belongs_to with MFA defaults" do
{:ok, schema} = TestRepo.insert(%Author{title: "Title", update_profile: nil})
changeset = cast(schema, %{"update_profile" => %{name: "Jose"}}, :update_profile)
assert_received {:defaults, %Profile{id: nil}, %Author{title: "Title"}, :extra}
assert changeset.changes.update_profile.data.id == 13
assert changeset.changes.update_profile.changes == %{name: "Jose"}
end
test "cast belongs_to with on_replace: :update" do
{:ok, schema} = TestRepo.insert(%Author{title: "Title",
update_profile: %Profile{id: 1, name: "Enio"}})
changeset = cast(schema, %{"update_profile" => %{id: 2, name: "Jose"}}, :update_profile)
assert changeset.changes.update_profile.changes == %{name: "Jose", id: 2}
assert changeset.changes.update_profile.action == :update
assert changeset.errors == []
assert changeset.valid?
end
test "cast belongs_to twice" do
schema = %Author{}
params = %{profile: %{name: "Bruce Wayne", id: 1}}
schema = cast(schema, params, :profile) |> Changeset.apply_changes
params = %{profile: %{name: "Batman", id: 1}}
changeset = cast(schema, params, :profile)
changeset = cast(changeset, params, :profile)
assert changeset.valid?
schema = %Author{}
params = %{profile: %{name: "Bruce Wayne"}}
changeset = cast(schema, params, :profile)
changeset = cast(changeset, params, :profile)
assert changeset.valid?
end
## Change
test "change belongs_to" do
assoc = Author.__schema__(:association, :profile)
assert {:ok, nil, true} = Relation.change(assoc, nil, nil)
assert {:ok, nil, true} = Relation.change(assoc, nil, %Profile{})
assoc_schema = %Profile{}
assoc_schema_changeset = Changeset.change(assoc_schema, name: "michal")
assert {:ok, changeset, true} =
Relation.change(assoc, assoc_schema_changeset, nil)
assert changeset.action == :insert
assert changeset.changes == %{name: "michal"}
assert {:ok, changeset, true} =
Relation.change(assoc, assoc_schema_changeset, assoc_schema)
assert changeset.action == :update
assert changeset.changes == %{name: "michal"}
assert :ignore = Relation.change(assoc, %{assoc_schema_changeset | action: :ignore}, nil)
empty_changeset = Changeset.change(assoc_schema)
assert :ignore = Relation.change(assoc, empty_changeset, assoc_schema)
assoc_with_id = %Profile{id: 2}
assert {:ok, _, true} =
Relation.change(assoc, %Profile{id: 1}, assoc_with_id)
end
test "change belongs_to with attributes" do
assoc = Author.__schema__(:association, :profile)
assert {:ok, changeset, true} =
Relation.change(assoc, %{name: "michal"}, nil)
assert changeset.action == :insert
assert changeset.changes == %{name: "michal"}
profile = %Profile{name: "other"} |> Ecto.put_meta(state: :loaded)
assert {:ok, changeset, true} =
Relation.change(assoc, %{name: "michal"}, profile)
assert changeset.action == :update
assert changeset.changes == %{name: "michal"}
assert {:ok, changeset, true} =
Relation.change(assoc, [name: "michal"], profile)
assert changeset.action == :update
assert changeset.changes == %{name: "michal"}
profile = %Profile{name: "other"}
assert {:ok, changeset, true} =
Relation.change(assoc, %{name: "michal"}, profile)
assert changeset.action == :insert
assert changeset.changes == %{name: "michal"}
assert {:ok, changeset, true} =
Relation.change(assoc, [name: "michal"], profile)
assert changeset.action == :insert
assert changeset.changes == %{name: "michal"}
# Empty attributes
assert {:ok, changeset, true} =
Relation.change(assoc, %{}, profile)
assert changeset.action == :insert
assert changeset.changes == %{}
assert {:ok, changeset, true} =
Relation.change(assoc, [], profile)
assert changeset.action == :insert
assert changeset.changes == %{}
end
test "change belongs_to with struct" do
assoc = Author.__schema__(:association, :profile)
profile = %Profile{name: "michal"}
assert {:ok, changeset, true} =
Relation.change(assoc, profile, nil)
assert changeset.action == :insert
assert {:ok, changeset, true} =
Relation.change(assoc, Ecto.put_meta(profile, state: :loaded), nil)
assert changeset.action == :update
assert {:ok, changeset, true} =
Relation.change(assoc, Ecto.put_meta(profile, state: :deleted), nil)
assert changeset.action == :delete
end
test "change belongs_to keeps appropriate action from changeset" do
assoc = Author.__schema__(:association, :profile)
assoc_schema = %Profile{id: 1}
# Adding
changeset = %{Changeset.change(assoc_schema, name: "michal") | action: :insert}
{:ok, changeset, _} = Relation.change(assoc, changeset, nil)
assert changeset.action == :insert
changeset = %{changeset | action: :update}
{:ok, changeset, _} = Relation.change(assoc, changeset, nil)
assert changeset.action == :update
changeset = %{changeset | action: :delete}
{:ok, changeset, _} = Relation.change(assoc, changeset, nil)
assert changeset.action == :delete
# Replacing
changeset = %{Changeset.change(assoc_schema, name: "michal") | action: :insert}
assert_raise RuntimeError, ~r/cannot insert related/, fn ->
Relation.change(assoc, changeset, assoc_schema)
end
changeset = %{changeset | action: :update}
{:ok, changeset, _} = Relation.change(assoc, changeset, assoc_schema)
assert changeset.action == :update
changeset = %{changeset | action: :delete}
{:ok, changeset, _} = Relation.change(assoc, changeset, assoc_schema)
assert changeset.action == :delete
end
test "change belongs_to with on_replace: :raise" do
assoc_schema = %Profile{id: 1}
base_changeset = Changeset.change(%Author{raise_profile: assoc_schema})
assert_raise RuntimeError, ~r"you are attempting to change relation", fn ->
Changeset.put_assoc(base_changeset, :raise_profile, nil)
end
assert_raise RuntimeError, ~r"you are attempting to change relation", fn ->
Changeset.put_assoc(base_changeset, :raise_profile, %Profile{id: 2})
end
end
test "change belongs_to with on_replace: :mark_as_invalid" do
assoc_schema = %Profile{id: 1}
base_changeset = Changeset.change(%Author{invalid_profile: assoc_schema})
changeset = Changeset.put_assoc(base_changeset, :invalid_profile, nil)
assert changeset.changes == %{}
assert changeset.errors == [invalid_profile: {"is invalid", [type: :map]}]
refute changeset.valid?
end
## Other
test "put_assoc/4" do
base_changeset = Changeset.change(%Author{})
changeset = Changeset.put_assoc(base_changeset, :profile, %{name: "michal"})
assert %Ecto.Changeset{} = changeset.changes.profile
assert changeset.changes.profile.data.__meta__.source == "authors_profiles"
changeset = Changeset.put_assoc(base_changeset, :profile, %Profile{name: "michal"})
assert %Ecto.Changeset{} = changeset.changes.profile
assert changeset.changes.profile.data.__meta__.source == "profiles"
base_changeset = Changeset.change(%Author{profile: %Profile{name: "michal"}})
empty_update_changeset = Changeset.change(%Profile{name: "michal"})
changeset = Changeset.put_assoc(base_changeset, :profile, empty_update_changeset)
refute Map.has_key?(changeset.changes, :profile)
end
test "put_assoc/4 with empty" do
# On unloaded
changeset =
%Author{}
|> Changeset.change()
|> Changeset.put_assoc(:profile, nil)
assert Map.has_key?(changeset.changes, :profile)
# On empty
changeset =
%Author{profile: nil}
|> Changeset.change()
|> Changeset.put_assoc(:profile, nil)
refute Map.has_key?(changeset.changes, :profile)
# On unloaded with change
changeset =
%Author{}
|> Changeset.change(profile: %Profile{})
|> Changeset.put_assoc(:profile, nil)
assert Map.has_key?(changeset.changes, :profile)
# On empty with change
changeset =
%Author{profile: nil}
|> Changeset.change(profile: %Profile{})
|> Changeset.put_assoc(:profile, nil)
refute Map.has_key?(changeset.changes, :profile)
end
test "put_change/3" do
changeset = Changeset.change(%Author{}, profile: %Profile{name: "michal"})
assert %Ecto.Changeset{} = changeset.changes.profile
base_changeset = Changeset.change(%Author{profile: %Profile{name: "michal"}})
empty_update_changeset = Changeset.change(%Profile{name: "michal"})
changeset = Changeset.put_change(base_changeset, :profile, empty_update_changeset)
refute Map.has_key?(changeset.changes, :profile)
end
test "get_field/3, fetch_field/2 with assocs" do
profile_changeset = Changeset.change(%Profile{}, name: "michal")
profile = Changeset.apply_changes(profile_changeset)
changeset =
%Author{}
|> Changeset.change
|> Changeset.put_assoc(:profile, profile_changeset)
assert Changeset.get_field(changeset, :profile) == profile
assert Changeset.fetch_field(changeset, :profile) == {:changes, profile}
changeset = Changeset.change(%Author{profile: profile})
assert Changeset.get_field(changeset, :profile) == profile
assert Changeset.fetch_field(changeset, :profile) == {:data, profile}
end
test "on_replace: :nilify" do
# one case is handled inside repo
profile = %Profile{id: 1}
changeset = cast(%Author{profile: profile}, %{"profile" => nil}, :profile)
assert changeset.changes.profile == nil
end
test "apply_changes" do
embed = Author.__schema__(:association, :profile)
changeset = Changeset.change(%Profile{}, name: "michal")
assert Relation.apply_changes(embed, changeset) == %Profile{name: "michal"}
changeset = Changeset.change(%Profile{}, name: "hello")
changeset2 = %{changeset | action: :delete}
assert Relation.apply_changes(embed, changeset2) == nil
end
end
| 36.764286 | 115 | 0.656402 |
73670ec831389a2bf83a8a5d678ddc13e66b47b9 | 1,583 | exs | Elixir | mix.exs | allen-garvey/mundum | 15719f6bca998a04f783206f4db2214ebd439e61 | [
"MIT"
] | null | null | null | mix.exs | allen-garvey/mundum | 15719f6bca998a04f783206f4db2214ebd439e61 | [
"MIT"
] | null | null | null | mix.exs | allen-garvey/mundum | 15719f6bca998a04f783206f4db2214ebd439e61 | [
"MIT"
] | null | null | null | defmodule Mundum.Mixfile do
use Mix.Project
def project do
[
app: :mundum,
version: "0.0.1",
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env),
compilers: [:phoenix, :gettext] ++ Mix.compilers,
start_permanent: Mix.env == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Mundum.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix, "~> 1.3.0"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.2"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.10"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]
]
end
end
| 25.95082 | 79 | 0.58307 |
736734ae138da8a84a83dfa598852c27edf2fa09 | 1,846 | ex | Elixir | clients/cloud_build/lib/google_api/cloud_build/v1/model/push_filter.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/cloud_build/lib/google_api/cloud_build/v1/model/push_filter.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/cloud_build/lib/google_api/cloud_build/v1/model/push_filter.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 "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 elixir code generator program.
# Do not edit the class manually.
defmodule GoogleApi.CloudBuild.V1.Model.PushFilter do
@moduledoc """
Push contains filter properties for matching GitHub git pushes.
## Attributes
* `branch` (*type:* `String.t`, *default:* `nil`) - Regexes of branches to match.
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax
* `tag` (*type:* `String.t`, *default:* `nil`) - Regexes of tags to match.
The syntax of the regular expressions accepted is the syntax accepted by
RE2 and described at https://github.com/google/re2/wiki/Syntax
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:branch => String.t(),
:tag => String.t()
}
field(:branch)
field(:tag)
end
defimpl Poison.Decoder, for: GoogleApi.CloudBuild.V1.Model.PushFilter do
def decode(value, options) do
GoogleApi.CloudBuild.V1.Model.PushFilter.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudBuild.V1.Model.PushFilter do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.964286 | 85 | 0.72156 |
736756e5c5f9740943923bae157d65019b5409a6 | 1,483 | ex | Elixir | lib/sanbase_web/graphql/schema/types/clickhouse_types.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | null | null | null | lib/sanbase_web/graphql/schema/types/clickhouse_types.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | 1 | 2021-07-24T16:26:03.000Z | 2021-07-24T16:26:03.000Z | lib/sanbase_web/graphql/schema/types/clickhouse_types.ex | sitedata/sanbase2 | 8da5e44a343288fbc41b68668c6c80ae8547d557 | [
"MIT"
] | null | null | null | defmodule SanbaseWeb.Graphql.ClickhouseTypes do
use Absinthe.Schema.Notation
object :active_addresses do
field(:datetime, non_null(:datetime))
field(:active_addresses, non_null(:float))
end
object :active_deposits do
field(:datetime, non_null(:datetime))
field(:active_deposits, non_null(:float))
end
object :gas_used do
field(:datetime, non_null(:datetime))
field(:eth_gas_used, :float, deprecate: "Use gasUsed")
field(:gas_used, :float)
end
object :mining_pools_distribution do
field(:datetime, non_null(:datetime))
field(:top3, :float)
field(:top10, :float)
field(:other, :float)
end
object :mvrv_ratio do
field(:datetime, non_null(:datetime))
field(:ratio, :float)
end
object :network_growth do
field(:datetime, non_null(:datetime))
field(:new_addresses, :float)
end
object :nvt_ratio do
field(:datetime, non_null(:datetime))
field(:nvt_ratio_circulation, :float)
field(:nvt_ratio_tx_volume, :float)
end
object :realized_value do
field(:datetime, non_null(:datetime))
field(:realized_value, :float)
end
object :percent_of_token_supply_on_exchanges do
field(:datetime, non_null(:datetime))
field(:percent_on_exchanges, :float)
end
object :top_holders_percent_of_total_supply do
field(:datetime, non_null(:datetime))
field(:in_exchanges, :float)
field(:outside_exchanges, :float)
field(:in_top_holders_total, :float)
end
end
| 24.716667 | 58 | 0.710722 |
736771625d0b357385f7856b26e14d7f0b5c01a2 | 1,879 | exs | Elixir | config/dev.exs | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 4 | 2020-08-05T20:05:34.000Z | 2020-10-01T10:01:56.000Z | config/dev.exs | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 1 | 2020-07-08T05:02:12.000Z | 2020-09-25T10:05:11.000Z | config/dev.exs | ATechnoHazard/katbin | 20a0b45954cf7819cd9d51c401db06be0f47666b | [
"MIT"
] | 1 | 2020-08-30T12:59:49.000Z | 2020-08-30T12:59:49.000Z | import 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 :ketbin, KetbinWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"build.js",
cd: Path.expand("../assets", __DIR__)
]
]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :ketbin, KetbinWeb.Endpoint,
live_reload: [
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/ketbin_web/(live|views)/.*(ex)$",
~r"lib/ketbin_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
# Import the secrets config
import_config "dev.secret.exs"
| 27.632353 | 68 | 0.691857 |
736774f5a2968e24470f7c5ff095db4a25d86ba5 | 229 | exs | Elixir | test/plds_web/controllers/health_controller_test.exs | phoenixframework/plds | 820600e8da6e13f376f8341cb78868bc189ddad8 | [
"MIT"
] | 60 | 2021-09-13T21:53:34.000Z | 2022-03-09T14:31:36.000Z | test/plds_web/controllers/health_controller_test.exs | phoenixframework/plds | 820600e8da6e13f376f8341cb78868bc189ddad8 | [
"MIT"
] | 2 | 2021-09-23T17:13:40.000Z | 2021-11-16T15:57:05.000Z | test/plds_web/controllers/health_controller_test.exs | phoenixframework/plds | 820600e8da6e13f376f8341cb78868bc189ddad8 | [
"MIT"
] | 2 | 2021-11-16T10:37:42.000Z | 2022-02-18T19:32:38.000Z | defmodule PLDSWeb.HealthControllerTest do
use PLDSWeb.ConnCase
test "GET /health", %{conn: conn} do
conn = get(conn, "/health")
assert %{"application" => "plds", "version" => _} = json_response(conn, 200)
end
end
| 22.9 | 80 | 0.659389 |
736794de895336f9c058b1c72e2eca7a2fc0ed10 | 2,221 | exs | Elixir | mix.exs | krainboltgreene/torch | 664b14d1eb2ca3b8a3da1709847d8b9869097e23 | [
"MIT"
] | null | null | null | mix.exs | krainboltgreene/torch | 664b14d1eb2ca3b8a3da1709847d8b9869097e23 | [
"MIT"
] | null | null | null | mix.exs | krainboltgreene/torch | 664b14d1eb2ca3b8a3da1709847d8b9869097e23 | [
"MIT"
] | null | null | null | defmodule Torch.MixProject do
use Mix.Project
@source_url "https://github.com/mojotech/torch"
@version "3.7.1"
def project do
[
app: :torch,
version: @version,
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
compilers: [:phoenix, :gettext] ++ Mix.compilers(),
name: "Torch",
description: "Rapid admin generator for Phoenix",
source_url: @source_url,
homepage_url: @source_url,
test_paths: ["test/mix", "test/torch"],
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
],
elixirc_paths: elixirc_paths(Mix.env()),
package: package(),
docs: docs(),
deps: deps()
]
end
defp elixirc_paths(:test), do: ["lib", "test/support/cases"]
defp elixirc_paths(_env), do: ["lib"]
# 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
[
{:phoenix, ">= 1.3.0 and < 1.7.0"},
{:phoenix_html, "~> 3.0"},
{:gettext, "~> 0.16"},
{:scrivener_ecto, ">= 1.2.1"},
{:filtrex, "~> 0.4.1"},
{:jason, ">= 0.0.0", only: [:dev, :test]},
{:excoveralls, ">= 0.0.0", only: [:dev, :test]},
{:credo, "~> 1.1", only: [:dev, :test]},
{:ex_doc, ">= 0.0.0", only: [:dev, :test], runtime: false},
{:ex_unit_notifier, "~> 1.0", only: [:test]},
{:mix_test_watch, "~> 1.0", only: [:dev], runtime: false}
]
end
defp package do
[
maintainers: ["MojoTech"],
licenses: ["MIT"],
files: ~w(lib priv mix.exs README.md LICENSE CHANGELOG.md CODE_OF_CONDUCT.md),
links: %{
"Github" => @source_url
}
]
end
defp docs do
[
extras: [
"CHANGELOG.md": [title: "Changelog"],
"CODE_OF_CONDUCT.md": [title: "Code of Conduct"],
LICENSE: [title: "License"],
"README.md": [title: "Overview"]
],
main: "readme",
source_ref: "v#{@version}",
formatters: ["html"]
]
end
end
| 26.129412 | 84 | 0.541198 |
73680ca695afecb4b19f8af6647fb46ab3446d74 | 621 | ex | Elixir | lib/oli/delivery/sections/enrollment.ex | DevShashi1993/oli-torus | e6e0b66f0973f9790a5785731b22db6fb1c50a73 | [
"MIT"
] | 45 | 2020-04-17T15:40:27.000Z | 2022-03-25T00:13:30.000Z | lib/oli/delivery/sections/enrollment.ex | DevShashi1993/oli-torus | e6e0b66f0973f9790a5785731b22db6fb1c50a73 | [
"MIT"
] | 944 | 2020-02-13T02:37:01.000Z | 2022-03-31T17:50:07.000Z | lib/oli/delivery/sections/enrollment.ex | DevShashi1993/oli-torus | e6e0b66f0973f9790a5785731b22db6fb1c50a73 | [
"MIT"
] | 23 | 2020-07-28T03:36:13.000Z | 2022-03-17T14:29:02.000Z | defmodule Oli.Delivery.Sections.Enrollment do
use Ecto.Schema
import Ecto.Changeset
schema "enrollments" do
belongs_to :user, Oli.Accounts.User
belongs_to :section, Oli.Delivery.Sections.Section
field :state, :map, default: %{}
many_to_many :context_roles, Lti_1p3.DataProviders.EctoProvider.ContextRole,
join_through: "enrollments_context_roles",
on_replace: :delete
timestamps(type: :utc_datetime)
end
@doc false
def changeset(section, attrs) do
section
|> cast(attrs, [:user_id, :section_id, :state])
|> validate_required([:user_id, :section_id])
end
end
| 24.84 | 80 | 0.716586 |
73680fa98d750383af836b5cc944b20883379083 | 1,000 | exs | Elixir | test/dynamic_test.exs | sasani5942/exactor | 453b4505d2d6fabd523e3ce70f5b00d4ca71c7c5 | [
"MIT"
] | 616 | 2015-01-09T03:11:36.000Z | 2022-03-16T06:07:55.000Z | test/dynamic_test.exs | sasani5942/exactor | 453b4505d2d6fabd523e3ce70f5b00d4ca71c7c5 | [
"MIT"
] | 23 | 2015-03-22T19:26:58.000Z | 2021-01-04T10:42:40.000Z | test/dynamic_test.exs | sasani5942/exactor | 453b4505d2d6fabd523e3ce70f5b00d4ca71c7c5 | [
"MIT"
] | 27 | 2015-03-23T17:41:41.000Z | 2020-10-31T13:20:22.000Z | defmodule DynamicTest do
use ExUnit.Case
defmodule DynServer do
use ExActor.Tolerant
defstart start
for op <- [:get] do
defcall unquote(op), state: state do
reply(state)
end
end
for op <- [:set] do
defcast unquote(op)(arg) do
new_state(arg)
end
end
end
test "dynamic" do
{:ok, pid} = DynServer.start
DynServer.set(pid, 1)
assert DynServer.get(pid) == 1
end
defmodule MapServer do
use ExActor.Tolerant
import ExActor.Delegator
defstart start, do: initial_state(Map.new)
delegate_to Map do
query get/2
query size/1
trans put/3
end
defcall normal_call, do: reply(2)
end
test "wrapper" do
{:ok, pid} = MapServer.start
assert MapServer.get(pid, :a) == nil
assert MapServer.size(pid) == 0
MapServer.put(pid, :a, 1)
assert MapServer.get(pid, :a) == 1
assert MapServer.size(pid) == 1
assert MapServer.normal_call(pid) == 2
end
end
| 17.857143 | 46 | 0.614 |
73682650e9f378a673822d351ada2d00de6eefc4 | 365 | exs | Elixir | apps/api_web/test/api_web/plugs/redirect_test.exs | fjlanasa/api | c39bc393aea572bfb81754b2ea1adf9dda9ce24a | [
"MIT"
] | 62 | 2019-01-17T12:34:39.000Z | 2022-03-20T21:49:47.000Z | apps/api_web/test/api_web/plugs/redirect_test.exs | fjlanasa/api | c39bc393aea572bfb81754b2ea1adf9dda9ce24a | [
"MIT"
] | 375 | 2019-02-13T15:30:50.000Z | 2022-03-30T18:50:41.000Z | apps/api_web/test/api_web/plugs/redirect_test.exs | fjlanasa/api | c39bc393aea572bfb81754b2ea1adf9dda9ce24a | [
"MIT"
] | 14 | 2019-01-16T19:35:57.000Z | 2022-02-26T18:55:54.000Z | defmodule ApiWeb.Plugs.RedirectTest do
use ApiWeb.ConnCase
alias ApiWeb.Plugs.Redirect
test "init/1" do
assert Redirect.init([]) == []
end
test "call/2", %{conn: conn} do
conn =
conn
|> bypass_through()
|> get("/")
|> Redirect.call(to: "/test")
assert redirected_to(conn) == "/test"
assert conn.halted
end
end
| 18.25 | 41 | 0.59726 |
7368359fac1e1551523a5e9a0f8e7730604d90ea | 2,556 | ex | Elixir | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/account_permission.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/account_permission.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dfa_reporting/lib/google_api/dfa_reporting/v34/model/account_permission.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.DFAReporting.V34.Model.AccountPermission do
@moduledoc """
AccountPermissions contains information about a particular account permission. Some features of Campaign Manager require an account permission to be present in the account.
## Attributes
* `accountProfiles` (*type:* `list(String.t)`, *default:* `nil`) - Account profiles associated with this account permission. Possible values are: - "ACCOUNT_PROFILE_BASIC" - "ACCOUNT_PROFILE_STANDARD"
* `id` (*type:* `String.t`, *default:* `nil`) - ID of this account permission.
* `kind` (*type:* `String.t`, *default:* `nil`) - Identifies what kind of resource this is. Value: the fixed string "dfareporting#accountPermission".
* `level` (*type:* `String.t`, *default:* `nil`) - Administrative level required to enable this account permission.
* `name` (*type:* `String.t`, *default:* `nil`) - Name of this account permission.
* `permissionGroupId` (*type:* `String.t`, *default:* `nil`) - Permission group of this account permission.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:accountProfiles => list(String.t()) | nil,
:id => String.t() | nil,
:kind => String.t() | nil,
:level => String.t() | nil,
:name => String.t() | nil,
:permissionGroupId => String.t() | nil
}
field(:accountProfiles, type: :list)
field(:id)
field(:kind)
field(:level)
field(:name)
field(:permissionGroupId)
end
defimpl Poison.Decoder, for: GoogleApi.DFAReporting.V34.Model.AccountPermission do
def decode(value, options) do
GoogleApi.DFAReporting.V34.Model.AccountPermission.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DFAReporting.V34.Model.AccountPermission do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 41.225806 | 205 | 0.705399 |
73685ad4eac34ef7f71eb7ebef5a9a319157c366 | 646 | ex | Elixir | test/support/slack_test_helpers.ex | zvkemp/elixir-bot-server | 0db6b6ce57ddccaac980bf659eb2d540a077de38 | [
"MIT"
] | 8 | 2016-03-15T17:15:26.000Z | 2021-12-11T11:21:53.000Z | test/support/slack_test_helpers.ex | zvkemp/elixir-bot-server | 0db6b6ce57ddccaac980bf659eb2d540a077de38 | [
"MIT"
] | 1 | 2017-10-15T20:13:15.000Z | 2017-10-15T20:13:15.000Z | test/support/slack_test_helpers.ex | zvkemp/elixir-bot-server | 0db6b6ce57ddccaac980bf659eb2d540a077de38 | [
"MIT"
] | null | null | null | defmodule Slack.TestHelpers do
def new_bot_name do
fn -> :crypto.strong_rand_bytes(16) end
|> Stream.repeatedly
|> Enum.take(2)
|> List.to_tuple
end
@doc """
proxies a subscription; forwards decoded JSON back to exunit for better
pattern matching on messages
"""
def subscribe_to_json(workspace, channel) do
me = self()
user_key = Base.encode64(:crypto.strong_rand_bytes(5))
{:ok, pid} = Slack.TestMessageForwarder.start_as(
{workspace, user_key},
:json,
fn {:push, json} -> Jason.decode!(json) end
)
Slack.Console.PubSub.subscribe(workspace, channel, pid, user_key)
end
end
| 26.916667 | 73 | 0.676471 |
73686cfc3501b82e936a0615bbe7cfd5a67347e0 | 22,823 | exs | Elixir | test/jumubase_web/controllers/internal/performance_controller_test.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 2 | 2019-01-20T07:03:30.000Z | 2019-04-11T10:20:14.000Z | test/jumubase_web/controllers/internal/performance_controller_test.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | 6 | 2018-09-20T05:52:14.000Z | 2019-04-23T19:27:39.000Z | test/jumubase_web/controllers/internal/performance_controller_test.exs | richeterre/jumubase-phoenix | 7584f890af117d496971b5284bf9de798e22266f | [
"MIT"
] | null | null | null | defmodule JumubaseWeb.Internal.PerformanceControllerTest do
use JumubaseWeb.ConnCase
setup config do
config
|> Map.put(:contest, insert(:contest))
|> login_if_needed
end
describe "index/2" do
for role <- all_roles() do
@tag login_as: role
test "lists contest performances to authorized #{role} users", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn = get(conn, Routes.internal_contest_performance_path(conn, :index, c))
assert html_response(conn, 200) =~ "Performances"
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to list contest performances",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn = get(conn, Routes.internal_contest_performance_path(conn, :index, c))
assert_unauthorized_user(conn)
end
end
test "redirects guests trying to list contest performances", %{conn: conn, contest: c} do
conn = get(conn, Routes.internal_contest_performance_path(conn, :index, c))
assert_unauthorized_guest(conn)
end
end
describe "show/2" do
for role <- all_roles() do
@tag login_as: role
test "shows a single performance to authorized #{role} users", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :show, c, p))
assert html_response(conn, 200) =~ p.edit_code
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to view a performance",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :show, c, p))
assert_unauthorized_user(conn)
end
end
test "redirects guests trying to view a performance", %{conn: conn, contest: c} do
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :show, c, p))
assert_unauthorized_guest(conn)
end
end
describe "new/2" do
for role <- roles_except("observer") do
@tag login_as: role
test "lets authorized #{role} users fill in a new performance", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn = conn |> attempt_new(c)
assert html_response(conn, 200) =~ "New Performance"
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to fill in a new performance",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_new(c) |> assert_unauthorized_user
end
end
@tag login_as: "observer"
test "redirects observers trying to fill in a new performance", %{conn: conn, contest: c} do
conn |> attempt_new(c) |> assert_unauthorized_user
end
test "redirects guests trying to fill in a new performance", %{conn: conn, contest: c} do
conn |> attempt_new(c) |> assert_unauthorized_guest
end
end
describe "edit/2" do
for role <- roles_except("observer") do
@tag login_as: role
test "lets authorized #{role} users edit a performance", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :edit, c, p))
assert html_response(conn, 200) =~ "Edit performance"
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} organizers trying to edit a performance",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :edit, c, p))
assert_unauthorized_user(conn)
end
end
@tag login_as: "observer"
test "redirects observers trying to edit a performance", %{conn: conn, contest: c} do
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :edit, c, p))
assert_unauthorized_user(conn)
end
test "redirects guests trying to edit a performance", %{conn: conn, contest: c} do
p = insert_performance(c)
conn = get(conn, Routes.internal_contest_performance_path(conn, :edit, c, p))
assert_unauthorized_guest(conn)
end
for role <- roles_except("observer") do
@tag login_as: role
test "redirects authorized #{role} users if the performance has results",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
p = insert_performance(c, appearances: [build(:appearance, points: 1)])
conn
|> get(Routes.internal_contest_performance_path(conn, :edit, c, p))
|> assert_flash_redirect(
Routes.internal_contest_performance_path(conn, :index, c),
"This performance already has results. To edit it, please clear them first."
)
end
end
end
describe "delete/2" do
for role <- roles_except("observer") do
@tag login_as: role
test "lets authorized #{role} users delete a performance", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_delete(c) |> assert_deletion_success(c)
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to delete a performance",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_delete(c) |> assert_unauthorized_user
end
end
@tag login_as: "observer"
test "redirects observers trying to delete a performance", %{conn: conn, contest: c} do
conn |> attempt_delete(c) |> assert_unauthorized_user
end
test "redirects guests trying to delete a performance", %{conn: conn, contest: c} do
conn |> attempt_delete(c) |> assert_unauthorized_guest
end
end
describe "reschedule/2" do
for role <- roles_except("observer") do
@tag login_as: role
test "lets authorized #{role} users reschedule performances", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
test_reschedule_success(conn, c)
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to reschedule performances",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_reschedule(c) |> assert_unauthorized_user
end
end
@tag login_as: "observer"
test "redirects observers trying to reschedule performances", %{conn: conn, contest: c} do
conn |> attempt_reschedule(c) |> assert_unauthorized_user
end
test "redirects guests trying to reschedule performances", %{conn: conn, contest: c} do
conn |> attempt_reschedule(c) |> assert_unauthorized_guest
end
@tag login_as: "admin"
test "returns an error for invalid reschedule params", %{conn: conn, contest: c} do
p = insert_performance(c)
params = %{
"performances" => %{p.id => %{"stageId" => nil, "stageTime" => "2019-01-01T07:00:00"}}
}
conn = patch(conn, Routes.internal_contest_performance_path(conn, :reschedule, c), params)
assert json_response(conn, 422) == %{
"error" => %{
"performanceId" => to_string(p.id),
"errors" => %{
"base" => [
"The performance can either have both stage and stage time, or neither."
]
}
}
}
end
end
describe "jury_material/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users list a contest's performances to create jury material",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_jury_material(c) |> assert_jury_material_success
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to list a contest's performances to create jury material",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_jury_material(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to list a contest's performances to create jury material",
%{conn: conn, contest: c} do
conn |> attempt_jury_material(c) |> assert_unauthorized_guest
end
end
describe "print_jury_sheets/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users print jury sheets",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_print_jury_sheets(c) |> assert_pdf_response
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to print jury sheets",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_print_jury_sheets(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to print jury sheets", %{
conn: conn,
contest: c
} do
conn |> attempt_print_jury_sheets(c) |> assert_unauthorized_guest
end
end
describe "print_jury_table/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users print a jury table",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_print_jury_table(c) |> assert_pdf_response
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to print a jury table",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_print_jury_table(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to print a jury table", %{
conn: conn,
contest: c
} do
conn |> attempt_print_jury_table(c) |> assert_unauthorized_guest
end
end
describe "edit_results/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users edit results", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_edit_results(c) |> assert_results_success
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to edit results", %{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_edit_results(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to edit results", %{conn: conn, contest: c} do
conn |> attempt_edit_results(c) |> assert_unauthorized_guest
end
end
describe "update_results/2" do
for role <- roles_except("observer") do
@tag login_as: role
test "lets authorized #{role} users update results", %{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_update_results(c) |> assert_update_results_success(c)
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to update results", %{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_update_results(c) |> assert_unauthorized_user
end
end
@tag login_as: "observer"
test "redirects observers trying to update results", %{conn: conn, contest: c} do
conn |> attempt_update_results(c) |> assert_unauthorized_user
end
test "redirects guests trying to update results", %{conn: conn, contest: c} do
conn |> attempt_update_results(c) |> assert_unauthorized_guest
end
@tag login_as: "admin"
test "handles updating results with an empty appearance id array", %{conn: conn, contest: c} do
params = %{"results" => %{"appearance_ids" => "", "points" => "25"}}
patch(conn, Routes.internal_contest_results_path(conn, :update_results, c), params)
end
end
describe "publish_results/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users list a contest's performances for result publishing",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_publish_results(c) |> assert_publish_results_success
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to list a contest's performances for result publishing",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_publish_results(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to list a contest's performances for result publishing",
%{conn: conn, contest: c} do
conn |> attempt_publish_results(c) |> assert_unauthorized_guest
end
end
describe "update_results_public/2" do
for role <- roles_except("observer") do
@tag login_as: role
test "lets authorized #{role} users publish a contest's performance results",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_update_results_public(c) |> assert_update_results_public_success(c)
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to publish a contest's performance results",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_update_results_public(c) |> assert_unauthorized_user
end
end
@tag login_as: "observer"
test "redirects observers trying to publish a contest's performance results",
%{conn: conn, contest: c} do
conn |> attempt_update_results_public(c) |> assert_unauthorized_user
end
test "redirects guests trying to publish a contest's performance results", %{
conn: conn,
contest: c
} do
conn |> attempt_update_results_public(c) |> assert_unauthorized_guest
end
end
describe "certificates/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users list a contest's performances to create certificates",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_certificates(c) |> assert_certificates_success
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to list a contest's performances to create certificates",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_certificates(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to list a contest's performances to create certificates",
%{conn: conn, contest: c} do
conn |> attempt_certificates(c) |> assert_unauthorized_guest
end
end
describe "print_certificates/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users print certificates",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_print_certificates(c) |> assert_pdf_response
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to print certificates",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_print_certificates(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to print certificates", %{conn: conn, contest: c} do
conn |> attempt_print_certificates(c) |> assert_unauthorized_guest
end
end
describe "advancing/2" do
for role <- all_roles() do
@tag login_as: role
test "lets authorized #{role} users list a contest's advancing performances",
%{conn: conn, user: u} do
c = insert_authorized_contest(u)
conn |> attempt_advancing(c) |> assert_advancing_success
end
end
for role <- ["local-organizer", "global-organizer"] do
@tag login_as: role
test "redirects unauthorized #{role} users trying to list a contest's advancing performances",
%{conn: conn, user: u} do
c = insert_unauthorized_contest(u)
conn |> attempt_advancing(c) |> assert_unauthorized_user
end
end
test "redirects guests trying to list a contest's advancing performances",
%{conn: conn, contest: c} do
conn |> attempt_advancing(c) |> assert_unauthorized_guest
end
end
# Private helpers
defp attempt_new(conn, contest) do
get(conn, Routes.internal_contest_performance_path(conn, :new, contest))
end
defp attempt_delete(conn, c) do
p = insert_performance(c)
delete(conn, Routes.internal_contest_performance_path(conn, :delete, c, p))
end
defp attempt_reschedule(conn, contest) do
p = insert_performance(contest, stage: build(:stage), stage_time: Timex.now())
params = %{"performances" => %{p.id => %{"stageId" => nil, "stageTime" => nil}}}
conn |> patch(Routes.internal_contest_performance_path(conn, :reschedule, contest), params)
end
defp attempt_jury_material(conn, contest) do
get(conn, Routes.internal_contest_performances_path(conn, :jury_material, contest))
end
defp attempt_print_jury_sheets(conn, contest) do
p1 = insert_performance(contest)
p2 = insert_performance(contest)
get(
conn,
Routes.internal_contest_performance_path(conn, :print_jury_sheets, contest,
performance_ids: [p1.id, p2.id]
)
)
end
defp attempt_print_jury_table(conn, contest) do
p1 = insert_performance(contest)
p2 = insert_performance(contest)
get(
conn,
Routes.internal_contest_performance_path(conn, :print_jury_table, contest,
performance_ids: [p1.id, p2.id]
)
)
end
defp attempt_edit_results(conn, contest) do
get(conn, Routes.internal_contest_results_path(conn, :edit_results, contest))
end
defp attempt_update_results(conn, contest) do
a1 = insert_appearance(contest)
a2 = insert_appearance(contest)
params = %{"results" => %{"appearance_ids" => "#{a1.id},#{a2.id}", "points" => "25"}}
conn |> patch(Routes.internal_contest_results_path(conn, :update_results, contest), params)
end
defp attempt_publish_results(conn, contest) do
conn |> get(Routes.internal_contest_results_path(conn, :publish_results, contest))
end
defp attempt_update_results_public(conn, contest) do
p1 = insert_performance(contest)
p2 = insert_performance(contest)
params = %{"performance_ids" => [p1.id, p2.id], "public" => true}
conn
|> patch(Routes.internal_contest_results_path(conn, :update_results_public, contest), params)
end
defp attempt_certificates(conn, contest) do
get(conn, Routes.internal_contest_performances_path(conn, :certificates, contest))
end
defp attempt_print_certificates(conn, contest) do
p1 = insert_performance(contest)
p2 = insert_performance(contest)
get(
conn,
Routes.internal_contest_performance_path(conn, :print_certificates, contest,
performance_ids: [p1.id, p2.id]
)
)
end
defp attempt_advancing(conn, contest) do
get(conn, Routes.internal_contest_performances_path(conn, :advancing, contest))
end
defp assert_deletion_success(conn, contest) do
assert_flash_redirect(
conn,
Routes.internal_contest_performance_path(conn, :index, contest),
"The performance was deleted."
)
end
defp assert_jury_material_success(conn) do
assert html_response(conn, 200) =~ "Create jury material"
end
defp assert_pdf_response(conn) do
assert response_content_type(conn, :pdf) =~ "charset=utf-8"
end
defp assert_results_success(conn) do
assert html_response(conn, 200) =~ "Enter points"
end
defp assert_update_results_success(conn, contest) do
assert redirected_to(conn) ==
Routes.internal_contest_results_path(conn, :edit_results, contest)
end
defp assert_publish_results_success(conn) do
assert html_response(conn, 200) =~ "Publish results"
end
defp assert_update_results_public_success(conn, contest) do
assert_flash_redirect(
conn,
Routes.internal_contest_results_path(conn, :publish_results, contest),
"The results of these 2 performances were published."
)
end
defp assert_certificates_success(conn) do
assert html_response(conn, 200) =~ "Create certificates"
end
defp assert_advancing_success(conn) do
assert html_response(conn, 200) =~ "Advancing performances"
end
defp test_reschedule_success(conn, contest) do
[s1, s2] = insert_list(2, :stage)
st1 = ~N[2019-01-01T07:00:00]
st2 = ~N[2019-01-02T07:00:00]
p1 = insert_performance(contest, stage: nil, stage_time: nil)
p2 = insert_performance(contest, stage: s1, stage_time: st1)
p3 = insert_performance(contest, stage: s2, stage_time: st2)
params = %{
"performances" => %{
p1.id => %{"stageId" => s1.id, "stageTime" => st1},
p2.id => %{"stageId" => s2.id, "stageTime" => st2},
p3.id => %{"stageId" => nil, "stageTime" => nil}
}
}
conn =
conn
|> patch(Routes.internal_contest_performance_path(conn, :reschedule, contest), params)
assert json_response(conn, 200) == %{
"#{p1.id}" => %{"stageTime" => "2019-01-01T07:00:00"},
"#{p2.id}" => %{"stageTime" => "2019-01-02T07:00:00"},
"#{p3.id}" => %{"stageTime" => nil}
}
end
defp assert_flash_redirect(conn, redirect_path, message) do
assert redirected_to(conn) == redirect_path
# Follow redirection
conn = get(recycle(conn), redirect_path)
assert html_response(conn, 200) =~ message
end
end
| 34.68541 | 114 | 0.656312 |
73687039950c3caed03f3dabafb867b23f1818b9 | 1,700 | ex | Elixir | clients/cloud_build/lib/google_api/cloud_build/v1/model/list_github_enterprise_configs_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/cloud_build/lib/google_api/cloud_build/v1/model/list_github_enterprise_configs_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/cloud_build/lib/google_api/cloud_build/v1/model/list_github_enterprise_configs_response.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudBuild.V1.Model.ListGithubEnterpriseConfigsResponse do
@moduledoc """
RPC response object returned by ListGithubEnterpriseConfigs RPC method.
## Attributes
* `configs` (*type:* `list(GoogleApi.CloudBuild.V1.Model.GitHubEnterpriseConfig.t)`, *default:* `nil`) - A list of GitHubEnterpriseConfigs
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:configs => list(GoogleApi.CloudBuild.V1.Model.GitHubEnterpriseConfig.t()) | nil
}
field(:configs, as: GoogleApi.CloudBuild.V1.Model.GitHubEnterpriseConfig, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.CloudBuild.V1.Model.ListGithubEnterpriseConfigsResponse do
def decode(value, options) do
GoogleApi.CloudBuild.V1.Model.ListGithubEnterpriseConfigsResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudBuild.V1.Model.ListGithubEnterpriseConfigsResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.170213 | 142 | 0.765882 |
736881d08aff74cb17aa531f160a77faca637ef4 | 1,135 | exs | Elixir | plants_weather_traffic/apps/astro_server/config/config.exs | andfoy/cpd-exercises | f36ac16c74bb980d7edd6aaf5661a6d4d4b09489 | [
"MIT"
] | null | null | null | plants_weather_traffic/apps/astro_server/config/config.exs | andfoy/cpd-exercises | f36ac16c74bb980d7edd6aaf5661a6d4d4b09489 | [
"MIT"
] | null | null | null | plants_weather_traffic/apps/astro_server/config/config.exs | andfoy/cpd-exercises | f36ac16c74bb980d7edd6aaf5661a6d4d4b09489 | [
"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 :astro_server, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:astro_server, :key)
#
# You can also configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env()}.exs"
| 36.612903 | 73 | 0.752423 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.