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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03243224c00388eed840b23161763f9023a45dc4 | 2,232 | exs | Elixir | test/arbitrary/gen_test.exs | alexdesousa/arbitrary | 19ace054ec77d179c5ab9d6f9c557eec4b883cbd | [
"MIT"
] | null | null | null | test/arbitrary/gen_test.exs | alexdesousa/arbitrary | 19ace054ec77d179c5ab9d6f9c557eec4b883cbd | [
"MIT"
] | null | null | null | test/arbitrary/gen_test.exs | alexdesousa/arbitrary | 19ace054ec77d179c5ab9d6f9c557eec4b883cbd | [
"MIT"
] | null | null | null | defmodule Arbitrary.GenTest do
use ExUnit.Case, async: true
alias Arbitrary.Gen
describe "choose/1" do
test "generates a function" do
%Gen{gen: f} = Gen.choose(1..10)
assert is_function(f)
end
test "chooses one value of a range" do
a = 1
b = 10
value =
a..b
|> Gen.choose()
|> Gen.generate()
assert a <= value and value <= b
end
end
describe "elements/1" do
test "generates a function" do
values = Enum.to_list(1..10)
%Gen{gen: f} = Gen.elements(values)
assert is_function(f)
end
test "gets a value from a list" do
a = 1
b = 10
value =
a..b
|> Enum.to_list()
|> Gen.elements()
|> Gen.generate()
assert a <= value and value <= b
end
end
describe "sublist_of/1" do
test "generates a function" do
%Gen{gen: f} = Gen.sublist_of([1,2,3])
assert is_function(f)
end
test "gets a subset from a list with values" do
set = [1,2,3,4]
subset =
set
|> Gen.sublist_of()
|> Gen.generate()
assert for i <- subset, do: Enum.member?(set, i)
assert length(subset) <= length(set)
end
end
describe "oneof/1" do
test "generates a function" do
%Gen{gen: f} = Gen.oneof([Gen.choose(1..10)])
assert is_function(f)
end
test "gets one of the generators" do
a = 1
b = 10
generators = [
Gen.choose(a..b),
Gen.elements([21, 42])
]
value =
generators
|> Gen.oneof()
|> Gen.generate()
assert (a <= value and value <= b) or value == 21 or value == 42
end
end
describe "frequency/1" do
test "generates a function" do
%Gen{gen: f} = Gen.frequency([{1, Gen.choose(1..10)}])
assert is_function(f)
end
test "gets one of the generator according to the frequency" do
a = 1
b = 10
generators = [
{0, Gen.choose(a..b)},
{1, Gen.elements([21, 42])}
]
value =
generators
|> Gen.frequency()
|> Gen.generate()
assert (a != value or value != b) and (value == 21 or value == 42)
end
end
end
| 21.257143 | 72 | 0.52957 |
032440784ce449c18a620b1c7868957ce509fe67 | 334 | ex | Elixir | lib/console_web/router_api_pipeline.ex | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 83 | 2018-05-31T14:49:10.000Z | 2022-03-27T16:49:49.000Z | lib/console_web/router_api_pipeline.ex | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 267 | 2018-05-22T23:19:02.000Z | 2022-03-31T04:31:06.000Z | lib/console_web/router_api_pipeline.ex | maco2035/console | 2a9a65678b8c671c7d92cdb62dfcfc71b84957c5 | [
"Apache-2.0"
] | 18 | 2018-11-20T05:15:54.000Z | 2022-03-28T08:20:13.000Z | defmodule ConsoleWeb.RouterApiPipeline do
use Guardian.Plug.Pipeline,
otp_app: :console,
module: ConsoleWeb.Guardian,
error_handler: ConsoleWeb.AuthErrorHandler
plug Guardian.Plug.VerifyHeader, claims: %{"typ" => "router"}
plug Guardian.Plug.EnsureAuthenticated
plug ConsoleWeb.Plug.VerifyRouterSecretVersion
end
| 30.363636 | 63 | 0.784431 |
032447b922ba2985bf4ff2bbc8c658c34a2262d4 | 286 | ex | Elixir | web/views/raw_supplier_rate_view.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/views/raw_supplier_rate_view.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | web/views/raw_supplier_rate_view.ex | zombalo/cgrates_web_jsonapi | 47845be4311839fe180cc9f2c7c6795649da4430 | [
"MIT"
] | null | null | null | defmodule CgratesWebJsonapi.RawSupplierRateView do
use CgratesWebJsonapi.Web, :view
use JaSerializer.PhoenixView
attributes [:rate, :supplier_name, :prefix, :description, :inserted_at, :updated_at]
has_one :tariff_plan,
field: :tariff_plan_id,
type: "tariff_plan"
end
| 26 | 86 | 0.769231 |
032453987d7215340bf0059515723a96834ac136 | 647 | exs | Elixir | config/integration.exs | PhilNorman2/valkyrie | 4f733965492e9a746a4dae217215b7270c24d0c0 | [
"Apache-2.0"
] | null | null | null | config/integration.exs | PhilNorman2/valkyrie | 4f733965492e9a746a4dae217215b7270c24d0c0 | [
"Apache-2.0"
] | null | null | null | config/integration.exs | PhilNorman2/valkyrie | 4f733965492e9a746a4dae217215b7270c24d0c0 | [
"Apache-2.0"
] | null | null | null | use Mix.Config
host =
case System.get_env("HOST_IP") do
nil -> "127.0.0.1"
defined -> defined
end
config :logger,
level: :info
config :valkyrie,
elsa_brokers: [{String.to_atom(host), 9092}],
input_topic_prefix: "raw",
output_topic_prefix: "validated",
divo: [
{DivoKafka, [create_topics: "raw:1:1,validated:1:1,dead-letters:1:1", outside_host: host, auto_topic: false]},
DivoRedis
],
divo_wait: [dwell: 700, max_tries: 50],
retry_count: 5,
retry_initial_delay: 1500
config :yeet,
topic: "dead-letters",
endpoint: [{to_charlist(host), 9092}]
config :smart_city_registry,
redis: [
host: host
]
| 20.21875 | 114 | 0.670788 |
032490a8f5eab0ba5a6eebe5a7283dbc2b95546a | 1,395 | ex | Elixir | lib/ash/resource/actions/shared_options.ex | ChristianTovar/ash | 66435322786c5d0b90a34051da969b68dcc8a045 | [
"MIT"
] | null | null | null | lib/ash/resource/actions/shared_options.ex | ChristianTovar/ash | 66435322786c5d0b90a34051da969b68dcc8a045 | [
"MIT"
] | null | null | null | lib/ash/resource/actions/shared_options.ex | ChristianTovar/ash | 66435322786c5d0b90a34051da969b68dcc8a045 | [
"MIT"
] | null | null | null | defmodule Ash.Resource.Actions.SharedOptions do
@moduledoc false
@shared_options [
name: [
type: :atom,
required: true,
doc: "The name of the action"
],
primary?: [
type: :boolean,
default: false,
doc: "Whether or not this action should be used when no action is specified by the caller."
],
description: [
type: :string,
doc: "An optional description for the action"
]
]
@create_update_opts [
accept: [
type: {:custom, Ash.OptionsHelpers, :list_of_atoms, []},
doc: "The list of attributes to accept. Defaults to all attributes on the resource"
],
reject: [
type: {:custom, Ash.OptionsHelpers, :list_of_atoms, []},
doc: """
A list of attributes not to accept. This is useful if you want to say 'accept all but x'
If this is specified along with `accept`, then everything in the `accept` list minus any matches in the
`reject` list will be accepted.
"""
],
require_attributes: [
type: {:custom, Ash.OptionsHelpers, :list_of_atoms, []},
doc: """
A list of attributes that would normally `allow_nil` to require for this action.
No need to include attributes that are `allow_nil?: false`.
"""
]
]
def shared_options do
@shared_options
end
def create_update_opts do
@create_update_opts
end
end
| 26.320755 | 109 | 0.630108 |
0324abe8c651439955a20bf69fde8b820beec15c | 2,390 | exs | Elixir | mix.exs | van-mronov/joken | da2c7236d037e57814c73e62eededda1e27766ca | [
"Apache-2.0"
] | null | null | null | mix.exs | van-mronov/joken | da2c7236d037e57814c73e62eededda1e27766ca | [
"Apache-2.0"
] | null | null | null | mix.exs | van-mronov/joken | da2c7236d037e57814c73e62eededda1e27766ca | [
"Apache-2.0"
] | null | null | null | defmodule Joken.Mixfile do
use Mix.Project
@version "2.0.0-rc3"
def project do
[
app: :joken,
version: @version,
name: "Joken",
elixir: "~> 1.5",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
consolidate_protocols: Mix.env() != :test,
description: description(),
package: package(),
deps: deps(),
source_ref: "v#{@version}",
source_url: "https://github.com/joken-elixir/joken",
docs: docs_config(),
dialyzer: [plt_add_deps: :apps_direct, plt_add_apps: [:jason]],
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
end
def application do
[
extra_applications: [:logger, :crypto],
mod: {Joken.Application, []}
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:jose, "~> 1.8"},
{:jason, "~> 1.1", optional: true},
{:benchee, "~> 0.13", only: :dev},
# Docs
{:ex_doc, "~> 0.19", only: :dev, runtime: false},
# Dialyzer
{:dialyxir, "~> 1.0.0-rc4", only: :dev, runtime: false},
# Credo
{:credo, "~> 1.0", only: [:dev, :test], runtime: false},
# Test
{:junit_formatter, "~> 3.0", only: :test},
{:stream_data, "~> 0.4", only: :test},
{:excoveralls, "~> 0.10", only: :test}
]
end
defp description do
"""
JWT (JSON Web Token) library for Elixir
"""
end
defp package do
[
files: ["lib", "mix.exs", "README.md", "LICENSE.txt", "CHANGELOG.md"],
maintainers: ["Bryan Joseph", "Victor Nascimento"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/joken-elixir/joken",
"Docs" => "http://hexdocs.pm/joken"
}
]
end
defp docs_config do
[
extra_section: "GUIDES",
extras: [
"guides/introduction.md",
"guides/configuration.md",
"guides/signer.md",
"guides/testing.md",
"guides/common_use_cases.md",
"guides/migration_from_1.md",
"guides/custom_header_arguments.md",
{"CHANGELOG.md", [title: "Changelog"]}
],
main: "introduction"
]
end
end
| 24.141414 | 76 | 0.541841 |
0324afef272ceb73f645ee6d35e275178d475da3 | 9,766 | ex | Elixir | lib/challenge_gov/analytics.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | null | null | null | lib/challenge_gov/analytics.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | null | null | null | lib/challenge_gov/analytics.ex | smartlogic/Challenge_gov | b4203d1fcfb742dd17ecfadb9e9c56ad836d4254 | [
"CC0-1.0"
] | null | null | null | defmodule ChallengeGov.Analytics do
@moduledoc """
Analytics context
"""
@behaviour Stein.Filter
import Ecto.Query
alias ChallengeGov.Challenges.Challenge
alias ChallengeGov.Repo
alias Stein.Filter
def get_challenges(opts \\ []) do
Challenge
|> where([c], not is_nil(c.start_date))
|> where([c], not is_nil(c.end_date))
|> Filter.filter(opts[:filter], __MODULE__)
|> Repo.all()
end
def challenge_prefilter(challenges) do
Enum.filter(challenges, fn challenge ->
!is_nil(challenge.start_date) and !is_nil(challenge.end_date)
end)
end
def active_challenges(all_challenges) do
Enum.filter(all_challenges, fn challenge ->
challenge.status == "published" and
(challenge.sub_status == "open" or challenge.sub_status == "closed")
end)
end
def archived_challenges(all_challenges) do
Enum.filter(all_challenges, fn challenge ->
challenge.status == "published" and challenge.sub_status == "archived"
end)
end
def draft_challenges(all_challenges) do
Enum.filter(all_challenges, fn challenge ->
challenge.status == "draft"
end)
end
def launched_in_year?(challenge, year) do
challenge.start_date.year == year
end
def ongoing_in_year?(challenge, year) do
challenge.start_date.year < year and
challenge.end_date.year > year
end
def closed_in_year?(challenge, year) do
challenge.end_date.year == year
end
def get_year_range(start_year, end_year) do
start_year = get_start_year(start_year)
end_year = get_end_year(end_year)
Enum.to_list(start_year..end_year)
end
def get_start_year(""), do: default_start_year()
def get_start_year(year), do: year_to_integer(year)
def default_start_year, do: Repo.one(select(Challenge, [c], min(c.start_date))).year
def get_end_year(""), do: default_end_year()
def get_end_year(year), do: year_to_integer(year)
def default_end_year, do: DateTime.utc_now().year
defp year_to_integer(year) do
{year, _} = Integer.parse(year)
year
end
def calculate_prize_amount(challenge = %{imported: true}), do: challenge.prize_total || 0
def calculate_prize_amount(challenge), do: (challenge.prize_total || 0) / 1000
def all_challenges(challenges, years) do
challenges = challenge_prefilter(challenges)
data =
years
|> Enum.reduce(%{}, fn year, acc ->
Map.put(
acc,
year,
Enum.count(challenges, fn challenge ->
challenge.start_date.year == year
end)
)
end)
data_obj = %{
datasets: [
%{
data: data
}
]
}
options_obj = []
%{
data: data_obj,
options: options_obj
}
end
def challenges_by_primary_type(challenges, years) do
challenges =
challenges
|> challenge_prefilter()
|> Enum.filter(fn challenge ->
!is_nil(challenge.primary_type)
end)
labels = years
data =
challenges
|> Enum.group_by(fn challenge -> challenge.primary_type end)
colors = ColorStream.hex() |> Enum.take(Enum.count(data))
data =
data
|> Enum.with_index()
|> Enum.reduce([], fn {{primary_type, challenges}, index}, acc ->
grouped_challenges =
Enum.group_by(challenges, fn challenge -> challenge.start_date.year end)
data =
years
|> Enum.map(fn year ->
grouped_challenges = grouped_challenges[year] || []
Enum.count(grouped_challenges)
end)
data = %{
label: primary_type,
data: data,
borderWidth: 1,
backgroundColor: "##{Enum.at(colors, index)}"
}
acc ++ [data]
end)
data_obj = %{
labels: labels,
datasets: data
}
options_obj = [
options: %{
plugins: %{
legend: %{
display: true,
position: "bottom"
}
},
scales: %{
x: %{
stacked: true
},
y: %{
stacked: true
}
}
}
]
%{
data: data_obj,
options: options_obj
}
end
def challenges_hosted_externally(challenges, years) do
challenges = challenge_prefilter(challenges)
colors = ColorStream.hex() |> Enum.take(2)
labels = years
data =
challenges
|> Enum.group_by(fn challenge -> is_nil(challenge.external_url) end)
|> Enum.reduce([], fn {hosted_internally, challenges}, acc ->
grouped_challenges =
Enum.group_by(challenges, fn challenge -> challenge.start_date.year end)
data =
years
|> Enum.map(fn year ->
grouped_challenges = grouped_challenges[year] || []
Enum.count(grouped_challenges)
end)
{label, color_index} =
if hosted_internally, do: {"Hosted on Challenge.gov", 0}, else: {"Hosted externally", 1}
data = %{
label: label,
data: data,
backgroundColor: "##{Enum.at(colors, color_index)}"
}
acc ++ [data]
end)
data_obj = %{
labels: labels,
datasets: data
}
options_obj = [
options: %{
plugins: %{
legend: %{
display: true,
position: "bottom"
}
}
}
]
%{
data: data_obj,
options: options_obj
}
end
def total_cash_prizes(challenges, years) do
challenges = challenge_prefilter(challenges)
data =
years
|> Enum.reduce(%{}, fn year, acc ->
total_prize_amount =
challenges
|> Enum.filter(fn challenge -> challenge.start_date.year == year end)
|> Enum.map(fn challenge ->
calculate_prize_amount(challenge)
end)
|> Enum.sum()
Map.put(acc, year, total_prize_amount)
end)
data_obj = %{
datasets: [
%{
data: data
}
]
}
options_obj = [
options: %{
format: "currency",
plugins: %{
legend: %{
display: false
},
scales: %{
y: %{
beginAtZero: true
}
}
}
}
]
%{
data: data_obj,
options: options_obj
}
end
def challenges_by_legal_authority(challenges, years) do
challenges =
challenges
|> challenge_prefilter()
|> Enum.filter(fn challenge ->
!is_nil(challenge.legal_authority)
end)
colors = ColorStream.hex() |> Enum.take(2)
labels = years
data =
challenges
|> Enum.group_by(fn challenge ->
challenge.legal_authority
|> String.downcase()
|> String.contains?("competes")
end)
|> Enum.reduce([], fn {is_america_competes, challenges}, acc ->
grouped_challenges =
Enum.group_by(challenges, fn challenge -> challenge.start_date.year end)
data =
years
|> Enum.map(fn year ->
grouped_challenges = grouped_challenges[year] || []
Enum.count(grouped_challenges)
end)
{label, color_index} =
if is_america_competes, do: {"America Competes", 0}, else: {"Other", 1}
data = %{
label: label,
data: data,
backgroundColor: "##{Enum.at(colors, color_index)}"
}
acc ++ [data]
end)
data_obj = %{
labels: labels,
datasets: data
}
options_obj = [
options: %{
plugins: %{
legend: %{
display: true,
position: "bottom"
}
}
}
]
%{
data: data_obj,
options: options_obj
}
end
def participating_lead_agencies(challenges, years) do
challenges =
challenges
|> challenge_prefilter()
|> Enum.filter(fn challenge -> !is_nil(challenge.agency_id) end)
labels = years
launched_data =
years
|> Enum.map(fn year ->
challenges
|> Enum.filter(fn challenge -> launched_in_year?(challenge, year) end)
|> Enum.uniq_by(fn challenge -> challenge.agency_id end)
|> Enum.count()
end)
data = [
%{
data: launched_data
}
]
data_obj = %{
labels: labels,
datasets: data
}
options_obj = []
%{
data: data_obj,
options: options_obj
}
end
@impl Stein.Filter
def filter_on_attribute({"agency_id", value}, query) do
where(query, [c], c.agency_id == ^value)
end
def filter_on_attribute({"year_filter", value}, query) do
query
|> maybe_filter_start_year(value)
|> maybe_filter_end_year(value)
end
defp maybe_filter_start_year(query, %{"start_year" => ""}), do: query
defp maybe_filter_start_year(query, %{"target_date" => "start", "start_year" => year}) do
{year, _} = Integer.parse(year)
where(query, [c], fragment("DATE_PART('year', ?)", c.start_date) >= ^year)
end
defp maybe_filter_start_year(query, %{"target_date" => "end", "start_year" => year}) do
{year, _} = Integer.parse(year)
where(query, [c], fragment("DATE_PART('year', ?)", c.end_date) >= ^year)
end
defp maybe_filter_end_year(query, %{"end_year" => ""}), do: query
defp maybe_filter_end_year(query, %{"target_date" => "start", "end_year" => year}) do
{year, _} = Integer.parse(year)
where(query, [c], fragment("DATE_PART('year', ?)", c.start_date) <= ^year)
end
defp maybe_filter_end_year(query, %{"target_date" => "end", "end_year" => year}) do
{year, _} = Integer.parse(year)
where(query, [c], fragment("DATE_PART('year', ?)", c.end_date) <= ^year)
end
end
| 23.14218 | 98 | 0.57178 |
0324fbdb6f341fc6c5f5dae72e69414369136662 | 1,052 | exs | Elixir | config/dev.exs | MihailoIsakov/LixLint | 5edba3068b929417d49b2084bb15b21057e9ca0b | [
"MIT"
] | null | null | null | config/dev.exs | MihailoIsakov/LixLint | 5edba3068b929417d49b2084bb15b21057e9ca0b | [
"MIT"
] | null | null | null | config/dev.exs | MihailoIsakov/LixLint | 5edba3068b929417d49b2084bb15b21057e9ca0b | [
"MIT"
] | null | null | null | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :statika, Statika.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
cache_static_lookup: false,
watchers: [node: ["node_modules/brunch/bin/brunch", "watch"]]
# Watch static and templates for browser reloading.
config :statika, Statika.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Configure your database
config :statika, Statika.Repo,
adapter: Ecto.Adapters.Postgres,
username: "postgres",
password: "postgres",
database: "statika_dev",
size: 10 # The amount of database connections in the pool
| 29.222222 | 63 | 0.708175 |
032523c67a03c02f76d304bbd252b8dde688af63 | 4,252 | ex | Elixir | clients/games/lib/google_api/games/v1/model/player.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/games/lib/google_api/games/v1/model/player.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/games/lib/google_api/games/v1/model/player.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.Games.V1.Model.Player do
@moduledoc """
This is a JSON template for a Player resource.
## Attributes
* `avatarImageUrl` (*type:* `String.t`, *default:* `nil`) - The base URL for the image that represents the player.
* `bannerUrlLandscape` (*type:* `String.t`, *default:* `nil`) - The url to the landscape mode player banner image.
* `bannerUrlPortrait` (*type:* `String.t`, *default:* `nil`) - The url to the portrait mode player banner image.
* `displayName` (*type:* `String.t`, *default:* `nil`) - The name to display for the player.
* `experienceInfo` (*type:* `GoogleApi.Games.V1.Model.PlayerExperienceInfo.t`, *default:* `nil`) - An object to represent Play Game experience information for the player.
* `kind` (*type:* `String.t`, *default:* `games#player`) - Uniquely identifies the type of this resource. Value is always the fixed string games#player.
* `lastPlayedWith` (*type:* `GoogleApi.Games.V1.Model.Played.t`, *default:* `nil`) - Details about the last time this player played a multiplayer game with the currently authenticated player. Populated for PLAYED_WITH player collection members.
* `name` (*type:* `GoogleApi.Games.V1.Model.PlayerName.t`, *default:* `nil`) - An object representation of the individual components of the player's name. For some players, these fields may not be present.
* `originalPlayerId` (*type:* `String.t`, *default:* `nil`) - The player ID that was used for this player the first time they signed into the game in question. This is only populated for calls to player.get for the requesting player, only if the player ID has subsequently changed, and only to clients that support remapping player IDs.
* `playerId` (*type:* `String.t`, *default:* `nil`) - The ID of the player.
* `profileSettings` (*type:* `GoogleApi.Games.V1.Model.ProfileSettings.t`, *default:* `nil`) - The player's profile settings. Controls whether or not the player's profile is visible to other players.
* `title` (*type:* `String.t`, *default:* `nil`) - The player's title rewarded for their game activities.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:avatarImageUrl => String.t(),
:bannerUrlLandscape => String.t(),
:bannerUrlPortrait => String.t(),
:displayName => String.t(),
:experienceInfo => GoogleApi.Games.V1.Model.PlayerExperienceInfo.t(),
:kind => String.t(),
:lastPlayedWith => GoogleApi.Games.V1.Model.Played.t(),
:name => GoogleApi.Games.V1.Model.PlayerName.t(),
:originalPlayerId => String.t(),
:playerId => String.t(),
:profileSettings => GoogleApi.Games.V1.Model.ProfileSettings.t(),
:title => String.t()
}
field(:avatarImageUrl)
field(:bannerUrlLandscape)
field(:bannerUrlPortrait)
field(:displayName)
field(:experienceInfo, as: GoogleApi.Games.V1.Model.PlayerExperienceInfo)
field(:kind)
field(:lastPlayedWith, as: GoogleApi.Games.V1.Model.Played)
field(:name, as: GoogleApi.Games.V1.Model.PlayerName)
field(:originalPlayerId)
field(:playerId)
field(:profileSettings, as: GoogleApi.Games.V1.Model.ProfileSettings)
field(:title)
end
defimpl Poison.Decoder, for: GoogleApi.Games.V1.Model.Player do
def decode(value, options) do
GoogleApi.Games.V1.Model.Player.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Games.V1.Model.Player do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 53.15 | 340 | 0.706961 |
032538e48015271245405531167e894de8dd23bf | 159 | exs | Elixir | samples/cowboy_wobserver/config/config.exs | IanLuites/wobserver-elixirconf-2017 | 86a56a392a5877d2d9a51dc7fbd7e0d8b576c711 | [
"MIT"
] | 11 | 2017-05-05T12:28:35.000Z | 2020-02-26T09:16:10.000Z | samples/cowboy_wobserver/config/config.exs | IanLuites/wobserver-elixirconf-2017 | 86a56a392a5877d2d9a51dc7fbd7e0d8b576c711 | [
"MIT"
] | null | null | null | samples/cowboy_wobserver/config/config.exs | IanLuites/wobserver-elixirconf-2017 | 86a56a392a5877d2d9a51dc7fbd7e0d8b576c711 | [
"MIT"
] | null | null | null | use Mix.Config
config :wobserver,
mode: :plug,
remote_url_prefix: "/wobserver"
# config :logger, level: :info
#
# import_config "#{Mix.env}.exs"
| 15.9 | 36 | 0.654088 |
0325426da13d4c109984abd60235d652523d4135 | 746 | ex | Elixir | api/lib/trello_clone_api/project/board.ex | arkanoryn/trello-clone | 2d5f5bc5c498c1740054dc56da16ad78c545b755 | [
"Apache-2.0"
] | 1 | 2021-04-17T20:20:59.000Z | 2021-04-17T20:20:59.000Z | api/lib/trello_clone_api/project/board.ex | arkanoryn/trello-clone | 2d5f5bc5c498c1740054dc56da16ad78c545b755 | [
"Apache-2.0"
] | null | null | null | api/lib/trello_clone_api/project/board.ex | arkanoryn/trello-clone | 2d5f5bc5c498c1740054dc56da16ad78c545b755 | [
"Apache-2.0"
] | null | null | null | defmodule TrelloCloneApi.Project.Board do
use Ecto.Schema
import Ecto.Changeset
import Ecto.Query, only: [from: 2]
schema "boards" do
field(:description, :string)
field(:name, :string)
belongs_to(:project, TrelloCloneApi.Organization.Project)
timestamps()
end
@doc false
def changeset(board, attrs) do
board
|> cast(attrs, [:name, :description, :project_id], ~w())
|> validate_required([:name, :description, :project_id])
|> foreign_key_constraint(:project_id)
end
def by_project(query, project_id) do
from(
c in query,
where: c.project_id == ^project_id,
preload: [:project]
)
end
def load_project(query) do
from(c in query, preload: [:project])
end
end
| 21.941176 | 61 | 0.663539 |
0325528c70de2f417866e9a1f01659d9d66e1945 | 40,340 | exs | Elixir | test/session_test.exs | desoulter/smppex | 1c8dbd9673291431b2d329a2cb20134c91857af2 | [
"MIT"
] | null | null | null | test/session_test.exs | desoulter/smppex | 1c8dbd9673291431b2d329a2cb20134c91857af2 | [
"MIT"
] | null | null | null | test/session_test.exs | desoulter/smppex | 1c8dbd9673291431b2d329a2cb20134c91857af2 | [
"MIT"
] | null | null | null | defmodule SMPPEX.SessionTest do
use ExUnit.Case
alias :timer, as: Timer
alias :sys, as: Sys
alias Support.TCP.Server
alias SMPPEX.Session
alias SMPPEX.Pdu
setup do
server = Server.start_link()
Timer.sleep(50)
{:ok, callback_agent} = Agent.start_link(fn -> [] end)
callbacks = fn ->
Agent.get(
callback_agent,
&Enum.reverse(&1)
)
end
esme_opts = [
enquire_link_limit: 1000,
session_init_limit: :infinity,
enquire_link_resp_limit: 1000,
inactivity_limit: 10_000,
response_limit: 2000,
timer_resolution: 100_000
]
esme_with_opts = fn handler, opts ->
case SMPPEX.ESME.start_link(
{127, 0, 0, 1},
Server.port(server),
{Support.Session, {callback_agent, handler}},
esme_opts: opts
) do
{:ok, pid} -> pid
other -> other
end
end
esme = &esme_with_opts.(&1, esme_opts)
{:ok, esme: esme, esme_with_opts: esme_with_opts, callbacks: callbacks, server: server}
end
test "send_pdu", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
assert {:ok, {:pdu, pdu1}, _} = Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.mandatory_field(pdu, :system_id) == Pdu.mandatory_field(pdu1, :system_id)
assert Pdu.mandatory_field(pdu, :password) == Pdu.mandatory_field(pdu1, :password)
end
test "send_pdu sequence_numbers", ctx do
pdu1 = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
pdu2 = SMPPEX.Pdu.Factory.bind_transceiver("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
end)
Session.send_pdu(esme, pdu1)
Session.send_pdu(esme, pdu2)
Timer.sleep(50)
assert {:ok, {:pdu, pdu1r}, rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, pdu2r}, _} = rest_data |> SMPPEX.Protocol.parse()
assert Pdu.sequence_number(pdu1r) == 1
assert Pdu.sequence_number(pdu2r) == 2
end
test "reply, reply sequence_number", ctx do
pdu = %Pdu{
SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
| sequence_number: 123
}
{:ok, pdu_data} = SMPPEX.Protocol.build(pdu)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_pdu, _pdu}, st -> {:ok, st}
end)
Server.send(ctx[:server], pdu_data)
Timer.sleep(50)
assert [{:init, _, _}, {:handle_pdu, received_pdu}] = ctx[:callbacks].()
reply_pdu = SMPPEX.Pdu.Factory.bind_transmitter_resp(0) |> Pdu.as_reply_to(received_pdu)
Session.send_pdu(esme, reply_pdu)
Timer.sleep(50)
assert {:ok, {:pdu, reply_received}, _} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.sequence_number(reply_received) == 123
end
test "stop", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:terminate, _reason, _lost_pdus}, _st -> :stop
end)
Timer.sleep(50)
assert :ok = Session.stop(esme, :oops)
assert [
{:init, _, _},
{:terminate, :oops, _lost_pdus}
] = ctx[:callbacks].()
receive do
x -> assert {:EXIT, ^esme, :oops} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "cast", ctx do
ref = make_ref()
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_cast, _}, st -> {:noreply, st}
end)
Session.cast(esme, ref)
Timer.sleep(10)
assert [{:init, _, _}, {:handle_cast, ^ref}] = ctx[:callbacks].()
end
test "cast with pdu", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_cast, :req}, st -> {:noreply, [SMPPEX.Pdu.Factory.enquire_link()], st}
{:handle_send_pdu_result, _, _}, st -> st
end)
assert :ok == Session.cast(esme, :req)
Timer.sleep(50)
assert {:ok, {:pdu, enquire_link_pdu}, _rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.command_name(enquire_link_pdu) == :enquire_link
end
test "terminate with sending pdus", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _, _}, st -> st
{:terminate, _, _}, st -> {:stop, [SMPPEX.Pdu.Factory.enquire_link()], st}
end)
assert :ok == Session.stop(esme)
Timer.sleep(50)
assert {:ok, {:pdu, enquire_link_pdu}, _rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.command_name(enquire_link_pdu) == :enquire_link
end
test "terminate with invalid response", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:terminate, _reason, _lost_pdus}, _st -> :bad_resp
end)
assert :ok = Session.stop(esme, :oops)
receive do
x -> assert {:EXIT, ^esme, {:bad_terminate_reply, :bad_resp}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "cast with stop", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_cast, :req}, st -> {:stop, :ooops, st}
{:terminate, _, _}, _ -> :stop
end)
Session.cast(esme, :req)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_cast, :req},
{:terminate, :ooops, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "cast with invalid reply", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_cast, _}, _st -> :foo
{:terminate, _, _}, _ -> :stop
end)
Session.cast(esme, :bar)
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_cast_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "call", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_call, :req, _from}, st -> {:reply, :got_it, st}
end)
assert :got_it == Session.call(esme, :req)
assert [{:init, _, _}, {:handle_call, :req, _from}] = ctx[:callbacks].()
end
test "call with delayed reply", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st ->
{:ok, st}
{:handle_call, :req, from}, st ->
spawn(fn -> Session.reply(from, :got_it) end)
{:noreply, st}
end)
assert :got_it == Session.call(esme, :req)
end
test "call with delayed reply and pdu", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st ->
{:ok, st}
{:handle_call, :req, from}, st ->
spawn(fn -> Session.reply(from, :got_it) end)
{:noreply, [SMPPEX.Pdu.Factory.enquire_link()], st}
{:handle_send_pdu_result, _, _}, st ->
st
end)
assert :got_it == Session.call(esme, :req)
Timer.sleep(50)
assert {:ok, {:pdu, enquire_link_pdu}, _rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.command_name(enquire_link_pdu) == :enquire_link
end
test "call with delayed reply and stop", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st ->
{:ok, st}
{:handle_call, :req, from}, st ->
spawn(fn ->
Timer.sleep(20)
Session.reply(from, :got_it)
end)
{:stop, :ooops, st}
{:terminate, _, _}, _ ->
:stop
end)
spawn_link(fn -> Session.call(esme, :req) end)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_call, :req, _from},
{:terminate, :ooops, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "call with invalid handle_call reply", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_call, _, _}, _st -> :foo
{:terminate, _, _}, _ -> :stop
end)
spawn(fn -> Session.call(esme, :bar) end)
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_call_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "info", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_info, :req}, st -> {:noreply, st}
end)
Kernel.send(esme, :req)
Timer.sleep(50)
assert [{:init, _, _}, {:handle_info, :req}] = ctx[:callbacks].()
end
test "info with pdu", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_info, :req}, st -> {:noreply, [SMPPEX.Pdu.Factory.enquire_link()], st}
{:handle_send_pdu_result, _, _}, st -> st
end)
Kernel.send(esme, :req)
Timer.sleep(50)
assert {:ok, {:pdu, enquire_link_pdu}, _rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.command_name(enquire_link_pdu) == :enquire_link
end
test "info with stop", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_info, :req}, st -> {:stop, :ooops, st}
{:terminate, _, _}, _ -> :stop
end)
Kernel.send(esme, :req)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_info, :req},
{:terminate, :ooops, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "info with invalid reply", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_info, _}, _st -> :foo
{:terminate, _, _}, _ -> :stop
end)
send(esme, :bar)
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_info_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "init", ctx do
_esme = ctx[:esme].(fn {:init, _socket, _transport}, st -> {:ok, st} end)
assert [{:init, _, _}] = ctx[:callbacks].()
end
test "init, stop from init", ctx do
Process.flag(:trap_exit, true)
assert {:error, :oops} ==
ctx[:esme].(fn {:init, _socket, _transport}, _st -> {:stop, :oops} end)
end
test "handle_pdu with ok", ctx do
pdu = %Pdu{
SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
| sequence_number: 123
}
{:ok, pdu_data} = SMPPEX.Protocol.build(pdu)
_esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_pdu, _pdu}, st -> {:ok, st}
end)
Server.send(ctx[:server], pdu_data)
Timer.sleep(50)
assert [{:init, _, _}, {:handle_pdu, received_pdu}] = ctx[:callbacks].()
assert Pdu.mandatory_field(received_pdu, :system_id) == "system_id"
assert Pdu.mandatory_field(received_pdu, :password) == "password"
assert Pdu.sequence_number(received_pdu) == 123
end
test "handle_pdu with ok and pdus", ctx do
pdu = %Pdu{
SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
| sequence_number: 123
}
{:ok, pdu_data} = SMPPEX.Protocol.build(pdu)
_esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_pdu, _pdu}, st -> {:ok, [SMPPEX.Pdu.Factory.bind_transmitter_resp(0)], st}
end)
Server.send(ctx[:server], pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_pdu, _},
{:handle_send_pdu_result, _, _}
] = ctx[:callbacks].()
assert {:ok, {:pdu, reply_pdu}, _rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.command_name(reply_pdu) == :bind_transmitter_resp
end
test "handle_pdu with stop", ctx do
Process.flag(:trap_exit, true)
pdu = %Pdu{
SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
| sequence_number: 123
}
{:ok, pdu_data} = SMPPEX.Protocol.build(pdu)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_pdu, _pdu}, st -> {:stop, :nopenope, st}
{:terminate, _, _}, _st -> :stop
end)
Server.send(ctx[:server], pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_pdu, _},
{:terminate, :nopenope, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "handle_pdu with invalid reply", ctx do
Process.flag(:trap_exit, true)
pdu = %Pdu{
SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
| sequence_number: 123
}
{:ok, pdu_data} = SMPPEX.Protocol.build(pdu)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_pdu, _pdu}, _st -> :foo
{:terminate, _, _}, _st -> :stop
end)
Server.send(ctx[:server], pdu_data)
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_pdu_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "handle_resp ok", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp, received_reply_pdu, _}
] = ctx[:callbacks].()
assert Pdu.mandatory_field(received_reply_pdu, :system_id) == "sid"
end
test "handle_resp ok with pdus", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, [SMPPEX.Pdu.Factory.enquire_link()], st}
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp, received_reply_pdu, _},
{:handle_send_pdu_result, _, :ok}
] = ctx[:callbacks].()
assert Pdu.mandatory_field(received_reply_pdu, :system_id) == "sid"
assert {:ok, {:pdu, _}, rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, enquire_link_pdu}, _rest_data} = SMPPEX.Protocol.parse(rest_data)
assert Pdu.command_name(enquire_link_pdu) == :enquire_link
end
test "handle_resp ok with stop", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:stop, :nopenope, st}
{:terminate, _, _}, _ -> :stop
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp, _, _},
{:terminate, :nopenope, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "handle_resp (with additional submit_sm)", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
pdu = SMPPEX.Pdu.Factory.submit_sm({"from", 1, 2}, {"to", 1, 2}, "message")
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.submit_sm_resp(0) | sequence_number: 2}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp, bind_resp, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp, submit_sm_resp, _}
] = ctx[:callbacks].()
assert Pdu.command_name(bind_resp) == :bind_transmitter_resp
assert Pdu.command_name(submit_sm_resp) == :submit_sm_resp
end
test "handle_resp with unknown resp", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 2}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok}
] = ctx[:callbacks].()
end
test "handle_resp with invalid reply", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id", "password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, _st -> :foo
{:terminate, _, _}, _ -> :stop
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_resp_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "handle_resp_timeout with ok", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp_timeout, _pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
Kernel.send(esme, {:check_expired_pdus, time + 2050})
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp_timeout, [timeout_pdu]}
] = ctx[:callbacks].()
assert Pdu.mandatory_field(timeout_pdu, :system_id) == "system_id1"
end
test "handle_resp_timeout with invalid pdu", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "too_long_password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp_timeout, _pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
Kernel.send(esme, {:check_expired_pdus, time + 2050})
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, invalid_pdu, {:error, _}}
] = ctx[:callbacks].()
assert Pdu.mandatory_field(invalid_pdu, :system_id) == "system_id1"
end
test "handle_resp_timeout with ok and pdus", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp_timeout, _pdu}, st -> {:ok, [SMPPEX.Pdu.Factory.enquire_link()], st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
Kernel.send(esme, {:check_expired_pdus, time + 2050})
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp_timeout, [timeout_pdu]},
{:handle_send_pdu_result, _, :ok}
] = ctx[:callbacks].()
assert Pdu.mandatory_field(timeout_pdu, :system_id) == "system_id1"
assert {:ok, {:pdu, _}, rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, enquire_link_pdu}, _rest_data} = SMPPEX.Protocol.parse(rest_data)
assert Pdu.command_name(enquire_link_pdu) == :enquire_link
end
test "handle_resp_timeout with stop", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp_timeout, _pdu}, st -> {:stop, :nopenope, st}
{:terminate, _, _}, _ -> :stop
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
Kernel.send(esme, {:check_expired_pdus, time + 2050})
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, :ok},
{:handle_resp_timeout, [_timeout_pdu]},
{:terminate, :nopenope, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "handle_resp_timeout with invalid reply", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp_timeout, _pdu}, _st -> :foo
{:terminate, _, _}, _ -> :stop
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
Kernel.send(esme, {:check_expired_pdus, time + 2050})
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_resp_timeout_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "handle_send_pdu_result", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "too_long_password")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, {:error, _}}
] = ctx[:callbacks].()
end
test "handle_unparsed_pdu with ok", ctx do
Server.send(ctx[:server], <<
00,
00,
00,
0x10,
0x80,
00,
0x33,
0x02,
00,
00,
00,
00,
00,
00,
00,
0x01,
0xAA,
0xBB,
0xCC
>>)
_esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_unparsed_pdu, _pdu, _error}, st -> {:ok, st}
end)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_unparsed_pdu, _pdu, "Unknown command_id"}
] = ctx[:callbacks].()
end
test "handle_unparsed_pdu with ok and pdus", ctx do
_esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_unparsed_pdu, _pdu, _error}, st -> {:ok, [SMPPEX.Pdu.Factory.enquire_link()], st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
end)
Server.send(ctx[:server], <<
00,
00,
00,
0x10,
0x80,
00,
0x33,
0x02,
00,
00,
00,
00,
00,
00,
00,
0x01,
0xAA,
0xBB,
0xCC
>>)
Timer.sleep(50)
assert {:ok, {:pdu, reply_pdu}, _rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert Pdu.command_name(reply_pdu) == :enquire_link
end
test "handle_unparsed_pdu with ok and stop", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_unparsed_pdu, _pdu, _error}, st -> {:stop, :nopenope, st}
{:terminate, _pdu, _los_pdus}, _st -> :stop
end)
Server.send(ctx[:server], <<
00,
00,
00,
0x10,
0x80,
00,
0x33,
0x02,
00,
00,
00,
00,
00,
00,
00,
0x01,
0xAA,
0xBB,
0xCC
>>)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_unparsed_pdu, _pdu, "Unknown command_id"},
{:terminate, :nopenope, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "handle_unparsed_pdu with invalid reply", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_unparsed_pdu, _pdu, _error}, _st -> :foo
{:terminate, _pdu, _los_pdus}, _st -> :stop
end)
Server.send(ctx[:server], <<
00,
00,
00,
0x10,
0x80,
00,
0x33,
0x02,
00,
00,
00,
00,
00,
00,
00,
0x01,
0xAA,
0xBB,
0xCC
>>)
receive do
x -> assert {:EXIT, ^esme, {:bad_handle_unparsed_pdu_reply, :foo}} = x
after
50 ->
assert false
end
refute Process.alive?(esme)
end
test "enquire_link by timeout", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 1050})
Timer.sleep(50)
assert {:ok, {:pdu, _}, rest_data} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, enquire_link}, _} = rest_data |> SMPPEX.Protocol.parse()
assert Pdu.command_name(enquire_link) == :enquire_link
end
test "enquire_link by timeout and consequent submit_sm", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 1050})
pdu = SMPPEX.Pdu.Factory.submit_sm({"from", 1, 2}, {"to", 1, 2}, "message")
Session.send_pdu(esme, pdu)
Timer.sleep(50)
assert {:ok, {:pdu, _}, rest_data0} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, enquire_link}, rest_data1} = rest_data0 |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, submit_sm}, _} = rest_data1 |> SMPPEX.Protocol.parse()
assert Pdu.sequence_number(enquire_link) < Pdu.sequence_number(submit_sm)
end
test "enquire_link cancel by peer action", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 950})
Timer.sleep(50)
action_pdu = %Pdu{SMPPEX.Pdu.Factory.enquire_link() | sequence_number: 1}
{:ok, action_pdu_data} = SMPPEX.Protocol.build(action_pdu)
Server.send(ctx[:server], action_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 1050})
Timer.sleep(50)
assert {:ok, {:pdu, _bind_pdu}, rest} =
Server.received_data(ctx[:server]) |> SMPPEX.Protocol.parse()
assert {:ok, {:pdu, _enquire_link_resp}, <<>>} = rest |> SMPPEX.Protocol.parse()
end
test "enquire_link timeout cancel by peer action", ctx do
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 1050})
Timer.sleep(50)
action_pdu = %Pdu{SMPPEX.Pdu.Factory.enquire_link() | sequence_number: 1}
{:ok, action_pdu_data} = SMPPEX.Protocol.build(action_pdu)
Server.send(ctx[:server], action_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 2100})
Timer.sleep(50)
assert [
{:init, _, _},
# bind_transmitter sent
{:handle_send_pdu_result, _, :ok},
{:handle_resp, _, _}
] = ctx[:callbacks].()
end
test "stop by enquire_link timeout", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
{:terminate, _reason, _los_pdus}, _st -> :stop
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 1050})
Kernel.send(esme, {:tick, time + 2050})
Timer.sleep(50)
assert [
{:init, _, _},
# bind_transmitter sent
{:handle_send_pdu_result, _, :ok},
{:handle_resp, _, _},
{:terminate, {:timers, :enquire_link_timer}, _los_pdus}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "stop by inactivity timeout", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
{:terminate, _reason, _los_pdus}, _st -> :stop
end)
Session.send_pdu(esme, pdu)
time = SMPPEX.Compat.monotonic_time()
Timer.sleep(50)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 10050})
Timer.sleep(50)
assert [
{:init, _, _},
# bind_transmitter sent
{:handle_send_pdu_result, _, :ok},
{:handle_resp, _, _},
{:terminate, {:timers, :inactivity_timer}, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "stop by session_init_time", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme_with_opts].(
fn
{:init, _socket, _transport}, st -> {:ok, st}
{:terminate, _reason, _los_pdus}, _st -> :stop
end,
session_init_limit: 1000
)
time = SMPPEX.Compat.monotonic_time()
Kernel.send(esme, {:tick, time + 1050})
Timer.sleep(50)
assert [
{:init, _, _},
{:terminate, {:timers, :session_init_timer}, []}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "stop by session_init_time cancel: esme", ctx do
esme =
ctx[:esme_with_opts].(
fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:handle_resp, _pdu, _original_pdu}, st -> {:ok, st}
{:terminate, _reason, _los_pdus}, _st -> :stop
end,
session_init_limit: 1000
)
time = SMPPEX.Compat.monotonic_time()
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
Session.send_pdu(esme, pdu)
reply_pdu = %Pdu{SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid") | sequence_number: 1}
{:ok, reply_pdu_data} = SMPPEX.Protocol.build(reply_pdu)
Server.send(ctx[:server], reply_pdu_data)
Timer.sleep(50)
Kernel.send(esme, {:tick, time + 1050})
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, _},
{:handle_resp, _, _}
] = ctx[:callbacks].()
assert Process.alive?(esme)
end
test "stop by session_init_time cancel: mc", ctx do
esme =
ctx[:esme_with_opts].(
fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
end,
session_init_limit: 1000
)
time = SMPPEX.Compat.monotonic_time()
pdu = SMPPEX.Pdu.Factory.bind_transmitter_resp(0, "sid")
Session.send_pdu(esme, pdu)
Kernel.send(esme, {:tick, time + 1050})
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, _}
] = ctx[:callbacks].()
assert Process.alive?(esme)
end
test "lost_pdus", ctx do
Process.flag(:trap_exit, true)
pdu = SMPPEX.Pdu.Factory.bind_transmitter("system_id1", "pass1")
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_send_pdu_result, _pdu, _result}, st -> st
{:terminate, _reason, _los_pdus}, _st -> :stop
end)
Session.send_pdu(esme, pdu)
Timer.sleep(50)
Process.exit(esme, :oops)
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_send_pdu_result, _, _},
{:terminate, :oops, [%SMPPEX.Pdu{command_id: 2}]}
] = ctx[:callbacks].()
refute Process.alive?(esme)
end
test "timeout event", ctx do
esme = ctx[:esme].(fn {:init, _socket, _transport}, st -> {:ok, st} end)
Kernel.send(esme, {:timeout, make_ref(), :emit_tick})
Timer.sleep(50)
assert [
{:init, _, _}
] = ctx[:callbacks].()
assert Process.alive?(esme)
end
test "code_change ok", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:code_change, _old_vsn, _extra}, st -> {:ok, st}
end)
Sys.suspend(esme)
Sys.change_code(esme, Support.Session, '0.0.1', :some_extra)
Sys.resume(esme)
assert [
{:init, _, _},
{:code_change, '0.0.1', :some_extra}
] = ctx[:callbacks].()
end
test "code_change fail", ctx do
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:code_change, _old_vsn, _extra}, _st -> {:error, :oops}
end)
Sys.suspend(esme)
Sys.change_code(esme, Support.Session, '0.0.1', :some_extra)
Sys.resume(esme)
assert [
{:init, _, _},
{:code_change, '0.0.1', :some_extra}
] = ctx[:callbacks].()
end
test "socket closed", ctx do
Process.flag(:trap_exit, true)
_esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_socket_closed}, st -> {:ooops, st}
{:terminate, _reason, _los_pdus}, _st -> :stop
end)
Server.stop(ctx[:server])
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_socket_closed},
{:terminate, :ooops, []}
] = ctx[:callbacks].()
end
test "socket error", ctx do
Process.flag(:trap_exit, true)
esme =
ctx[:esme].(fn
{:init, _socket, _transport}, st -> {:ok, st}
{:handle_socket_error, :wow_such_socket_error}, st -> {:ooops, st}
{:terminate, _reason, _los_pdus}, _st -> :stop
end)
{_ok, _closed, error} = Support.Session.socket_messages()
Kernel.send(esme, {error, :socket, :wow_such_socket_error})
Timer.sleep(50)
assert [
{:init, _, _},
{:handle_socket_error, :wow_such_socket_error},
{:terminate, :ooops, []}
] = ctx[:callbacks].()
end
end
| 26.821809 | 98 | 0.577343 |
03257c0398bce53c2b79a62967952fa4b609a4c6 | 6,959 | ex | Elixir | lib/iex/lib/iex/evaluator.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | lib/iex/lib/iex/evaluator.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | lib/iex/lib/iex/evaluator.ex | diogovk/elixir | 7b8213affaad38b50afaa3dfc3a43717f35ba4e7 | [
"Apache-2.0"
] | null | null | null | defmodule IEx.Evaluator do
@moduledoc false
@doc """
Eval loop for an IEx session. Its responsibilities include:
* loading of .iex files
* evaluating code
* trapping exceptions in the code being evaluated
* keeping expression history
"""
def init(server, leader, opts) do
old_leader = Process.group_leader
Process.group_leader(self, leader)
try do
loop(server, IEx.History.init, loop_state(opts))
after
Process.group_leader(self, old_leader)
end
end
defp loop(server, history, state) do
receive do
{:eval, ^server, code, iex_state} ->
{result, history, state} = eval(code, iex_state, history, state)
send server, {:evaled, self, result}
loop(server, history, state)
{:peek_env, receiver} ->
send receiver, {:peek_env, state.env}
loop(server, history, state)
{:done, ^server} ->
:ok
end
end
defp loop_state(opts) do
env =
if env = opts[:env] do
:elixir.env_for_eval(env, [])
else
:elixir.env_for_eval(file: "iex")
end
{_, _, env, scope} = :elixir.eval('import IEx.Helpers', [], env)
binding = Keyword.get(opts, :binding, [])
state = %{binding: binding, scope: scope, env: env}
case opts[:dot_iex_path] do
"" -> state
path -> load_dot_iex(state, path)
end
end
defp load_dot_iex(state, path) do
candidates = if path do
[path]
else
Enum.map [".iex.exs", "~/.iex.exs"], &Path.expand/1
end
path = Enum.find candidates, &File.regular?/1
if is_nil(path) do
state
else
eval_dot_iex(state, path)
end
end
defp eval_dot_iex(state, path) do
try do
code = File.read!(path)
env = :elixir.env_for_eval(state.env, file: path, line: 1)
# Evaluate the contents in the same environment server_loop will run in
{_result, binding, env, _scope} =
:elixir.eval(String.to_charlist(code), state.binding, env)
%{state | binding: binding, env: :elixir.env_for_eval(env, file: "iex", line: 1)}
catch
kind, error ->
io_result "Error while evaluating: #{path}"
print_error(kind, error, System.stacktrace)
System.halt(1)
end
end
# Instead of doing just :elixir.eval, we first parse the expression to see
# if it's well formed. If parsing succeeds, we evaluate the AST as usual.
#
# If parsing fails, this might be a TokenMissingError which we treat in
# a special way (to allow for continuation of an expression on the next
# line in IEx). In case of any other error, we let :elixir_translator
# to re-raise it.
#
# Returns updated state.
#
# The first two clauses provide support for the break-trigger allowing to
# break out from a pending incomplete expression. See
# https://github.com/elixir-lang/elixir/issues/1089 for discussion.
@break_trigger '#iex:break\n'
defp eval(code, iex_state, history, state) do
try do
do_eval(String.to_charlist(code), iex_state, history, state)
catch
kind, error ->
print_error(kind, error, System.stacktrace)
{%{iex_state | cache: ''}, history, state}
end
end
defp do_eval(@break_trigger, %IEx.State{cache: ''} = iex_state, history, state) do
{iex_state, history, state}
end
defp do_eval(@break_trigger, iex_state, _history, _state) do
:elixir_errors.parse_error(iex_state.counter, "iex", "incomplete expression", "")
end
defp do_eval(latest_input, iex_state, history, state) do
code = iex_state.cache ++ latest_input
line = iex_state.counter
Process.put(:iex_history, history)
handle_eval(Code.string_to_quoted(code, [line: line, file: "iex"]), code, line, iex_state, history, state)
after
Process.delete(:iex_history)
end
defp handle_eval({:ok, forms}, code, line, iex_state, history, state) do
{result, binding, env, scope} =
:elixir.eval_forms(forms, state.binding, state.env, state.scope)
unless result == IEx.dont_display_result, do: io_inspect(result)
iex_state =
%{iex_state | cache: '',
counter: iex_state.counter + 1}
state =
%{state | env: env,
scope: scope,
binding: binding}
{iex_state, update_history(history, line, code, result), state}
end
defp handle_eval({:error, {_, _, ""}}, code, _line, iex_state, history, state) do
# Update iex_state.cache so that IEx continues to add new input to
# the unfinished expression in "code"
{%{iex_state | cache: code}, history, state}
end
defp handle_eval({:error, {line, error, token}}, _code, _line, _iex_state, _, _state) do
# Encountered malformed expression
:elixir_errors.parse_error(line, "iex", error, token)
end
defp update_history(history, counter, cache, result) do
IEx.History.append(history, {counter, cache, result}, IEx.Config.history_size)
end
defp io_inspect(result) do
io_result inspect(result, IEx.inspect_opts)
end
defp io_result(result) do
IO.puts :stdio, IEx.color(:eval_result, result)
end
defp io_error(result) do
IO.puts :stdio, IEx.color(:eval_error, result)
end
## Error handling
defp print_error(kind, reason, stacktrace) do
Exception.format_banner(kind, reason, stacktrace) |> io_error
stacktrace |> prune_stacktrace |> format_stacktrace |> io_error
end
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_clauses,
:elixir_translator, :elixir_expand, :elixir_lexical, :elixir_exp_clauses,
:elixir_def, :elixir_map]
defp prune_stacktrace(stacktrace) do
# The order in which each drop_while is listed is important.
# For example, the user my call Code.eval_string/2 in IEx
# and if there is an error we should not remove erl_eval
# and eval_bits information from the user stacktrace.
stacktrace
|> Enum.reverse()
|> Enum.drop_while(&(elem(&1, 0) == __MODULE__))
|> Enum.drop_while(&(elem(&1, 0) == :elixir))
|> Enum.drop_while(&(elem(&1, 0) in [:erl_eval, :eval_bits]))
|> Enum.reverse()
|> Enum.reject(&(elem(&1, 0) in @elixir_internals))
end
@doc false
def format_stacktrace(trace) do
entries =
for entry <- trace do
split_entry(Exception.format_stacktrace_entry(entry))
end
width = Enum.reduce entries, 0, fn {app, _}, acc ->
max(String.length(app), acc)
end
" " <> Enum.map_join(entries, "\n ", &format_entry(&1, width))
end
defp split_entry(entry) do
case entry do
"(" <> _ ->
case :binary.split(entry, ") ") do
[left, right] -> {left <> ") ", right}
_ -> {"", entry}
end
_ ->
{"", entry}
end
end
defp format_entry({app, info}, width) do
app = String.rjust(app, width)
IEx.color(:stack_app, app) <> IEx.color(:stack_info, info)
end
end
| 29.99569 | 110 | 0.643196 |
0325952fa2f6c67f0ff44fb6b5cd38ce441e42b6 | 4,898 | ex | Elixir | clients/you_tube/lib/google_api/you_tube/v3/model/channel.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/channel.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/channel.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.YouTube.V3.Model.Channel do
@moduledoc """
A channel resource contains information about a YouTube channel.
## Attributes
- auditDetails (ChannelAuditDetails): The auditionDetails object encapsulates channel data that is relevant for YouTube Partners during the audition process. Defaults to: `null`.
- brandingSettings (ChannelBrandingSettings): The brandingSettings object encapsulates information about the branding of the channel. Defaults to: `null`.
- contentDetails (ChannelContentDetails): The contentDetails object encapsulates information about the channel's content. Defaults to: `null`.
- contentOwnerDetails (ChannelContentOwnerDetails): The contentOwnerDetails object encapsulates channel data that is relevant for YouTube Partners linked with the channel. Defaults to: `null`.
- conversionPings (ChannelConversionPings): The conversionPings object encapsulates information about conversion pings that need to be respected by the channel. Defaults to: `null`.
- etag (String.t): Etag of this resource. Defaults to: `null`.
- id (String.t): The ID that YouTube uses to uniquely identify the channel. Defaults to: `null`.
- invideoPromotion (InvideoPromotion): The invideoPromotion object encapsulates information about promotion campaign associated with the channel. Defaults to: `null`.
- kind (String.t): Identifies what kind of resource this is. Value: the fixed string \"youtube#channel\". Defaults to: `null`.
- localizations (%{optional(String.t) => ChannelLocalization}): Localizations for different languages Defaults to: `null`.
- snippet (ChannelSnippet): The snippet object contains basic details about the channel, such as its title, description, and thumbnail images. Defaults to: `null`.
- statistics (ChannelStatistics): The statistics object encapsulates statistics for the channel. Defaults to: `null`.
- status (ChannelStatus): The status object encapsulates information about the privacy status of the channel. Defaults to: `null`.
- topicDetails (ChannelTopicDetails): The topicDetails object encapsulates information about Freebase topics associated with the channel. Defaults to: `null`.
"""
defstruct [
:auditDetails,
:brandingSettings,
:contentDetails,
:contentOwnerDetails,
:conversionPings,
:etag,
:id,
:invideoPromotion,
:kind,
:localizations,
:snippet,
:statistics,
:status,
:topicDetails
]
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.Channel do
import GoogleApi.YouTube.V3.Deserializer
def decode(value, options) do
value
|> deserialize(
:auditDetails,
:struct,
GoogleApi.YouTube.V3.Model.ChannelAuditDetails,
options
)
|> deserialize(
:brandingSettings,
:struct,
GoogleApi.YouTube.V3.Model.ChannelBrandingSettings,
options
)
|> deserialize(
:contentDetails,
:struct,
GoogleApi.YouTube.V3.Model.ChannelContentDetails,
options
)
|> deserialize(
:contentOwnerDetails,
:struct,
GoogleApi.YouTube.V3.Model.ChannelContentOwnerDetails,
options
)
|> deserialize(
:conversionPings,
:struct,
GoogleApi.YouTube.V3.Model.ChannelConversionPings,
options
)
|> deserialize(
:invideoPromotion,
:struct,
GoogleApi.YouTube.V3.Model.InvideoPromotion,
options
)
|> deserialize(:localizations, :map, GoogleApi.YouTube.V3.Model.ChannelLocalization, options)
|> deserialize(:snippet, :struct, GoogleApi.YouTube.V3.Model.ChannelSnippet, options)
|> deserialize(:statistics, :struct, GoogleApi.YouTube.V3.Model.ChannelStatistics, options)
|> deserialize(:status, :struct, GoogleApi.YouTube.V3.Model.ChannelStatus, options)
|> deserialize(
:topicDetails,
:struct,
GoogleApi.YouTube.V3.Model.ChannelTopicDetails,
options
)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.Channel do
def encode(value, options) do
GoogleApi.YouTube.V3.Deserializer.serialize_non_nil(value, options)
end
end
| 41.508475 | 194 | 0.737444 |
0325a5159c1d5edf43abd71b3752aca7e22c2b52 | 67 | ex | Elixir | lib/phoenix_cms_web/views/page_view.ex | SerenityIK/phoenix_cms | 2e6f5068c5d3bf0a1372f6da4f910522f7faa6a4 | [
"Apache-2.0"
] | null | null | null | lib/phoenix_cms_web/views/page_view.ex | SerenityIK/phoenix_cms | 2e6f5068c5d3bf0a1372f6da4f910522f7faa6a4 | [
"Apache-2.0"
] | 17 | 2021-03-22T06:11:32.000Z | 2022-03-28T20:03:58.000Z | lib/phoenix_cms_web/views/page_view.ex | SerenityIK/phoenix_cms | 2e6f5068c5d3bf0a1372f6da4f910522f7faa6a4 | [
"Apache-2.0"
] | null | null | null | defmodule PhoenixCmsWeb.PageView do
use PhoenixCmsWeb, :view
end
| 16.75 | 35 | 0.820896 |
0325c421a23cda9883f2c89e74ac0e7ef0a04c6b | 1,263 | exs | Elixir | mix.exs | hauleth/mix_unused | 778f60773a1c0d10e62b85c5fd39611b71b41e53 | [
"MIT"
] | 116 | 2019-01-05T02:08:47.000Z | 2022-03-29T08:10:16.000Z | mix.exs | hauleth/mix_unused | 778f60773a1c0d10e62b85c5fd39611b71b41e53 | [
"MIT"
] | 22 | 2020-04-12T23:29:14.000Z | 2022-03-30T17:23:21.000Z | mix.exs | hauleth/mix_unused | 778f60773a1c0d10e62b85c5fd39611b71b41e53 | [
"MIT"
] | 2 | 2021-09-28T10:35:00.000Z | 2022-03-24T14:08:27.000Z | defmodule MixUnused.MixProject do
use Mix.Project
@source_url "https://github.com/hauleth/mix_unused"
@version "0.3.0"
def project do
[
app: :mix_unused,
description: "Mix compiler tracer for detecting unused public functions",
version: @version,
elixir: "~> 1.10",
package: [
licenses: ~w[MIT],
links: %{
"Changelog" => "https://hexdocs.pm/mix_unused/changelog.html",
"GitHub" => @source_url
}
],
deps: [
{:credo, ">= 0.0.0", only: :dev, runtime: false},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false},
{:dialyxir, "~> 1.0", only: :dev, runtime: false},
{:covertool, "~> 2.0", only: :test}
],
docs: [
extras: [
"CHANGELOG.md": [],
LICENSE: [title: "License"],
"README.md": [title: "Overview"]
],
# main: "Mix.Tasks.Compile.Unused",
main: "readme",
source_url: @source_url,
source_url: "v#{@version}",
formatters: ["html"]
],
test_coverage: [tool: :covertool]
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:mix, :logger]
]
end
end
| 25.77551 | 79 | 0.527316 |
03265d8b5016a1ac901272f8b6ce90e33e30b5b0 | 565 | ex | Elixir | test/test_bot/middleware/message_transformer.ex | bot-ex/bot_ex | 7f28464723187ef415b5e6926e4c48e2ace50fad | [
"MIT"
] | 20 | 2020-04-10T11:25:47.000Z | 2021-11-08T08:03:22.000Z | test/test_bot/middleware/message_transformer.ex | bot-ex/botex | 7f28464723187ef415b5e6926e4c48e2ace50fad | [
"MIT"
] | 1 | 2020-07-21T08:01:50.000Z | 2020-07-22T17:53:00.000Z | test/test_bot/middleware/message_transformer.ex | bot-ex/botex | 7f28464723187ef415b5e6926e4c48e2ace50fad | [
"MIT"
] | 2 | 2020-04-11T11:12:03.000Z | 2020-07-21T07:37:55.000Z | defmodule TestBot.Middleware.MessaegTransformer do
@moduledoc """
Convert telegram message to `BotEx.Models.Message`
"""
@behaviour BotEx.Behaviours.MiddlewareParser
alias BotEx.Models.Message
@spec transform({binary(), binary(), binary(), map()}) ::
Message.t()
def transform({command, action, text, _user, _pid} = msg) do
%Message{
msg: msg,
text: text,
date_time: Timex.local(),
module: command,
action: action,
data: nil,
from: :test_bot,
is_cmd: not is_nil(command)
}
end
end
| 23.541667 | 62 | 0.631858 |
03268f59bd2199286c1eaa3d98c9c5980e3f77cf | 871 | exs | Elixir | test/web/controller/admin/quest_controller_test.exs | stevegrossi/ex_venture | e02d5a63fdb882d92cfb4af3e15f7b48ad7054aa | [
"MIT"
] | 2 | 2019-05-14T11:36:44.000Z | 2020-07-01T08:54:04.000Z | test/web/controller/admin/quest_controller_test.exs | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | null | null | null | test/web/controller/admin/quest_controller_test.exs | nickwalton/ex_venture | d8ff1b0181db03f9ddcb7610ae7ab533feecbfbb | [
"MIT"
] | 1 | 2021-01-29T14:12:40.000Z | 2021-01-29T14:12:40.000Z | defmodule Web.Admin.QuestControllerTest do
use Web.AuthConnCase
test "create a quest", %{conn: conn} do
npc = create_npc(%{is_quest_giver: true})
params = %{
"name" => "Quest",
"description" => "A quest",
"completed_message" => "The quest is done",
"script" => [
%{"key" => "start", "message" => "Hi", "trigger" => "quest"},
] |> Poison.encode!(),
"level" => 1,
"experience" => 100,
"giver_id" => npc.id,
}
conn = post conn, quest_path(conn, :create), quest: params
assert html_response(conn, 302)
end
test "update a quest", %{conn: conn} do
npc = create_npc(%{is_quest_giver: true})
quest = create_quest(npc, %{name: "Finding a Guard"})
conn = put conn, quest_path(conn, :update, quest.id), quest: %{name: "Kill a Bandit"}
assert html_response(conn, 302)
end
end
| 28.096774 | 89 | 0.586682 |
03269343a076587f8cda31611e498f331315abb0 | 1,475 | ex | Elixir | lib/bloggex_web/views/error_helpers.ex | dreamingechoes/bloggex | 9ead10ec1fd8fda0da3cb08106c43a9043188199 | [
"MIT"
] | 1 | 2020-01-14T03:17:51.000Z | 2020-01-14T03:17:51.000Z | lib/bloggex_web/views/error_helpers.ex | dreamingechoes/bloggex | 9ead10ec1fd8fda0da3cb08106c43a9043188199 | [
"MIT"
] | null | null | null | lib/bloggex_web/views/error_helpers.ex | dreamingechoes/bloggex | 9ead10ec1fd8fda0da3cb08106c43a9043188199 | [
"MIT"
] | null | null | null | defmodule BloggexWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error), class: "help-block")
end)
end
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext "errors", "is invalid"
#
# # Translate the number of files with plural rules
# dngettext "errors", "1 file", "%{count} files", count
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(BloggexWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(BloggexWeb.Gettext, "errors", msg, opts)
end
end
end
| 32.777778 | 76 | 0.671186 |
0326ad2b0225330d6452949dac126997a93eeb60 | 46 | exs | Elixir | test/solana_test.exs | dcrck/solana-elixir | 3ab8531129d303b3951a292ce2813ebcb9ab2cb3 | [
"MIT"
] | 15 | 2021-11-16T23:56:03.000Z | 2022-02-19T08:48:30.000Z | test/solana_test.exs | dcrck/solana-elixir | 3ab8531129d303b3951a292ce2813ebcb9ab2cb3 | [
"MIT"
] | null | null | null | test/solana_test.exs | dcrck/solana-elixir | 3ab8531129d303b3951a292ce2813ebcb9ab2cb3 | [
"MIT"
] | 1 | 2021-11-29T06:33:51.000Z | 2021-11-29T06:33:51.000Z | defmodule SolanaTest do
use ExUnit.Case
end
| 11.5 | 23 | 0.804348 |
0326f69e5da55a61933558c0954ec569c088bf5b | 832 | ex | Elixir | lib/kaffy/cache/client.ex | adipurnama/kaffy | d940958b8730648b060dff8a89232dff082a090e | [
"MIT"
] | 840 | 2020-05-08T20:24:01.000Z | 2022-03-18T07:03:49.000Z | lib/kaffy/cache/client.ex | adipurnama/kaffy | d940958b8730648b060dff8a89232dff082a090e | [
"MIT"
] | 189 | 2020-05-07T04:58:35.000Z | 2022-02-09T16:33:36.000Z | lib/kaffy/cache/client.ex | adipurnama/kaffy | d940958b8730648b060dff8a89232dff082a090e | [
"MIT"
] | 103 | 2020-05-09T12:42:22.000Z | 2022-03-30T04:10:22.000Z | defmodule Kaffy.Cache.Client do
use GenServer
def start_link(args) do
GenServer.start_link(__MODULE__, args, name: KaffyCache)
end
@impl true
def init(_) do
Kaffy.Cache.Table.create_table()
{:ok, %{}}
end
def add_cache(key, suffix, value, expire_after \\ 600) do
GenServer.call(KaffyCache, {:add, key, suffix, value, expire_after})
end
def get_cache(key, suffix) do
GenServer.call(KaffyCache, {:get, key, suffix})
end
@impl true
def handle_call({:add, key, suffix, value, expire_after}, _from, state) do
result = Kaffy.Cache.Table.add_to_cache(key, suffix, value, expire_after)
{:reply, result, state}
end
@impl true
def handle_call({:get, key, suffix}, _from, state) do
result = Kaffy.Cache.Table.get_from_cache(key, suffix)
{:reply, result, state}
end
end
| 24.470588 | 77 | 0.685096 |
03270fca3708998b872b67757d6ecdd5d7aca22f | 253 | ex | Elixir | test/support/cms/V3/Database/mock_version_table.ex | noizu-labs/KitchenSinkAdvanced | 6d91b5dd4f59cd9838f87a64605a0ef87f4301c8 | [
"MIT"
] | null | null | null | test/support/cms/V3/Database/mock_version_table.ex | noizu-labs/KitchenSinkAdvanced | 6d91b5dd4f59cd9838f87a64605a0ef87f4301c8 | [
"MIT"
] | null | null | null | test/support/cms/V3/Database/mock_version_table.ex | noizu-labs/KitchenSinkAdvanced | 6d91b5dd4f59cd9838f87a64605a0ef87f4301c8 | [
"MIT"
] | null | null | null | defmodule Noizu.Support.V3.CMS.Database.Article.Version.MockTable do
@moduledoc false
require Noizu.Testing.Mnesia.TableMocker
Noizu.Testing.Mnesia.TableMocker.customize() do
@table Noizu.V3.CMS.Database.Article.Version.Table
end
end
| 31.625 | 69 | 0.778656 |
03273b0c5c2311f83c719bce0bb8bea282b655e3 | 428 | ex | Elixir | lib/conduit_web/controllers/fallback_controller.ex | ray-sh/cov_detect | b4e74b13850eff4a7c646a64fc7c28fbe700ad2e | [
"MIT"
] | 298 | 2017-06-05T14:28:23.000Z | 2022-03-30T16:53:44.000Z | lib/conduit_web/controllers/fallback_controller.ex | ray-sh/cov_detect | b4e74b13850eff4a7c646a64fc7c28fbe700ad2e | [
"MIT"
] | 28 | 2017-07-21T01:06:47.000Z | 2021-03-07T12:32:56.000Z | lib/conduit_web/controllers/fallback_controller.ex | ray-sh/cov_detect | b4e74b13850eff4a7c646a64fc7c28fbe700ad2e | [
"MIT"
] | 77 | 2017-08-14T20:12:03.000Z | 2021-12-08T22:24:59.000Z | defmodule ConduitWeb.FallbackController do
use ConduitWeb, :controller
def call(conn, {:error, :validation_failure, errors}) do
conn
|> put_status(:unprocessable_entity)
|> put_view(ConduitWeb.ValidationView)
|> render("error.json", errors: errors)
end
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(ConduitWeb.ErrorView)
|> render(:"404")
end
end
| 23.777778 | 58 | 0.682243 |
03274dead7db75a78460e6c09366e92443c74cbb | 652 | exs | Elixir | test/dotfiler/print_test.exs | filipebarros/dotfiler | 6d0984371c6b0bc91902c65b7b10691579d7d414 | [
"MIT"
] | null | null | null | test/dotfiler/print_test.exs | filipebarros/dotfiler | 6d0984371c6b0bc91902c65b7b10691579d7d414 | [
"MIT"
] | null | null | null | test/dotfiler/print_test.exs | filipebarros/dotfiler | 6d0984371c6b0bc91902c65b7b10691579d7d414 | [
"MIT"
] | null | null | null | defmodule Dotfiler.PrintTest do
use ExUnit.Case
alias Dotfiler.Print
import ExUnit.CaptureIO
test "prints help menu" do
help_message = """
Usage:
./dotfiler --source [folder] [options]
Options:
--help Show this help message.
--brew Install Homebrew
--packages Install Homebrew packages (Brewfile)
Description:
Installs dotfiles
"""
print = fn ->
Print.help
end
assert capture_io(print) == help_message
end
test "prints version" do
print = fn ->
Print.version
end
assert capture_io(print) == "#{Dotfiler.Mixfile.project[:version]}\n"
end
end
| 17.157895 | 73 | 0.631902 |
0327528c1286e824e32841c612d6c00c460c4118 | 198 | exs | Elixir | priv/repo/migrations/20190808002434_change_reward_amount_type.exs | pakorn186c/blockchain-api | 3c9fbc892e645f9bb144414f3da36749603f37bc | [
"Apache-2.0"
] | 17 | 2019-11-03T03:02:41.000Z | 2022-01-13T17:03:32.000Z | priv/repo/migrations/20190808002434_change_reward_amount_type.exs | AddressXception/blockchain-api | eea98fa78af2887cc84762f84532c602c3b8b666 | [
"Apache-2.0"
] | 5 | 2019-11-07T23:26:53.000Z | 2020-11-24T21:45:35.000Z | priv/repo/migrations/20190808002434_change_reward_amount_type.exs | AddressXception/blockchain-api | eea98fa78af2887cc84762f84532c602c3b8b666 | [
"Apache-2.0"
] | 11 | 2019-12-04T07:03:16.000Z | 2022-01-13T17:03:50.000Z | defmodule BlockchainAPI.Repo.Migrations.ChangeRewardAmountType do
use Ecto.Migration
def change do
alter table(:reward_txns) do
modify :amount, :bigint, null: false
end
end
end
| 19.8 | 65 | 0.737374 |
03278e7884f5288a3dc4b2138a331c196ae85cb8 | 2,016 | ex | Elixir | lib/battle_box/api_key.ex | GrantJamesPowell/battle_box | 301091955b68cd4672f6513d645eca4e3c4e17d0 | [
"Apache-2.0"
] | 2 | 2020-10-17T05:48:49.000Z | 2020-11-11T02:34:15.000Z | lib/battle_box/api_key.ex | FlyingDutchmanGames/battle_box | 301091955b68cd4672f6513d645eca4e3c4e17d0 | [
"Apache-2.0"
] | 3 | 2020-05-18T05:52:21.000Z | 2020-06-09T07:24:14.000Z | lib/battle_box/api_key.ex | FlyingDutchmanGames/battle_box | 301091955b68cd4672f6513d645eca4e3c4e17d0 | [
"Apache-2.0"
] | null | null | null | defmodule BattleBox.ApiKey do
alias BattleBox.{Repo, User}
import BattleBox.Utilities.UserIdentifierValidation, only: [validate_user_identifer: 2]
import Ecto.Changeset
use Ecto.Schema
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
@derive {Inspect, except: [:hashed_token]}
schema "api_keys" do
field :name, :binary
field :token, :string, virtual: true
field :hashed_token, :binary
field :last_used, :naive_datetime
belongs_to :user, User
timestamps()
end
def changeset(api_key, params \\ %{}) do
token = gen_token()
api_key
|> cast(params, [:name])
|> validate_user_identifer(:name)
|> put_change(:token, token)
|> put_change(:hashed_token, hash(token))
end
@spec authenticate(String.t()) ::
{:ok, %User{}} | {:error, %{token: [String.t()]}} | {:error, %{user: [String.t()]}}
def authenticate(token) do
Repo.get_by(__MODULE__, hashed_token: hash(token))
|> Repo.preload(:user)
|> case do
nil ->
{:error, %{token: ["Invalid API Key"]}}
%__MODULE__{user: %User{is_banned: true}} ->
{:error, %{user: ["User is banned"]}}
%__MODULE__{user: %User{} = user} = key ->
mark_used!(key)
{:ok, user}
end
end
@spec gen_token() :: String.t()
def gen_token do
:crypto.strong_rand_bytes(16)
|> Base.encode32(padding: false, case: :lower)
end
defp mark_used!(%__MODULE__{} = api_key) do
api_key
|> change(last_used: now())
|> Repo.update()
end
defp hash(token) do
# Normally when you hash passwords you want to use a much stronger/slower
# hash function like argon2. Since API keys are 128 bits of strong random
# bytes and not a short user generated phrase, we're safe to use a much faster
# hash function. There's a 0% chance of brute forcing 128 random bits
:crypto.hash(:sha256, token)
end
def now do
NaiveDateTime.utc_now() |> NaiveDateTime.truncate(:second)
end
end
| 28 | 93 | 0.645337 |
0327d7f433490a1ed089b2ba43d595eb5fb019ec | 1,586 | ex | Elixir | test/support/data_case.ex | manojsamanta/stripe-multiple-products | 746895c2a4ef375c74bf0a643cbd3db7a8e19bcc | [
"MIT"
] | null | null | null | test/support/data_case.ex | manojsamanta/stripe-multiple-products | 746895c2a4ef375c74bf0a643cbd3db7a8e19bcc | [
"MIT"
] | null | null | null | test/support/data_case.ex | manojsamanta/stripe-multiple-products | 746895c2a4ef375c74bf0a643cbd3db7a8e19bcc | [
"MIT"
] | null | null | null | defmodule MultipleProducts.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,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use MultipleProducts.DataCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
alias MultipleProducts.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import MultipleProducts.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(MultipleProducts.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(MultipleProducts.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transforms changeset errors into a map of messages.
assert {:error, 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
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Regex.replace(~r"%{(\w+)}", message, fn _, key ->
opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
end)
end)
end
end
| 28.321429 | 78 | 0.699243 |
03281252bc1d3bc4b6010a72476dbd683c6a3745 | 1,524 | ex | Elixir | clients/content/lib/google_api/content/v2/model/customer_return_reason.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/customer_return_reason.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/customer_return_reason.ex | kaaboaye/elixir-google-api | 1896784c4342151fd25becd089a5beb323eff567 | [
"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.Content.V2.Model.CustomerReturnReason do
@moduledoc """
## Attributes
* `description` (*type:* `String.t`, *default:* `nil`) - Description of the reason.
* `reasonCode` (*type:* `String.t`, *default:* `nil`) - Code of the return reason.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:description => String.t(),
:reasonCode => String.t()
}
field(:description)
field(:reasonCode)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.CustomerReturnReason do
def decode(value, options) do
GoogleApi.Content.V2.Model.CustomerReturnReason.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.CustomerReturnReason do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 30.48 | 87 | 0.723097 |
032819b294f0490e58836ab4e04210caf4fc8236 | 463 | exs | Elixir | enum/countdown.exs | diningyo/programming-elixir | bc61ee99a56e462129263c6b372eaf1faa9bb3fb | [
"MIT"
] | null | null | null | enum/countdown.exs | diningyo/programming-elixir | bc61ee99a56e462129263c6b372eaf1faa9bb3fb | [
"MIT"
] | null | null | null | enum/countdown.exs | diningyo/programming-elixir | bc61ee99a56e462129263c6b372eaf1faa9bb3fb | [
"MIT"
] | null | null | null | defmodule Countdown do
def sleep(seconds) do
receive do
after seconds * 1000 -> nil
end
end
def say(text) do
spawn fn -> :os.cmd('say #{text}') end
end
def timer do
Stream.resource(
fn ->
{_h, _m, s} = :erlang.time
60 - s - 1
end,
fn
0 ->
{:halt, 0}
count ->
sleep(1)
{[inspect(count)], count - 1 }
end,
fn _-> nil end
)
end
end
| 15.965517 | 42 | 0.455724 |
032823cab46a2374dc0f3adf29279f1cf7622324 | 261 | exs | Elixir | exercise/0203_PatternMaching3.exs | diningyo/programming-elixir | bc61ee99a56e462129263c6b372eaf1faa9bb3fb | [
"MIT"
] | null | null | null | exercise/0203_PatternMaching3.exs | diningyo/programming-elixir | bc61ee99a56e462129263c6b372eaf1faa9bb3fb | [
"MIT"
] | null | null | null | exercise/0203_PatternMaching3.exs | diningyo/programming-elixir | bc61ee99a56e462129263c6b372eaf1faa9bb3fb | [
"MIT"
] | null | null | null | # 2.4 p.020 - exercise PatternMatching-3
# rerequirements : a is bound by 2.
a = 2
[ a, b, a ] = [ 1, 2, 3 ] # no match
a = 2
[ a, b, a ] = [ 1, 1, 2 ] # no match
a = 2
a = 1 # match
a = 2
^a = 2 # match
a = 2
^a = 1 # no match
a = 2
^a = 2 - a # no match
| 13.05 | 40 | 0.482759 |
03282ae29f731103c6ef6caa0e3e69761fb19ca7 | 200 | ex | Elixir | lib/phone/il.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/il.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | lib/phone/il.ex | net/phone | 18e1356d2f8d32fe3f95638c3c44bceab0164fb2 | [
"Apache-2.0"
] | null | null | null | defmodule Phone.IL do
@moduledoc false
use Helper.Country
def regex, do: ~r/^(972)()(.{8,9})/
def country, do: "Israel"
def a2, do: "IL"
def a3, do: "ISR"
matcher :regex, ["972"]
end
| 15.384615 | 37 | 0.595 |
0328301df2c0903f2f05227aa1e23a24740703e9 | 618 | ex | Elixir | lib/api/workshops/attendance.ex | nunopolonia/psc-api | 2e358503851cc04cdaa89201a3f56586f8746736 | [
"MIT"
] | 1 | 2017-09-10T23:51:40.000Z | 2017-09-10T23:51:40.000Z | lib/api/workshops/attendance.ex | nunopolonia/psc-api | 2e358503851cc04cdaa89201a3f56586f8746736 | [
"MIT"
] | 24 | 2018-03-14T18:17:00.000Z | 2021-03-01T07:47:53.000Z | lib/api/workshops/attendance.ex | portosummerofcode/psc-api | 2e358503851cc04cdaa89201a3f56586f8746736 | [
"MIT"
] | null | null | null | defmodule Api.Workshops.Attendance do
use Ecto.Schema
import Ecto.Changeset
alias Api.Accounts.User
alias Api.Workshops.Workshop
@valid_attrs ~w(
user_id
workshop_id
checked_in
)a
@required_attrs ~w(
user_id
workshop_id
)a
@primary_key false
@foreign_key_type :binary_id
schema "users_workshops" do
field :checked_in, :boolean, default: false
belongs_to :user, User
belongs_to :workshop, Workshop
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, @valid_attrs)
|> validate_required(@required_attrs)
end
end
| 18.176471 | 47 | 0.695793 |
0328322acda1d3a9a477c6f30fc4e6e3d26f5275 | 1,757 | ex | Elixir | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_product_key_value.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_product_key_value.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p1beta1_product_key_value.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.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue do
@moduledoc """
A product label represented as a key-value pair.
## Attributes
* `key` (*type:* `String.t`, *default:* `nil`) - The key of the label attached to the product. Cannot be empty and cannot exceed 128 bytes.
* `value` (*type:* `String.t`, *default:* `nil`) - The value of the label attached to the product. Cannot be empty and cannot exceed 128 bytes.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:key => String.t() | nil,
:value => String.t() | nil
}
field(:key)
field(:value)
end
defimpl Poison.Decoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p1beta1ProductKeyValue do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.14 | 147 | 0.734775 |
03284a9174ce3efce0f72138ea9b7c2d4369671c | 1,197 | exs | Elixir | mix.exs | ljgago/minex | 5cdd56222a0648a855574764a47fa89b35eaf1f8 | [
"Apache-2.0"
] | null | null | null | mix.exs | ljgago/minex | 5cdd56222a0648a855574764a47fa89b35eaf1f8 | [
"Apache-2.0"
] | null | null | null | mix.exs | ljgago/minex | 5cdd56222a0648a855574764a47fa89b35eaf1f8 | [
"Apache-2.0"
] | null | null | null | defmodule Minex.MixProject do
use Mix.Project
@version "0.1.0"
@repo_url "https://github.com/ljgago/minex"
def project do
[
app: :minex,
version: @version,
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps(),
# Doc
name: "Minex",
# Pakcage
package: package(),
description: "Elixir MinIO client"
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
# extra_applications: [:logger], mod: {Minex, []}
mod: {Minex.Application, []},
extra_applications: [:logger, :crypto]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:finch, "~> 0.7"},
{:mint, "~> 1.3"},
{:castore, "~> 0.1"},
{:erlsom, "~> 1.5"},
{:credo, "~> 1.4", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0", only: [:dev], runtime: false},
{:benchee, "~> 1.0", only: :dev},
{:bypass, "~> 2.0", only: :test}
# {:observer_cli, "~> 1.5"},
#{:tesla, "~> 1.3"},
]
end
defp package do
[
licenses: ["MIT"],
links: %{"GitHub" => @repo_url}
]
end
end
| 21.375 | 62 | 0.507937 |
03286f4206ed438533638d0e0425c4aa0b08b15c | 5,689 | ex | Elixir | lib/mix/lib/mix/tasks/escriptize.ex | knewter/elixir | 8310d62499e292d78d5c9d79d5d15a64e32fb738 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/escriptize.ex | knewter/elixir | 8310d62499e292d78d5c9d79d5d15a64e32fb738 | [
"Apache-2.0"
] | null | null | null | lib/mix/lib/mix/tasks/escriptize.ex | knewter/elixir | 8310d62499e292d78d5c9d79d5d15a64e32fb738 | [
"Apache-2.0"
] | null | null | null | defmodule Mix.Tasks.Escriptize do
use Mix.Task
use Bitwise, only_operators: true
@shortdoc "Generates an escript for the project"
@recursive true
@moduledoc %S"""
Generates an escript for the project.
## Command line options
* `--force` - forces compilation regardless of modification times
* `--no-compile` - skips compilation to .beam files
## Configuration
The following options can be specified in your `mix.exs` file:
* `escript_name` - the name of the generated escript.
Defaults to app name
* `escript_path` - the path to write the escript to.
Defaults to app name
* `escript_app` - the app to start with the escript.
Defaults to app name. Set it to `nil` if no application should
be started.
* `escript_main_module` - the module containing the `main/1` function.
Defaults to `Project`
* `escript_embed_elixir` - if `true` embed elixir in the escript file.
Defaults to `true`
* `escript_embed_extra_apps` - embed additional Elixir applications.
if `escript_embed_elixir` is `true`.
Defaults to `[]`
* `escript_shebang` - shebang interpreter directive used to execute the escript.
Defaults to "#! /usr/bin/env escript\n"
* `escript_comment` - comment line to follow shebang directive in the escript.
Defaults to "%%\n"
* `escript_emu_args` - emulator arguments to embed in the escript file.
Defaults to "%%!\n"
"""
def run(args) do
{ opts, _, _ } = OptionParser.parse(args, switches: [force: :boolean, no_compile: :boolean])
# Require the project to be available
Mix.Project.get!
unless opts[:no_compile] do
Mix.Task.run :compile, args
end
escriptize(Mix.project, opts[:force])
end
defp escriptize(project, force) do
script_name = project[:escript_name] || project[:app]
filename = project[:escript_path] || atom_to_binary(script_name)
embed = Keyword.get(project, :escript_embed_elixir, true)
app = Keyword.get(project, :escript_app, project[:app])
files = project_files()
cond do
!script_name ->
raise Mix.Error, message: "Could not generate escript, no name given, " <>
"set :escript_name or :app in the project settings"
force || Mix.Utils.stale?(files, [filename]) ->
tuples = gen_main(script_name, project[:escript_main_module], app) ++ to_tuples(files)
tuples = tuples ++ deps_tuples()
if embed do
extra_apps = project[:escript_embed_extra_apps] || []
tuples = Enum.reduce [:elixir|extra_apps], tuples, fn(app, acc) ->
app_tuples(app) ++ acc
end
end
# We might get duplicate tuples in umbrella projects from applications
# sharing the same dependencies
tuples = Enum.uniq(tuples, fn {name, _} -> name end)
case :zip.create 'mem', tuples, [:memory] do
{ :ok, { 'mem', zip } } ->
shebang = project[:escript_shebang] || "#! /usr/bin/env escript\n"
comment = project[:escript_comment] || "%%\n"
emu_args = project[:escript_emu_args] || "%%!\n"
script = iolist_to_binary([shebang, comment, emu_args, zip])
File.mkdir_p!(Path.dirname(filename))
File.write!(filename, script)
{:error, error} ->
Mix.shell.error "Error creating escript: #{error}"
end
set_perms(filename)
Mix.shell.info "Generated escript #{filename}"
:ok
true ->
:noop
end
end
defp project_files do
get_files(Mix.Project.app_path)
end
defp deps_tuples do
Enum.reduce Mix.Deps.loaded || [], [], fn(dep, acc) ->
get_tuples(dep.opts[:build]) ++ acc
end
end
defp set_perms(filename) do
stat = File.stat!(filename)
:ok = :file.change_mode(filename, stat.mode ||| 73)
end
defp app_tuples(app) do
case :code.where_is_file('#{app}.app') do
:non_existing -> raise Mix.Error, message: "Could not find application #{app}"
file -> get_tuples(Path.dirname(Path.dirname(file)))
end
end
defp get_files(app) do
Path.wildcard("#{app}/ebin/*.{app,beam}") ++
(Path.wildcard("#{app}/priv/**/*") |> Enum.filter(&File.regular?/1))
end
defp get_tuples(app) do
get_files(app) |> to_tuples
end
defp to_tuples(files) do
lc f inlist files do
{ String.to_char_list!(Path.basename(f)), File.read!(f) }
end
end
defp gen_main(script_name, nil, app) do
camelized = Mix.Utils.camelize(atom_to_binary(script_name))
gen_main(script_name, Module.concat([camelized]), app)
end
defp gen_main(script_name, script_name, _app) do
[]
end
defp gen_main(name, module, app) do
{ :module, ^name, binary, _ } =
defmodule name do
@module module
@app app
def main(args) do
case :application.start(:elixir) do
:ok ->
start_app
args = Enum.map(args, &String.from_char_list!(&1))
Kernel.CLI.run fn -> @module.main(args) end, true
_ ->
IO.puts :stderr, IO.ANSI.escape("%{red, bright} Elixir is not in the code path, aborting.")
System.halt(1)
end
end
defp start_app do
if app = @app do
case Application.Behaviour.start(app) do
:ok -> :ok
{ :error, reason } ->
IO.puts :stderr, IO.ANSI.escape("%{red, bright} Could not start application #{app}: #{inspect reason}.")
System.halt(1)
end
end
end
end
[{ '#{name}.beam', binary }]
end
end
| 29.78534 | 120 | 0.610652 |
0328771b65ea354ef522d8ef5636d7e084ddccbd | 2,888 | exs | Elixir | test/telemetry_metrics_statsd/formatter/datadog_test.exs | samullen/telemetry_metrics_statsd | 969e6d8ce7d146216b96be1187e08ac33aedd4e2 | [
"MIT"
] | null | null | null | test/telemetry_metrics_statsd/formatter/datadog_test.exs | samullen/telemetry_metrics_statsd | 969e6d8ce7d146216b96be1187e08ac33aedd4e2 | [
"MIT"
] | null | null | null | test/telemetry_metrics_statsd/formatter/datadog_test.exs | samullen/telemetry_metrics_statsd | 969e6d8ce7d146216b96be1187e08ac33aedd4e2 | [
"MIT"
] | null | null | null | defmodule TelemetryMetricsStatsd.Formatter.DatadogTest do
use ExUnit.Case, async: true
import TelemetryMetricsStatsd.Test.Helpers
alias TelemetryMetricsStatsd.Formatter.Datadog
test "counter update is formatted as a Datadog counter with 1 as a value" do
m = given_counter("my.awesome.metric")
assert format(m, 30, []) == "my.awesome.metric:1|c"
end
test "positive sum update is formatted as a Datadog gauge with +n value" do
m = given_sum("my.awesome.metric")
assert format(m, 21, []) == "my.awesome.metric:+21|g"
end
test "negative sum update is formatted as a Datadog gauge with -n value" do
m = given_sum("my.awesome.metric")
assert format(m, -21, []) == "my.awesome.metric:-21|g"
end
test "last_value update is formatted as a Datadog gauge with absolute value" do
m = given_last_value("my.awesome.metric")
assert format(m, -18, []) == "my.awesome.metric:-18|g"
end
test "summary update is formatted as a Datadog timer" do
m = given_summary("my.awesome.metric")
assert format(m, 121, []) == "my.awesome.metric:121|ms"
end
test "distribution update is formatted as a Datadog histogram" do
m = given_distribution("my.awesome.metric", buckets: {0..300, 100})
assert format(m, 131, []) == "my.awesome.metric:131|h"
end
test "StatsD metric name is based on metric name and tags" do
m = given_last_value("my.awesome.metric", tags: [:method, :status])
assert format(m, 131, method: "GET", status: 200) ==
"my.awesome.metric:131|g|#method:GET,status:200"
end
test "nil tags are included in the formatted metric" do
m = given_last_value("my.awesome.metric", tags: [:method, :status])
assert format(m, 131, method: nil, status: 200) ==
"my.awesome.metric:131|g|#method:nil,status:200"
end
test "tags passed as explicit argument are used for the formatted metric" do
m = given_last_value("my.awesome.metric", tags: [:whatever])
assert format(m, 131, method: "GET", status: 200) ==
"my.awesome.metric:131|g|#method:GET,status:200"
end
test "float measurements are allowed" do
m = given_last_value("my.awesome.metric")
assert format(m, 131.4, []) ==
"my.awesome.metric:131.4|g"
assert format(m, 131.5, []) ==
"my.awesome.metric:131.5|g"
end
test "sampling rate is added to third field" do
m = given_last_value("my.awesome.metric", reporter_options: [sampling_rate: 0.2])
assert format(m, 131.4, []) == "my.awesome.metric:131.4|g|@0.2"
end
test "sampling rate is ignored if == 1.0" do
m = given_last_value("my.awesome.metric", reporter_options: [sampling_rate: 1.0])
assert format(m, 131.4, []) == "my.awesome.metric:131.4|g"
end
defp format(metric, value, tags) do
Datadog.format(metric, value, tags)
|> :erlang.iolist_to_binary()
end
end
| 31.391304 | 85 | 0.666205 |
03289439beda7eee4e213c85a0a620ff3426ec4f | 1,799 | ex | Elixir | clients/mirror/lib/google_api/mirror/v1/model/subscriptions_list_response.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/mirror/lib/google_api/mirror/v1/model/subscriptions_list_response.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/mirror/lib/google_api/mirror/v1/model/subscriptions_list_response.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.Mirror.V1.Model.SubscriptionsListResponse do
@moduledoc """
A list of Subscriptions. This is the response from the server to GET requests on the subscription collection.
## Attributes
- items ([Subscription]): The list of subscriptions. Defaults to: `null`.
- kind (String.t): The type of resource. This is always mirror#subscriptionsList. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:items => list(GoogleApi.Mirror.V1.Model.Subscription.t()),
:kind => any()
}
field(:items, as: GoogleApi.Mirror.V1.Model.Subscription, type: :list)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.Mirror.V1.Model.SubscriptionsListResponse do
def decode(value, options) do
GoogleApi.Mirror.V1.Model.SubscriptionsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Mirror.V1.Model.SubscriptionsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.27451 | 111 | 0.744302 |
0328993040201df56325990ff52b1ab471048291 | 1,813 | ex | Elixir | lib/elixir_blog/posts/posts.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | lib/elixir_blog/posts/posts.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | lib/elixir_blog/posts/posts.ex | xorvo/elixir_blog | 67123c05eb4cacfa482604ce62c4f5a7e9bc1690 | [
"MIT"
] | null | null | null | defmodule ElixirBlog.Posts do
@moduledoc """
The Posts context.
"""
import Ecto.Query, warn: false
alias ElixirBlog.Repo
alias ElixirBlog.Posts.Article
@doc """
Returns the list of articles.
## Examples
iex> list_articles()
[%Article{}, ...]
"""
def list_articles do
Repo.all(Article)
end
@doc """
Gets a single article.
Raises `Ecto.NoResultsError` if the Article does not exist.
## Examples
iex> get_article!(123)
%Article{}
iex> get_article!(456)
** (Ecto.NoResultsError)
"""
def get_article!(id), do: Repo.get!(Article, id)
@doc """
Creates a article.
## Examples
iex> create_article(%{field: value})
{:ok, %Article{}}
iex> create_article(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_article(attrs \\ %{}) do
%Article{}
|> Article.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a article.
## Examples
iex> update_article(article, %{field: new_value})
{:ok, %Article{}}
iex> update_article(article, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_article(%Article{} = article, attrs) do
article
|> Article.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Article.
## Examples
iex> delete_article(article)
{:ok, %Article{}}
iex> delete_article(article)
{:error, %Ecto.Changeset{}}
"""
def delete_article(%Article{} = article) do
Repo.delete(article)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking article changes.
## Examples
iex> change_article(article)
%Ecto.Changeset{source: %Article{}}
"""
def change_article(%Article{} = article) do
Article.changeset(article, %{})
end
end
| 17.266667 | 62 | 0.601765 |
0328ae33889659e08cdc65d8a9f2398388b903ec | 771 | ex | Elixir | apps/meeple/lib/meeple/application.ex | grrrisu/meeple | 428762a58a94306a6643b09c08d72fb2883a0309 | [
"MIT"
] | null | null | null | apps/meeple/lib/meeple/application.ex | grrrisu/meeple | 428762a58a94306a6643b09c08d72fb2883a0309 | [
"MIT"
] | 13 | 2021-12-24T23:44:10.000Z | 2022-03-04T20:56:28.000Z | apps/meeple/lib/meeple/application.ex | grrrisu/meeple | 428762a58a94306a6643b09c08d72fb2883a0309 | [
"MIT"
] | null | null | null | defmodule Meeple.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
@impl true
def start(_type, _args) do
children = [
Meeple.Repo,
{Phoenix.PubSub, name: Meeple.PubSub},
Meeple.BoardSupervisor,
{
Sim.Realm.Supervisor,
name: MeepleRealm,
domain_services: [
{Meeple.Service.Admin, partition: :admin, max_demand: 1},
{Meeple.Service.User, partition: :user, max_demand: 1},
{Meeple.Service.Sim, partition: :sim, max_demand: 1}
],
reducers: [Meeple.PubSubReducer]
}
]
Supervisor.start_link(children, strategy: :one_for_one, name: Meeple.Supervisor)
end
end
| 26.586207 | 84 | 0.64332 |
0328c315abfb85cdad76506f30cde3626ed5a493 | 1,888 | exs | Elixir | clients/memcache/mix.exs | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/memcache/mix.exs | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/memcache/mix.exs | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Memcache.Mixfile do
use Mix.Project
@version "0.4.0"
def project() do
[
app: :google_api_memcache,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/memcache"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.2"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Cloud Memorystore for Memcached API client library. Google Cloud Memorystore for Memcached API is used for creating and managing Memcached instances in GCP.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/memcache",
"Homepage" => "https://cloud.google.com/memorystore/"
}
]
end
end
| 28.179104 | 160 | 0.660487 |
0328ffa88aaec9af95eb1589e03f42559d04ee64 | 3,930 | ex | Elixir | lib/fdb/native.ex | ananthakumaran/fdb | 5fd4ffff505d38fa843b7ef2e38e25fb932db125 | [
"MIT"
] | 40 | 2018-06-12T17:38:51.000Z | 2022-03-31T05:16:14.000Z | lib/fdb/native.ex | ananthakumaran/fdb | 5fd4ffff505d38fa843b7ef2e38e25fb932db125 | [
"MIT"
] | 15 | 2018-06-19T00:56:37.000Z | 2022-01-30T04:33:25.000Z | lib/fdb/native.ex | ananthakumaran/fdb | 5fd4ffff505d38fa843b7ef2e38e25fb932db125 | [
"MIT"
] | 6 | 2018-08-23T19:30:50.000Z | 2021-11-06T14:44:32.000Z | defmodule FDB.Native do
@moduledoc false
@on_load {:init, 0}
@compile {:autoload, false}
@app Mix.Project.config()[:app]
def init do
path = :filename.join(:code.priv_dir(@app), 'fdb_nif')
:ok = :erlang.load_nif(path, 0)
end
def get_max_api_version, do: :erlang.nif_error(:nif_library_not_loaded)
def select_api_version_impl(_runtime_version, _header_version),
do: :erlang.nif_error(:nif_library_not_loaded)
def network_set_option(_option), do: :erlang.nif_error(:nif_library_not_loaded)
def network_set_option(_option, _value), do: :erlang.nif_error(:nif_library_not_loaded)
def setup_network, do: :erlang.nif_error(:nif_library_not_loaded)
def run_network, do: :erlang.nif_error(:nif_library_not_loaded)
def stop_network, do: :erlang.nif_error(:nif_library_not_loaded)
def create_database(_file_path), do: :erlang.nif_error(:nif_library_not_loaded)
def database_set_option(_database, _option), do: :erlang.nif_error(:nif_library_not_loaded)
def database_set_option(_database, _option, _value),
do: :erlang.nif_error(:nif_library_not_loaded)
def database_create_transaction(_database), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_set_option(_transaction, _option),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_set_option(_transaction, _option, _value),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get(_transaction, _key, _snapshot),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_read_version(_transaction), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_approximate_size(_transaction), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_committed_version(_transaction),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_versionstamp(_transaction), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_watch(_transaction, _key), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_key(_transaction, _key, _or_equal, _offset, _snapshot),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_addresses_for_key(_transaction, _key),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_get_range(
_transaction,
_begin_key,
_begin_or_equal,
_begin_offset,
_end_key,
_end_or_equal,
_end_offset,
_limit,
_target_bytes,
_mode,
_iteration,
_snapshot,
_reverse
),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_set(_transaction, _key, _value), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_set_read_version(_transaction, _version),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_add_conflict_range(_transaction, _begin_key, _end_key, _conflict_range_type),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_atomic_op(_transaction, _key, _param, _operation_type),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_clear(_transaction, _key), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_clear_range(_transaction, _begin_key, _end_key),
do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_commit(_transaction), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_cancel(_transaction), do: :erlang.nif_error(:nif_library_not_loaded)
def transaction_on_error(_transaction, _error_code),
do: :erlang.nif_error(:nif_library_not_loaded)
def get_error(_code), do: :erlang.nif_error(:nif_library_not_loaded)
def get_error_predicate(_predicate_test, _code), do: :erlang.nif_error(:nif_library_not_loaded)
def future_resolve(_future, _reference), do: :erlang.nif_error(:nif_library_not_loaded)
def future_is_ready(_future), do: :erlang.nif_error(:nif_library_not_loaded)
end
| 39.3 | 100 | 0.774809 |
03290b171d3e32982152d93ac4aee705c9fd8660 | 5,116 | exs | Elixir | test/oli/interop/ingest_test.exs | ChristianMurphy/oli-torus | ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97 | [
"MIT"
] | null | null | null | test/oli/interop/ingest_test.exs | ChristianMurphy/oli-torus | ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97 | [
"MIT"
] | null | null | null | test/oli/interop/ingest_test.exs | ChristianMurphy/oli-torus | ffeee4996b66b7c6c6eb3e0082d030b8cc6cea97 | [
"MIT"
] | null | null | null | defmodule Oli.Interop.IngestTest do
alias Oli.Interop.Ingest
alias Oli.Interop.Export
alias Oli.Publishing.AuthoringResolver
alias Oli.Resources.Revision
alias Oli.Repo
use Oli.DataCase
def by_title(project, title) do
query =
from r in Revision,
where: r.title == ^title,
limit: 1
AuthoringResolver.from_revision_slug(project.slug, Repo.one(query).slug)
end
def unzip_to_memory(data) do
File.write("export.zip", data)
result = :zip.unzip(to_charlist("export.zip"), [:memory])
File.rm!("export.zip")
case result do
{:ok, entries} -> entries
_ -> []
end
end
def verify_export(entries) do
assert length(entries) == 9
m = Enum.reduce(entries, %{}, fn {f, c}, m -> Map.put(m, f, c) end)
assert Map.has_key?(m, '_hierarchy.json')
assert Map.has_key?(m, '_media-manifest.json')
assert Map.has_key?(m, '_project.json')
hierarchy =
Map.get(m, '_hierarchy.json')
|> Jason.decode!()
assert length(Map.get(hierarchy, "children")) == 1
unit = Map.get(hierarchy, "children") |> hd
assert Map.get(unit, "title") == "Analog and Digital Unit"
end
# This mimics the result of unzipping a digest file, but instead reads the individual
# files from disk (which makes updating and evolving this unit test easier). To mimic
# the zip read result, we have to read all the JSON files in and present them as a
# list of tuples where the first tuple item is a charlist representation of the file name
# (just the file name, not the full path) and the second tuple item is the contents of
# the file.
def simulate_unzipping() do
Path.wildcard("./test/oli/interop/digest/*.json")
|> Enum.map(fn f ->
{String.split(f, "/") |> Enum.reverse() |> hd |> String.to_charlist(), File.read(f)}
end)
|> Enum.map(fn {f, {:ok, contents}} -> {f, contents} end)
end
describe "course project ingest" do
setup do
Oli.Seeder.base_project_with_resource2()
end
test "ingest/1 and then export/1 works end to end", %{author: author} do
{:ok, project} =
simulate_unzipping()
|> Ingest.process(author)
Export.export(project)
|> unzip_to_memory()
|> verify_export()
end
test "ingest/1 processes the digest files and creates a course", %{author: author} do
{:ok, p} =
simulate_unzipping()
|> Ingest.process(author)
# verify project
project = Repo.get(Oli.Authoring.Course.Project, p.id)
assert project.title == "KTH CS101"
assert p.title == project.title
# verify project access for author
access =
Repo.get_by(Oli.Authoring.Authors.AuthorProject,
author_id: author.id,
project_id: project.id
)
refute is_nil(access)
# verify correct number of hierarchy elements were created
containers = Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "container")
# 4 defined in the course, plus 1 for the root
assert length(containers) == 4 + 1
# verify correct number of practice pages were created
practice_pages =
Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "page")
|> Enum.filter(fn p -> !p.graded end)
assert length(practice_pages) == 3
# verify that every practice page has a content attribute with a model
assert Enum.all?(practice_pages, fn p -> Map.has_key?(p.content, "model") end)
# verify that the page that had a link to another page had that link rewired correctly
src = Enum.filter(practice_pages, fn p -> p.title == "Analog and Digital Page" end) |> hd
dest =
Enum.filter(practice_pages, fn p -> p.title == "Contents: Analog and Digital Page" end)
|> hd
link =
Enum.at(src.content["model"], 0)
|> Map.get("children")
|> Enum.at(1)
|> Map.get("children")
|> Enum.at(5)
assert link["href"] == "/course/link/#{dest.slug}"
# spot check some elements to ensure that they were correctly constructed:
# check an internal hierarchy node, one that contains references to only
# other hierarchy nodes
c = by_title(project, "Analog and Digital Unit")
assert length(c.children) == 3
children = AuthoringResolver.from_resource_id(project.slug, c.children)
assert Enum.at(children, 0).title == "Contents: Analog and Digital"
assert Enum.at(children, 1).title == "Analog and Digital"
assert Enum.at(children, 2).title == "Analog and Digital Quiz"
# check a leaf hierarchy node, one that contains only page references
c = by_title(project, "Analog and Digital")
assert length(c.children) == 1
children = AuthoringResolver.from_resource_id(project.slug, c.children)
assert Enum.at(children, 0).title == "Analog and Digital Page"
# verify that all the activities were created correctly
activities = Oli.Publishing.get_unpublished_revisions_by_type(project.slug, "activity")
assert length(activities) == 3
end
end
end
| 34.33557 | 95 | 0.654222 |
03290dd3359b50d10c5f5f9255002eba5e0cda38 | 1,522 | exs | Elixir | asset_builder/asset_builder.exs | jhunschejones/asset_builder | 9abcee4a3d503f1fe4ff8d8adb447885ff49cda8 | [
"MIT"
] | null | null | null | asset_builder/asset_builder.exs | jhunschejones/asset_builder | 9abcee4a3d503f1fe4ff8d8adb447885ff49cda8 | [
"MIT"
] | 1 | 2022-02-10T18:56:31.000Z | 2022-02-10T18:56:31.000Z | asset_builder/asset_builder.exs | jhunschejones/asset_builder | 9abcee4a3d503f1fe4ff8d8adb447885ff49cda8 | [
"MIT"
] | null | null | null | defmodule AssetBuilder do
def compile(file), do: compile(file, file_extension(file))
def compile(file, "scss") do
System.cmd("npm", ["run", "--silent", "compile-scss"],
env: [{"FROM", file}, {"TO", "../../priv/static/css/#{file_name(file)}.min.css"}])
IO.puts("\e[36mCompiled '#{String.replace(file, "../../", "")}' to 'priv/static/css/#{file_name(file)}.min.css'\e[0m")
end
def compile(file, "css") do
System.cmd("npm", ["run", "--silent", "minify-css"],
env: [{"FROM", file}, {"TO", "../../priv/static/css/#{file_name(file)}.min.css"}])
IO.puts("\e[36mCompiled '#{String.replace(file, "../../", "")}' to 'priv/static/css/#{file_name(file)}.min.css'\e[0m")
end
def compile(file, "js") do
System.cmd("npm", ["run", "--silent", "minify-js"],
env: [{"FROM", file}, {"TO", "../../priv/static/js/#{file_name(file)}.min.js"}])
IO.puts("\e[36mCompiled '#{String.replace(file, "../../", "")}' to 'priv/static/js/#{file_name(file)}.min.js'\e[0m")
end
def compile(file, _) do
IO.puts("\e[33m'#{file}' is an incompatible file format for asset builder\e[0m")
end
def compilable_file?(file) do
Enum.member?(["js", "css", "scss", "cs"], file_extension(file))
&& !Enum.member?(["site", "phoenix_html"], file_name(file))
end
defp file_name(file) do
file
|> String.split("/")
|> List.last()
|> String.split(".")
|> List.first()
end
defp file_extension(file) do
file
|> String.split(".")
|> List.last()
end
end
| 31.708333 | 122 | 0.573587 |
032955918a7c0acbe8460424b9bda11381c67de6 | 1,800 | exs | Elixir | test/geohash_test.exs | elbow-jason/elixir-geohash | 0db29a76a2403fddb85cacd44374aebdcd2f2e61 | [
"Apache-2.0"
] | null | null | null | test/geohash_test.exs | elbow-jason/elixir-geohash | 0db29a76a2403fddb85cacd44374aebdcd2f2e61 | [
"Apache-2.0"
] | null | null | null | test/geohash_test.exs | elbow-jason/elixir-geohash | 0db29a76a2403fddb85cacd44374aebdcd2f2e61 | [
"Apache-2.0"
] | null | null | null | defmodule GeohashTest do
use ExUnit.Case
doctest Geohash
test "Geohash.encode" do
assert Geohash.encode(57.64911, 10.40744) == "u4pruydqqvj"
assert Geohash.encode(50.958087, 6.9204459) == "u1hcvkxk65f"
assert Geohash.encode(39.51, -76.24, 10) == "dr1bc0edrj"
assert Geohash.encode(42.6, -5.6, 5) == "ezs42"
assert Geohash.encode(0, 0) == "s0000000000"
assert Geohash.encode(0, 0, 2) == "s0"
assert Geohash.encode(57.648, 10.410, 6) == "u4pruy"
assert Geohash.encode(-25.38262, -49.26561, 8) == "6gkzwgjz"
end
test "Geohash.decode_to_bits" do
assert Geohash.decode_to_bits("ezs42") == <<0b0110111111110000010000010::25>>
end
test "Geohash.decode" do
assert Geohash.decode("ww8p1r4t8") == {37.832386, 112.558386}
assert Geohash.decode("ezs42") == {42.605, -5.603}
assert Geohash.decode("u4pruy") == {57.648, 10.410}
assert Geohash.decode('6gkzwgjz') == {-25.38262, -49.26561}
end
test "Geohash.encode matches elasticsearch geohash example" do
assert Geohash.encode(51.501568, -0.141257, 1) == "g"
assert Geohash.encode(51.501568, -0.141257, 2) == "gc"
assert Geohash.encode(51.501568, -0.141257, 3) == "gcp"
assert Geohash.encode(51.501568, -0.141257, 4) == "gcpu"
assert Geohash.encode(51.501568, -0.141257, 5) == "gcpuu"
assert Geohash.encode(51.501568, -0.141257, 6) == "gcpuuz"
assert Geohash.encode(51.501568, -0.141257, 7) == "gcpuuz9"
assert Geohash.encode(51.501568, -0.141257, 8) == "gcpuuz94"
assert Geohash.encode(51.501568, -0.141257, 9) == "gcpuuz94k"
assert Geohash.encode(51.501568, -0.141257, 10) == "gcpuuz94kk"
assert Geohash.encode(51.501568, -0.141257, 11) == "gcpuuz94kkp"
assert Geohash.encode(51.501568, -0.141257, 12) == "gcpuuz94kkp5"
end
end
| 41.860465 | 81 | 0.661667 |
032968cf19397ff9ab91f7ebec812fb74c07eea1 | 4,527 | ex | Elixir | lib/teslamate/locations/geocoder.ex | tuxbox/teslamate | feda761e39a98eaf943773a3f52c1a892302481f | [
"MIT"
] | 1 | 2021-05-04T18:06:35.000Z | 2021-05-04T18:06:35.000Z | lib/teslamate/locations/geocoder.ex | tuxbox/teslamate | feda761e39a98eaf943773a3f52c1a892302481f | [
"MIT"
] | 171 | 2020-07-08T18:42:57.000Z | 2022-03-23T00:55:30.000Z | lib/teslamate/locations/geocoder.ex | virtualm2000/teslamate | b2dad66d992b8e04d8213f2657492fa75872ece5 | [
"MIT"
] | null | null | null | defmodule TeslaMate.Locations.Geocoder do
use Tesla, only: [:get]
@version Mix.Project.config()[:version]
adapter Tesla.Adapter.Finch, name: TeslaMate.HTTP, receive_timeout: 30_000
plug Tesla.Middleware.BaseUrl, "https://nominatim.openstreetmap.org"
plug Tesla.Middleware.Headers, [{"user-agent", "TeslaMate/#{@version}"}]
plug Tesla.Middleware.JSON
plug Tesla.Middleware.Logger, debug: true, log_level: &log_level/1
alias TeslaMate.Locations.Address
def reverse_lookup(lat, lon, lang \\ "en") do
opts = [
format: :jsonv2,
addressdetails: 1,
extratags: 1,
namedetails: 1,
zoom: 19,
lat: lat,
lon: lon
]
with {:ok, address_raw} <- query("/reverse", lang, opts),
{:ok, address} <- into_address(address_raw) do
{:ok, address}
end
end
def details(addresses, lang) when is_list(addresses) do
osm_ids =
addresses
|> Enum.reject(fn %Address{} = a -> a.osm_id == nil or a.osm_type in [nil, "unknown"] end)
|> Enum.map(fn %Address{} = a -> "#{String.upcase(String.at(a.osm_type, 0))}#{a.osm_id}" end)
|> Enum.join(",")
params = [
osm_ids: osm_ids,
format: :jsonv2,
addressdetails: 1,
extratags: 1,
namedetails: 1,
zoom: 19
]
with {:ok, raw_addresses} <- query("/lookup", lang, params) do
addresses =
Enum.map(raw_addresses, fn attrs ->
case into_address(attrs) do
{:ok, address} -> address
{:error, reason} -> throw({:invalid_address, reason})
end
end)
{:ok, addresses}
end
catch
{:invalid_address, reason} ->
{:error, reason}
end
defp query(url, lang, params) do
case get(url, query: params, headers: [{"Accept-Language", lang}]) do
{:ok, %Tesla.Env{status: 200, body: body}} -> {:ok, body}
{:ok, %Tesla.Env{body: %{"error" => reason}}} -> {:error, reason}
{:ok, %Tesla.Env{} = env} -> {:error, reason: "Unexpected response", env: env}
{:error, reason} -> {:error, reason}
end
end
# Address Formatting
# Source: https://github.com/OpenCageData/address-formatting/blob/master/conf/components.yaml
@road_aliases [
"road",
"footway",
"street",
"street_name",
"residential",
"path",
"pedestrian",
"road_reference",
"road_reference_intl",
"square",
"place"
]
@neighbourhood_aliases [
"neighbourhood",
"suburb",
"city_district",
"district",
"quarter",
"residential",
"commercial",
"houses",
"subdivision"
]
@city_aliases [
"city",
"town",
"municipality",
"village",
"hamlet",
"locality",
"croft"
]
@county_aliases [
"county",
"local_administrative_area",
"county_code"
]
defp into_address(%{"error" => "Unable to geocode"} = raw) do
unknown_address = %{
display_name: "Unknown",
osm_type: "unknown",
osm_id: 0,
latitude: 0.0,
longitude: 0.0,
raw: raw
}
{:ok, unknown_address}
end
defp into_address(%{"error" => reason}) do
{:error, {:geocoding_failed, reason}}
end
defp into_address(raw) do
address = %{
display_name: Map.get(raw, "display_name"),
osm_id: Map.get(raw, "osm_id"),
osm_type: Map.get(raw, "osm_type"),
latitude: Map.get(raw, "lat"),
longitude: Map.get(raw, "lon"),
name:
Map.get(raw, "name") || get_in(raw, ["namedetails", "name"]) ||
get_in(raw, ["namedetails", "alt_name"]),
house_number: raw["address"] |> get_first(["house_number", "street_number"]),
road: raw["address"] |> get_first(@road_aliases),
neighbourhood: raw["address"] |> get_first(@neighbourhood_aliases),
city: raw["address"] |> get_first(@city_aliases),
county: raw["address"] |> get_first(@county_aliases),
postcode: get_in(raw, ["address", "postcode"]),
state: raw["address"] |> get_first(["state", "province", "state_code"]),
state_district: get_in(raw, ["address", "state_district"]),
country: raw["address"] |> get_first(["country", "country_name"]),
raw: raw
}
{:ok, address}
end
defp get_first(nil, _aliases), do: nil
defp get_first(_address, []), do: nil
defp get_first(address, [key | aliases]) do
with nil <- Map.get(address, key), do: get_first(address, aliases)
end
defp log_level(%Tesla.Env{} = env) when env.status >= 400, do: :warn
defp log_level(%Tesla.Env{}), do: :info
end
| 26.629412 | 99 | 0.595096 |
03296d87d7979d9ca074c8daaacebe55a916d366 | 752 | ex | Elixir | test/support/rem/test/application.ex | pyzlnar/rem-bot | 100b71949026eb191c1ebf80d64270406f237958 | [
"MIT"
] | 4 | 2022-02-20T13:33:48.000Z | 2022-03-31T00:48:52.000Z | test/support/rem/test/application.ex | pyzlnar/rem-bot | 100b71949026eb191c1ebf80d64270406f237958 | [
"MIT"
] | 1 | 2022-02-22T05:42:05.000Z | 2022-02-22T05:42:05.000Z | test/support/rem/test/application.ex | pyzlnar/rem-bot | 100b71949026eb191c1ebf80d64270406f237958 | [
"MIT"
] | null | null | null | defmodule Rem.TestApplication do
@moduledoc """
This application is supposed to be a mirror of Rem.Application,
but starts dependencies only necessary for tests
"""
use Application
@impl true
def start(_type, _args) do
children = [
Rem.Repo,
{Registry, name: Rem.Session.Registry, keys: :unique},
{DynamicSupervisor, name: Rem.Session.DynamicSupervisor, strategy: :one_for_one},
# Not started since it depends on Nostrum which we have off for testing
# Rem.Consumer
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Rem.Supervisor]
Supervisor.start_link(children, opts)
end
end
| 30.08 | 87 | 0.68617 |
03297929a89bf90b268adb08e8f338dc10575338 | 715 | ex | Elixir | lib/spawn_api_web/gettext.ex | spawnfest/spawn_api | e99dbc20dfc5ff18747efc0c2dafbecdf577707c | [
"MIT"
] | 2 | 2018-12-19T16:12:41.000Z | 2020-01-20T17:37:15.000Z | lib/spawn_api_web/gettext.ex | spawnfest/spawn_api | e99dbc20dfc5ff18747efc0c2dafbecdf577707c | [
"MIT"
] | null | null | null | lib/spawn_api_web/gettext.ex | spawnfest/spawn_api | e99dbc20dfc5ff18747efc0c2dafbecdf577707c | [
"MIT"
] | null | null | null | defmodule SpawnApiWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import SpawnApiWeb.Gettext
# Simple translation
gettext("Here is the string to translate")
# Plural translation
ngettext("Here is the string to translate",
"Here are the strings to translate",
3)
# Domain-based translation
dgettext("errors", "Here is the error message to translate")
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :spawn_api
end
| 28.6 | 72 | 0.67972 |
03298ac8eec15cb0e3f8c2bf887cfa3723636786 | 93,427 | ex | Elixir | lib/elixir/lib/kernel.ex | garyf/elixir | 20fcde6ff392836dfd4cf449ee438a11b7f52813 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | garyf/elixir | 20fcde6ff392836dfd4cf449ee438a11b7f52813 | [
"Apache-2.0"
] | null | null | null | lib/elixir/lib/kernel.ex | garyf/elixir | 20fcde6ff392836dfd4cf449ee438a11b7f52813 | [
"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` reference in any way outside the binary, an
`ArgumentError` exception is raised.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> binary_part("foo", 1, 2)
"oo"
A negative `length` can be used to extract bytes that come *before* the byte
at `start`:
iex> binary_part("Hello", 5, -3)
"llo"
"""
@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 (by excess). This operation
happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> byte_size(<<433::16, 3::3>>)
3
iex> byte_size(<<1, 2, 3>>)
3
"""
@spec byte_size(binary) :: non_neg_integer
def byte_size(binary) do
:erlang.byte_size(binary)
end
@doc """
Performs an integer division.
Raises an `ArithmeticError` exception 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 `exit/1` explicitly if you
want to terminate a process but not signal any failure:
exit(:normal)
In case something goes wrong, you can also use `exit/1` with
a different reason:
exit(:seems_bad)
If the exit reason is not `:normal`, all the processes linked to the process
that exited will crash (unless they are trapping exits).
## OTP exits
Exits are used by the OTP to determine if a process exited abnormally
or not. The following exits are considered "normal":
* `exit(:normal)`
* `exit(:shutdown)`
* `exit({:shutdown, term})`
Exiting with any other reason is considered abnormal and treated
as a crash. This means the default supervisor behaviour kicks in,
error reports are emitted, 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 `ArgumentError` if the list is empty.
Inlined by the compiler.
## Examples
iex> hd([1, 2, 3, 4])
1
"""
@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.
## Examples
iex> is_binary "foo"
true
iex> is_binary <<1::3>>
false
"""
@spec is_binary(term) :: boolean
def is_binary(term) do
:erlang.is_binary(term)
end
@doc """
Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> is_bitstring "foo"
true
iex> is_bitstring <<1::3>>
true
"""
@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.
## Examples
iex> is_function(fn(x) -> x * 2 end, 1)
true
iex> is_function(fn(x) -> x * 2 end, 2)
false
"""
@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.
The size of a map is the number of key-value pairs that the map contains.
This operation happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> map_size(%{a: "foo", b: "bar"})
2
"""
@spec map_size(map) :: non_neg_integer
def map_size(map) do
:erlang.map_size(map)
end
@doc """
Returns the biggest of the two given terms according to
Erlang's term ordering. If the terms compare equal, the
first one is returned.
Inlined by the compiler.
## Examples
iex> max(1, 2)
2
iex> max(:a, :b)
:b
"""
@spec max(term, term) :: term
def max(first, second) do
:erlang.max(first, second)
end
@doc """
Returns 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
iex> min("foo", "bar")
"bar"
"""
@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 """
Computes the remainder of an integer division.
Raises an `ArithmeticError` exception 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 """
Rounds a number to the nearest integer.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> round(5.6)
6
iex> round(5.2)
5
iex> round(-9.9)
-10
"""
@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 `Process` and `Node` modules for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
current = self()
child = spawn(fn -> send current, {self(), 1 + 2} end)
receive do
{^child, 3} -> IO.puts "Received 3 back"
end
"""
@spec spawn((() -> any)) :: pid
def spawn(fun) do
:erlang.spawn(fun)
end
@doc """
Spawns the given module and function passing the given args
and returns its pid.
Check the `Process` and `Node` modules 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 `Process` and `Node` modules for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
current = self()
child = spawn_link(fn -> send current, {self(), 1 + 2} end)
receive do
{^child, 3} -> IO.puts "Received 3 back"
end
"""
@spec spawn_link((() -> any)) :: pid
def spawn_link(fun) do
:erlang.spawn_link(fun)
end
@doc """
Spawns the given module and function passing the given args,
links it to the current process and returns its pid.
Check the `Process` and `Node` modules 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 `Process` and `Node` modules for other functions
to handle processes, including spawning functions in nodes.
Inlined by the compiler.
## Examples
current = self()
spawn_monitor(fn -> send current, {self(), 1 + 2} end)
"""
@spec spawn_monitor((() -> any)) :: {pid, reference}
def spawn_monitor(fun) do
:erlang.spawn_monitor(fun)
end
@doc """
Spawns the given module and function passing the given args,
monitors it and returns its pid and monitoring reference.
Check the `Process` and `Node` modules 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.
## Examples
iex> tl([1, 2, 3, :go])
[2, 3, :go]
"""
@spec tl(maybe_improper_list) :: maybe_improper_list
def tl(list) do
:erlang.tl(list)
end
@doc """
Returns the integer part of `number`.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> trunc(5.4)
5
iex> trunc(5.99)
5
"""
@spec trunc(number) :: integer
def trunc(number) do
:erlang.trunc(number)
end
@doc """
Returns the size of a tuple.
This operation happens in constant time.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> tuple_size {:a, :b, :c}
3
"""
@spec tuple_size(tuple) :: non_neg_integer
def tuple_size(tuple) do
:erlang.tuple_size(tuple)
end
@doc """
Arithmetic addition.
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 subtraction.
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/2` and `rem/2` if you want
an integer 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 list
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.
`arg` must be a boolean; if it's not, an `ArgumentError` exception is raised.
Allowed in guard tests. Inlined by the compiler.
## Examples
iex> not false
true
"""
@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 """
Gets the element at the zero-based `index` in `tuple`.
Allowed in guard tests. Inlined by the compiler.
## Examples
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 """
Inserts `value` at the given zero-based `index` in `tuple`.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar, 3}
iex> put_elem(tuple, 0, :baz)
{:baz, :bar, 3}
"""
@spec put_elem(tuple, non_neg_integer, term) :: tuple
def put_elem(tuple, index, value) do
:erlang.setelement(index + 1, tuple, value)
end
## Implemented in Elixir
@doc """
Boolean or.
If the first argument is `true`, `true` is returned; otherwise, the second
argument is returned.
Requires only the first argument to be a boolean since it short-circuits.
If the first argument is not a boolean, an `ArgumentError` exception is
raised.
Allowed in guard tests.
## Examples
iex> true or false
true
iex> false or 42
42
"""
defmacro left or right do
quote do: __op__(:orelse, unquote(left), unquote(right))
end
@doc """
Boolean and.
If the first argument is `false`, `false` is returned; otherwise, the second
argument is returned.
Requires only the first argument to be a boolean since it short-circuits. If
the first argument is not a boolean, an `ArgumentError` exception is raised.
Allowed in guard tests.
## Examples
iex> true and false
false
iex> true and "yay!"
"yay!"
"""
defmacro left and right do
quote do: __op__(:andalso, unquote(left), unquote(right))
end
@doc """
Boolean not.
Receives any argument (not just booleans) and returns `true` if the argument
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 pattern matching (and guard clauses) as
long as the first part is a literal binary:
iex> "foo" <> x = "foobar"
iex> x
"bar"
`x <> "bar" = "foobar"` would have resulted in a `CompileError` exception.
"""
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 `msg` is a binary, it raises a `RuntimeError` exception
using the given argument as message.
If `msg` is an atom, it just calls `raise/2` with the atom as the first
argument and `[]` as the second argument.
If `msg` is anything else, raises an `ArgumentError` exception.
## Examples
iex> raise "Oops"
** (RuntimeError) Oops
try do
1 + :foo
rescue
x in [ArithmeticError] ->
IO.puts "that was expected"
raise x
end
"""
defmacro raise(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
_ ->
:erlang.error ArgumentError.exception("raise/1 expects an alias or a string as the first argument")
end
end
end
end
@doc """
Raises an exception.
Calls the `exception/1` function on the given argument (which has to be a
module name like `ArgumentError` or `RuntimeError`) passing `attrs` as the
attributes in order to retrieve the exception struct.
Any module that contains a call to the `defexception/1` macro automatically
implements the `exception/1` callback expected by `raise/2`. See the docs for
`defexception/1` for more information.
## 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/0` 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/0` 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
_ ->
:erlang.error ArgumentError.exception("reraise/2 expects an alias or a string as the first argument")
end
end
end
end
@doc """
Raises an exception preserving a previous stacktrace.
`reraise/3` works like `reraise/2`, except it passes arguments to the
`exception/1` function like explained in `raise/2`.
## 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"""
Inspects the given argument according to the `Inspect` protocol.
The second argument is a keyword list with options to control
inspection.
## Options
`inspect/2` accepts a list of options that are internally
translated to an `Inspect.Opts` struct. Check the docs for
`Inspect.Opts` to see the supported options.
## Examples
iex> inspect(:foo)
":foo"
iex> inspect [1, 2, 3, 4, 5], limit: 3
"[1, 2, 3, ...]"
iex> inspect("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 pairs) during enumeration.
Keys in the Enumerable that don't exist in the struct are automatically
discarded.
This function is useful for dynamically creating and updating
structs.
## Examples
defmodule User do
defstruct name: "john"
end
struct(User)
#=> %User{name: "john"}
opts = [name: "meg"]
user = struct(User, opts)
#=> %User{name: "meg"}
struct(user, unknown: "value")
#=> %User{name: "meg"}
"""
@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 """
Converts the argument to a char 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`, `false` otherwise.
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
iex> map = %{a: 1, b: 2}
iex> match?(%{a: _}, map)
true
iex> a = 1
iex> match?(^a, 1)
true
`match?/2` is very useful when filtering of finding a value in an enumerable:
list = [{:a, 1}, {:b, 2}, {:a, 3}]
Enum.filter list, &match?({:a, _}, &1)
#=> [{:a, 1}, {:a, 3}]
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)
#=> [{:a, 1}]
However, variables assigned in the match will not be available
outside of the function call (unlike regular pattern matching with the `=`
operator):
iex> match?(x, 1)
true
iex> binding()
[]
"""
defmacro match?(pattern, expr)
# Special case where underscore, which always matches, is passed as the first
# argument.
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 """
Reads and writes 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 the module attributes supported by Erlang, but
custom attributes can be used as well:
defmodule MyServer do
@my_data 13
IO.inspect @my_data #=> 13
end
Unlike Erlang, such attributes are not stored in the module by default since
it is common in Elixir to use custom attributes to store temporary data that
will be available at compile-time. Custom attributes may be configured to
behave closer to Erlang by using `Module.register_attribute/3`.
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 not function? and __CALLER__.context == :match do
false -> nil
true ->
raise ArgumentError, "invalid write attribute syntax, you probably meant to use: @#{name} expression"
end
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.
In the returned result, keys are variable names and values are the
corresponding variable values.
If the given `context` is `nil` (by default it is), the binding for the
current context is returned.
## Examples
iex> x = 1
iex> binding()
[x: 1]
iex> x = 2
iex> binding()
[x: 2]
iex> binding(:foo)
[]
iex> var!(x, :foo) = 1
1
iex> binding(:foo)
[x: 1]
"""
defmacro binding(context \\ nil) do
in_match? = Macro.Env.in_match?(__CALLER__)
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 second
argument to be a keyword list.
## One-liner examples
if(foo, do: bar)
In the example above, `bar` will be returned if `foo` evaluates to
`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
It's also possible to pass a block to the `if` macro. The first
example above would be translated to:
if foo do
bar
end
Note that `do/end` become delimiters. The second example would
translate to:
if foo do
bar
else
baz
end
In order to compare more than two clauses, the `cond/1` macro has to be used.
"""
defmacro if(condition, clauses) do
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 """
Provides an `unless` macro.
This macro evaluates and returns the `do` block passed in as the second
argument unless `clause` evaluates to `true`. Otherwise, it returns the value
of the `else` block if present or `nil` if not.
See also `if/2`.
## Examples
iex> unless(Enum.empty?([]), do: "Hello")
nil
iex> unless(Enum.empty?([1, 2, 3]), do: "Hello")
"Hello"
iex> unless Enum.sum([2, 2]) == 5 do
...> "Math still works"
...> else
...> "Math is broken"
...> end
"Math still works"
"""
defmacro unless(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 """
Destructures two lists, assigning each term in the
right one to the matching term in the left one.
Unlike pattern matching via `=`, if the sizes of the left
and right lists don't match, destructuring simply stops
instead of raising an error.
## Examples
iex> destructure([x, y, z], [1, 2, 3, 4, 5])
iex> {x, y, z}
{1, 2, 3}
In the example above, even though the right list has more entries than the
left one, destructuring works fine. If the right list is smaller, the
remaining items are simply set to `nil`:
iex> destructure([x, y, z], [1])
iex> {x, y, z}
{1, nil, nil}
The left-hand side supports any expression you would use
on the left-hand side of a match:
x = 1
destructure([^x, y, z], [1, 2, 3])
The example above will only work if `x` matches the first value in the right
list. Otherwise, it will raise a `MatchError` (like the `=` operator would
do).
"""
defmacro destructure(left, right) when is_list(left) do
Enum.reduce left, right, fn item, acc ->
{:case, meta, args} =
quote do
case unquote(acc) do
[h|t] ->
unquote(item) = h
t
other when other == [] or other == nil ->
unquote(item) = nil
[]
end
end
{:case, meta, args}
end
end
@doc """
Returns a range with the specified start and end.
Both ends are included.
## 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.
Not allowed in guard clauses.
## Examples
iex> Enum.empty?([]) && Enum.empty?([])
true
iex> List.first([]) && true
nil
iex> Enum.empty?([]) && List.first([1])
1
iex> false && throw(:bad)
false
Note that, unlike Erlang's `and` operator,
this operator accepts any expression as the first argument,
not only booleans.
"""
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.
Not allowed in guard clauses.
## Examples
iex> Enum.empty?([1]) || Enum.empty?([1])
false
iex> List.first([]) || true
true
iex> Enum.empty?([1]) || 1
1
iex> Enum.empty?([]) || throw(:bad)
true
Note that, unlike Erlang's `or` operator,
this operator accepts any expression as the first argument,
not only booleans.
"""
defmacro left || right do
quote do
case unquote(left) do
x when x in [false, nil] ->
unquote(right)
x ->
x
end
end
end
@doc """
Pipe operator.
This operator introduces the expression on the left-hand side as
the first argument to the function call on the right-hand side.
## Examples
iex> [1, [2], 3] |> List.flatten()
[1, 2, 3]
The example above is the same as calling `List.flatten([1, [2], 3])`.
The `|>` operator is mostly useful when there is a desire to execute a series
of operations resembling a pipeline:
iex> [1, [2], 3] |> List.flatten |> Enum.map(fn x -> x * 2 end)
[2, 4, 6]
In the example above, the list `[1, [2], 3]` is passed as the first argument
to the `List.flatten/1` function, then the flattened list is passed as the
first argument to the `Enum.map/2` function which doubles each element of the
list.
In other words, the expression above simply translates to:
Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end)
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 results in an error as the `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 """
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 hygienized. 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`.
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
`__using__/1` is just a regular macro that can be defined in any module:
defmodule MyModule do
defmacro __using__(opts) do
quote do
# code that will run in the module that will `use MyModule`
end
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.230084 | 120 | 0.629069 |
0329974d2b9549abb3a2710d7938d09ce9c6cd4a | 236 | ex | Elixir | lib/matrix/structs/agent_type.ex | nemanja-m/matrix | 92298697827f30a2d6ba144004c1668fe70b760e | [
"MIT"
] | null | null | null | lib/matrix/structs/agent_type.ex | nemanja-m/matrix | 92298697827f30a2d6ba144004c1668fe70b760e | [
"MIT"
] | null | null | null | lib/matrix/structs/agent_type.ex | nemanja-m/matrix | 92298697827f30a2d6ba144004c1668fe70b760e | [
"MIT"
] | null | null | null | defmodule Matrix.AgentType do
@moduledoc """
Represents agent type struct with :name and :module fields.
"""
@derive [Poison.Encoder]
defstruct [:name, :module]
@type t :: %__MODULE__{name: String.t, module: String.t}
end
| 21.454545 | 61 | 0.690678 |
03299cfb17be90116171b25ac2e51d07c27c7a39 | 556 | exs | Elixir | priv/repo/migrations/20181006144906_create_cities.exs | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | priv/repo/migrations/20181006144906_create_cities.exs | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | priv/repo/migrations/20181006144906_create_cities.exs | TDogVoid/job_board | 23793917bd1cc4e68bccce737b971093030a31eb | [
"MIT"
] | null | null | null | defmodule JobBoard.Repo.Migrations.CreateCities do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS postgis"
create table(:cities) do
add :name, :string
add :zipcode, :integer
add :state_id, references(:states)
add :geom, :geometry
timestamps()
end
create index(:cities, [:name])
create index(:cities, [:zipcode])
create index(:cities, [:state_id])
alter table(:jobs) do
add :city_id, references(:cities)
end
create index(:jobs, [:city_id])
end
end
| 21.384615 | 52 | 0.645683 |
0329a0b38141c4c6efd42c672c261965e5181ec5 | 543 | ex | Elixir | api/lib/responda_me_web/views/error_view.ex | mendes13/responda.me | 42facc3de1c5cc503459457b2bb452f0ad6fac37 | [
"MIT"
] | null | null | null | api/lib/responda_me_web/views/error_view.ex | mendes13/responda.me | 42facc3de1c5cc503459457b2bb452f0ad6fac37 | [
"MIT"
] | null | null | null | api/lib/responda_me_web/views/error_view.ex | mendes13/responda.me | 42facc3de1c5cc503459457b2bb452f0ad6fac37 | [
"MIT"
] | null | null | null | defmodule Responda.MeWeb.ErrorView do
use Responda.MeWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def template_not_found(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
| 31.941176 | 83 | 0.720074 |
0329e909fb85404b57552f6c942cfee17ba43b92 | 1,149 | exs | Elixir | spec/assertions/enum/have_count_spec.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | spec/assertions/enum/have_count_spec.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | spec/assertions/enum/have_count_spec.exs | bblaszkow06/espec | 4d9819ca5c68c6eb70276c7d9c9630ded01ba778 | [
"Apache-2.0"
] | null | null | null | defmodule ESpec.Assertions.Enum.HaveCountSpec do
use ESpec, async: true
let :range, do: 1..3
context "Success" do
it "checks success with `to`" do
message = expect(range()).to(have_count(3))
expect(message) |> to(eq "`1..3` has `3` elements.")
end
it "checks success with `not_to`" do
message = expect(range()).to_not(have_count(2))
expect(message) |> to(eq "`1..3` doesn't have `2` elements.")
end
end
context "aliases" do
it do: expect(range()).to(have_size(3))
it do: expect(range()).to(have_length(3))
end
context "Error" do
context "with `to`" do
before do
{:shared,
expectation: fn -> expect(range()).to(have_count(2)) end,
message: "Expected `1..3` to have `2` elements but it has `3`."}
end
it_behaves_like(CheckErrorSharedSpec)
end
context "with `not_to`" do
before do
{:shared,
expectation: fn -> expect(range()).to_not(have_count(3)) end,
message: "Expected `1..3` not to have `3` elements but it has `3`."}
end
it_behaves_like(CheckErrorSharedSpec)
end
end
end
| 25.533333 | 77 | 0.600522 |
032a095c5610a9b16f88406e2ce437ccbf0d3e50 | 37,849 | ex | Elixir | lib/phoenix_live_view.ex | balexand/phoenix_live_view | 980e29d84be5bd009549b3be21eb307b9b891325 | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | balexand/phoenix_live_view | 980e29d84be5bd009549b3be21eb307b9b891325 | [
"MIT"
] | null | null | null | lib/phoenix_live_view.ex | balexand/phoenix_live_view | 980e29d84be5bd009549b3be21eb307b9b891325 | [
"MIT"
] | null | null | null | defmodule Phoenix.LiveView do
@moduledoc ~S'''
LiveView provides rich, real-time user experiences with
server-rendered HTML.
The LiveView programming model is declarative: instead of
saying "once event X happens, change Y on the page",
events in LiveView are regular messages which may cause
changes to its state. Once the state changes, LiveView will
re-render the relevant parts of its HTML template and push it
to the browser, which updates itself in the most efficient
manner. This means developers write LiveView templates as
any other server-rendered HTML and LiveView does the hard
work of tracking changes and sending the relevant diffs to
the browser.
At the end of the day, a LiveView is nothing more than a
process that receives events as messages and updates its
state. The state itself is nothing more than functional
and immutable Elixir data structures. The events are either
internal application messages (usually emitted by `Phoenix.PubSub`)
or sent by the client/browser.
LiveView is first rendered statically as part of regular
HTTP requests, which provides quick times for "First Meaningful
Paint", in addition to helping search and indexing engines.
Then a persistent connection is established between client and
server. This allows LiveView applications to react faster to user
events as there is less work to be done and less data to be sent
compared to stateless requests that have to authenticate, decode, load,
and encode data on every request. The flipside is that LiveView
uses more memory on the server compared to stateless requests.
## Use cases
There are many use cases where LiveView is an excellent
fit right now:
* Handling of user interaction and inputs, buttons, and
forms - such as input validation, dynamic forms,
autocomplete, etc;
* Events and updates pushed by server - such as
notifications, dashboards, etc;
* Page and data navigation - such as navigating between
pages, pagination, etc can be built with LiveView
using the excellent live navigation feature set.
This reduces the amount of data sent over the wire,
gives developers full control over the LiveView
life-cycle, while controlling how the browser
tracks those changes in state;
There are also use cases which are a bad fit for LiveView:
* Animations - animations, menus, and general events
that do not need the server in the first place are a
bad fit for LiveView, as they can be achieved purely
with CSS and/or CSS transitions;
## Life-cycle
A LiveView begins as a regular HTTP request and HTML response,
and then upgrades to a stateful view on client connect,
guaranteeing a regular HTML page even if JavaScript is disabled.
Any time a stateful view changes or updates its socket assigns, it is
automatically re-rendered and the updates are pushed to the client.
You begin by rendering a LiveView typically from your router.
When LiveView is first rendered, the `c:mount/3` callback is invoked
with the current params, the current session and the LiveView socket.
As in a regular request, `params` contains public data that can be
modified by the user. The `session` always contains private data set
by the application itself. The `c:mount/3` callback wires up socket
assigns necessary for rendering the view. After mounting, `c:render/1`
is invoked and the HTML is sent as a regular HTML response to the
client.
After rendering the static page, LiveView connects from the client
to the server where stateful views are spawned to push rendered updates
to the browser, and receive client events via `phx-` bindings. Just like
the first rendering, `c:mount/3` is invoked with params, session,
and socket state, where mount assigns values for rendering. However
in the connected client case, a LiveView process is spawned on
the server, pushes the result of `c:render/1` to the client and
continues on for the duration of the connection. If at any point
during the stateful life-cycle a crash is encountered, or the client
connection drops, the client gracefully reconnects to the server,
calling `c:mount/3` once again.
## Example
Before writing your first example, make sure that Phoenix LiveView
is properly installed. If you are just getting started, this can
be easily done by running `mix phx.new my_app --live`. The `phx.new`
command with the `--live` flag will create a new project with
LiveView installed and configured. Otherwise, please follow the steps
in the [installation guide](installation.md) before continuing.
A LiveView is a simple module that requires two callbacks: `c:mount/3`
and `c:render/1`:
defmodule MyAppWeb.ThermostatLive do
# If you generated an app with mix phx.new --live,
# the line below would be: use MyAppWeb, :live_view
use Phoenix.LiveView
def render(assigns) do
~L"""
Current temperature: <%= @temperature %>
"""
end
def mount(_params, %{"current_user_id" => user_id}, socket) do
temperature = Thermostat.get_user_reading(user_id)
{:ok, assign(socket, :temperature, temperature)}
end
end
The `c:render/1` callback receives the `socket.assigns` and is responsible
for returning rendered content. You can use `Phoenix.LiveView.Helpers.sigil_L/2`
to inline LiveView templates.
Next, decide where you want to use your LiveView.
You can serve the LiveView directly from your router (recommended):
defmodule MyAppWeb.Router do
use Phoenix.Router
import Phoenix.LiveView.Router
scope "/", MyAppWeb do
live "/thermostat", ThermostatLive
end
end
*Note:* the above assumes there is `plug :put_root_layout` call
in your router that configures the LiveView layout. This call is
automatically included by `mix phx.new --live` and described in
the installation guide. If you don't want to configure a root layout,
you must pass `layout: {MyAppWeb.LayoutView, "app.html"}` as an
option to the `live` macro above.
Alternatively, you can `live_render` from any template:
<h1>Temperature Control</h1>
<%= live_render(@conn, MyAppWeb.ThermostatLive) %>
Or you can `live_render` your view from any controller:
defmodule MyAppWeb.ThermostatController do
...
import Phoenix.LiveView.Controller
def show(conn, %{"id" => id}) do
live_render(conn, MyAppWeb.ThermostatLive)
end
end
When a LiveView is rendered, all of the data currently stored in the
connection session (see `Plug.Conn.get_session/1`) will be given to
the LiveView.
It is also possible to pass additional session information to the LiveView
through a session parameter:
# In the router
live "/thermostat", ThermostatLive, session: %{"extra_token" => "foo"}
# In a view
<%= live_render(@conn, MyAppWeb.ThermostatLive, session: %{"extra_token" => "foo"}) %>
Notice the `:session` uses string keys as a reminder that session data
is serialized and sent to the client. So you should always keep the data
in the session to a minimum. For example, instead of storing a User struct,
you should store the "user_id" and load the User when the LiveView mounts.
Once the LiveView is rendered, a regular HTML response is sent. In your
app.js file, you should find the following:
import {Socket} from "phoenix"
import LiveSocket from "phoenix_live_view"
let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {params: {_csrf_token: csrfToken}})
liveSocket.connect()
After the client connects, `c:mount/3` will be invoked inside a spawned
LiveView process. At this point, you can use `connected?/1` to
conditionally perform stateful work, such as subscribing to pubsub topics,
sending messages, etc. For example, you can periodically update a LiveView
with a timer:
defmodule DemoWeb.ThermostatLive do
use Phoenix.LiveView
...
def mount(_params, %{"current_user_id" => user_id}, socket) do
if connected?(socket), do: Process.send_after(self(), :update, 30000)
case Thermostat.get_user_reading(user_id) do
{:ok, temperature} ->
{:ok, assign(socket, temperature: temperature, user_id: user_id)}
{:error, _reason} ->
{:ok, redirect(socket, to: "/error")}
end
end
def handle_info(:update, socket) do
Process.send_after(self(), :update, 30000)
{:ok, temperature} = Thermostat.get_reading(socket.assigns.user_id)
{:noreply, assign(socket, :temperature, temperature)}
end
end
We used `connected?(socket)` on mount to send our view a message every 30s if
the socket is in a connected state. We receive the `:update` message in the
`handle_info/2` callback, just like in an Elixir `GenServer`, and update our
socket assigns. Whenever a socket's assigns change, `c:render/1` is automatically
invoked, and the updates are sent to the client.
## Colocating templates
In the examples above, we have placed the template directly inside the
LiveView:
defmodule MyAppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
~L"""
Current temperature: <%= @temperature %>
"""
end
For larger templates, you can place them in a file in the same directory
and same name as the LiveView. For example, if the file above is placed
at `lib/my_app_web/live/thermostat_live.ex`, you can also remove the
`c:render/1` definition above and instead put the template code at
`lib/my_app_web/live/thermostat_live.html.leex`.
Alternatively, you can keep the `c:render/1` callback but delegate to an
existing `Phoenix.View` module in your application. For example:
defmodule MyAppWeb.ThermostatLive do
use Phoenix.LiveView
def render(assigns) do
Phoenix.View.render(MyAppWeb.PageView, "page.html", assigns)
end
end
In all cases, each assign in the template will be accessible as `@assign`.
You can learn more about [assigns and LiveEEx templates in their own guide](assigns-eex.md).
## Bindings
Phoenix supports DOM element bindings for client-server interaction. For
example, to react to a click on a button, you would render the element:
<button phx-click="inc_temperature">+</button>
Then on the server, all LiveView bindings are handled with the `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
| Binding | Attributes |
|------------------------|------------|
| [Params](bindings.md#click-events) | `phx-value-*` |
| [Click Events](bindings.md#click-events) | `phx-click`, `phx-capture-click` |
| [Focus/Blur Events](bindings.md#focus-and-blur-events) | `phx-blur`, `phx-focus`, `phx-window-blur`, `phx-window-focus` |
| [Key Events](bindings.md#key-events) | `phx-keydown`, `phx-keyup`, `phx-window-keydown`, `phx-window-keyup` |
| [Form Events](form-bindings.md) | `phx-change`, `phx-submit`, `phx-feedback-for`, `phx-disable-with`, `phx-trigger-action`, `phx-auto-recover` |
| [Rate Limiting](bindings.md#rate-limiting-events-with-debounce-and-throttle) | `phx-debounce`, `phx-throttle` |
| [DOM Patching](dom-patching.md) | `phx-update` |
| [JS Interop](js-interop.md#client-hooks) | `phx-hook` |
## Compartmentalizing markup and events with `render`, `live_render`, and `live_component`
We can render another template directly from a LiveView template by simply
calling `render`:
render SomeView, "child_template.html", assigns
Where `SomeView` is a regular `Phoenix.View`, typically defined in
`lib/my_app_web/views/some_view.ex` and "child_template.html" is defined
at `lib/my_app_web/templates/some_view/child_template.html.leex`. As long
as the template has the `.leex` extension and all assigns are passed,
LiveView change tracking will also work across templates.
When rendering a child template, any of the `phx-*` events in the child
template will be sent to the LiveView. In other words, similar to regular
Phoenix templates, a regular `render` call does not start another LiveView.
This means `render` is useful for sharing markup between views.
If you want to start a separate LiveView from within a LiveView, then you
can call `live_render/3` instead of `render/3`. This child LiveView runs
in a separate process than the parent, with its own `mount` and `handle_event`
callbacks. If a child LiveView crashes, it won't affect the parent. If the
parent crashes, all children are terminated.
When rendering a child LiveView, the `:id` option is required to uniquely
identify the child. A child LiveView will only ever be rendered and mounted
a single time, provided its ID remains unchanged. Updates to a child session
will be merged on the client, but not passed back up until either a crash and
re-mount or a connection drop and recovery. To force a child to re-mount with
new session data, a new ID must be provided.
Given that a LiveView runs on its own process, it is an excellent tool for creating
completely isolated UI elements, but it is a slightly expensive abstraction if
all you want is to compartmentalize markup and events. For example, if you are
showing a table with all users in the system, and you want to compartmentalize
this logic, rendering a separate `LiveView` for each user, then using a process
per user would likely be too expensive. For these cases, LiveView provides
`Phoenix.LiveComponent`, which are rendered using `live_component/3`:
<%= live_component(@socket, UserComponent, id: user.id, user: user) %>
Components have their own `mount` and `handle_event` callbacks, as well as their
own state with change tracking support. Components are also lightweight as they
"run" in the same process as the parent `LiveView`. However, this means an error
in a component would cause the whole view to fail to render. See `Phoenix.LiveComponent`
for a complete rundown on components.
To sum it up:
* `render` - compartmentalizes markup
* `live_component` - compartmentalizes state, markup, and events
* `live_render` - compartmentalizes state, markup, events, and error isolation
## Endpoint configuration
LiveView accepts the following configuration in your endpoint under
the `:live_view` key:
* `:signing_salt` (required) - the salt used to sign data sent
to the client
* `:hibernate_after` (optional) - the idle time in milliseconds allowed in
the LiveView before compressing its own memory and state.
Defaults to 15000ms (15 seconds)
## Guides
LiveView has many guides to help you on your journey.
## Server-side
These guides focus on server-side functionality:
* [Assigns and LiveEEx](assigns-eex.md)
* [Error and exception handling](error-handling.md)
* [Live Layouts](live-layouts.md)
* [Live Navigation](live-navigation.md)
* [Security considerations of the LiveView model](security-model.md)
* [Telemetry](telemetry.md)
* [Using Gettext for internationalization](using-gettext.md)
## Client-side
These guides focus on LiveView bindings and client-side integration:
* [Bindings](bindings.md)
* [Form bindings](form-bindings.md)
* [DOM patching and temporary assigns](dom-patching.md)
* [JavaScript interoperability](js-interop.md)
'''
alias Phoenix.LiveView.Socket
@type unsigned_params :: map
@doc """
The LiveView entry-point.
For each LiveView in the root of a template, `c:mount/3` is invoked twice:
once to do the initial page load and again to establish the live socket.
It expects three parameters:
* `params` - a map of string keys which contain public information that
can be set by the user. The map contains the query params as well as any
router path parameter. If the LiveView was not mounted at the router,
this argument is the atom `:not_mounted_at_router`
* `session` - the connection session
* `socket` - the LiveView socket
It must return either `{:ok, socket}` or `{:ok, socket, options}`, where
`options` is one of:
* `:temporary_assigns` - a keyword list of assigns that are temporary
and must be reset to their value after every render
* `:layout` - the optional layout to be used by the LiveView
"""
@callback mount(
unsigned_params() | :not_mounted_at_router,
session :: map,
socket :: Socket.t()
) ::
{:ok, Socket.t()} | {:ok, Socket.t(), keyword()}
@callback render(assigns :: Socket.assigns()) :: Phoenix.LiveView.Rendered.t()
@callback terminate(reason, socket :: Socket.t()) :: term
when reason: :normal | :shutdown | {:shutdown, :left | :closed | term}
@callback handle_params(unsigned_params(), uri :: String.t(), socket :: Socket.t()) ::
{:noreply, Socket.t()}
@callback handle_event(event :: binary, unsigned_params(), socket :: Socket.t()) ::
{:noreply, Socket.t()} | {:reply, map, Socket.t()}
@callback handle_call(msg :: term, {pid, reference}, socket :: Socket.t()) ::
{:noreply, Socket.t()} | {:reply, term, Socket.t()}
@callback handle_info(msg :: term, socket :: Socket.t()) ::
{:noreply, Socket.t()}
@optional_callbacks mount: 3,
terminate: 2,
handle_params: 3,
handle_event: 3,
handle_call: 3,
handle_info: 2
@doc """
Uses LiveView in the current module to mark it a LiveView.
use Phoenix.LiveView,
namespace: MyAppWeb,
container: {:tr, class: "colorized"},
layout: {MyAppWeb.LayoutView, "live.html"}
## Options
* `:namespace` - configures the namespace the `LiveView` is in
* `:container` - configures the container the `LiveView` will be wrapped in
* `:layout` - configures the layout the `LiveView` will be rendered in
"""
defmacro __using__(opts) do
# Expand layout if possible to avoid compile-time dependencies
opts =
with true <- Keyword.keyword?(opts),
{layout, template} <- Keyword.get(opts, :layout) do
layout = Macro.expand(layout, %{__CALLER__ | function: {:__live__, 0}})
Keyword.replace!(opts, :layout, {layout, template})
else
_ -> opts
end
quote bind_quoted: [opts: opts] do
import Phoenix.LiveView
import Phoenix.LiveView.Helpers
@behaviour Phoenix.LiveView
require Phoenix.LiveView.Renderer
@before_compile Phoenix.LiveView.Renderer
@doc false
def __live__, do: unquote(Macro.escape(Phoenix.LiveView.__live__(__MODULE__, opts)))
end
end
@doc false
def __live__(module, opts) do
container = opts[:container] || {:div, []}
namespace = opts[:namespace] || module |> Module.split() |> Enum.take(1) |> Module.concat()
name = module |> Atom.to_string() |> String.replace_prefix("#{namespace}.", "")
layout =
case opts[:layout] do
{mod, template} when is_atom(mod) and is_binary(template) ->
{mod, template}
nil ->
nil
other ->
raise ArgumentError,
":layout expects a tuple of the form {MyLayoutView, \"my_template.html\"}, " <>
"got: #{inspect(other)}"
end
%{container: container, name: name, kind: :view, module: module, layout: layout}
end
@doc """
Returns true if the socket is connected.
Useful for checking the connectivity status when mounting the view.
For example, on initial page render, the view is mounted statically,
rendered, and the HTML is sent to the client. Once the client
connects to the server, a LiveView is then spawned and mounted
statefully within a process. Use `connected?/1` to conditionally
perform stateful work, such as subscribing to pubsub topics,
sending messages, etc.
## Examples
defmodule DemoWeb.ClockLive do
use Phoenix.LiveView
...
def mount(_params, _session, socket) do
if connected?(socket), do: :timer.send_interval(1000, self(), :tick)
{:ok, assign(socket, date: :calendar.local_time())}
end
def handle_info(:tick, socket) do
{:noreply, assign(socket, date: :calendar.local_time())}
end
end
"""
def connected?(%Socket{connected?: connected?}), do: connected?
@doc """
Assigns a value into the socket only if it does not exist.
Useful for lazily assigning values and referencing parent assigns.
## Referencing parent assigns
When a LiveView is mounted in a disconnected state, the Plug.Conn assigns
will be available for reference via `assign_new/3`, allowing assigns to
be shared for the initial HTTP request. On connected mount, `assign_new/3`
will be invoked, and the LiveView will use its session to rebuild the
originally shared assign. Likewise, nested LiveView children have access
to their parent's assigns on mount using `assign_new`, which allows
assigns to be shared down the nested LiveView tree.
## Examples
# controller
conn
|> assign(:current_user, user)
|> LiveView.Controller.live_render(MyLive, session: %{"user_id" => user.id})
# LiveView mount
def mount(_params, %{"user_id" => user_id}, socket) do
{:ok, assign_new(socket, :current_user, fn -> Accounts.get_user!(user_id) end)}
end
"""
def assign_new(%Socket{} = socket, key, func) when is_function(func, 0) do
validate_assign_key!(key)
case socket do
%{assigns: %{^key => _}} ->
socket
%{private: %{assign_new: {assigns, keys}}} ->
# It is important to store the keys even if they are not in assigns
# because maybe the controller doesn't have it but the view does.
socket = put_in(socket.private.assign_new, {assigns, [key | keys]})
Phoenix.LiveView.Utils.force_assign(socket, key, Map.get_lazy(assigns, key, func))
%{} ->
Phoenix.LiveView.Utils.force_assign(socket, key, func.())
end
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
validate_assign_key!(key)
Phoenix.LiveView.Utils.assign(socket, key, value)
end
@doc """
See `assign/3`.
"""
def assign(%Socket{} = socket, attrs) when is_map(attrs) or is_list(attrs) do
Enum.reduce(attrs, socket, fn {key, value}, acc ->
validate_assign_key!(key)
Phoenix.LiveView.Utils.assign(acc, key, value)
end)
end
defp validate_assign_key!(:flash) do
raise ArgumentError,
":flash is a reserved assign by LiveView and it cannot be set directly. " <>
"Use the appropriate flash functions instead."
end
defp validate_assign_key!(_key), do: :ok
@doc """
Updates an existing key 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*: While you can use `put_flash/3` inside a `Phoenix.LiveComponent`,
components have their own `@flash` assigns. The `@flash` assign
in a component is only copied to its parent LiveView if the component
calls `push_redirect/2` or `push_patch/2`.
*Note*: You must also place the `Phoenix.LiveView.Router.fetch_live_flash/2`
plug in your browser's pipeline in place of `fetch_flash` to be supported,
for example:
import Phoenix.LiveView.Router
pipeline :browser do
...
plug :fetch_live_flash
end
## Examples
iex> put_flash(socket, :info, "It worked!")
iex> put_flash(socket, :error, "You can't access that page")
"""
defdelegate put_flash(socket, kind, msg), to: Phoenix.LiveView.Utils
@doc """
Clears the flash.
## Examples
iex> clear_flash(socket)
"""
defdelegate clear_flash(socket), to: Phoenix.LiveView.Utils
@doc """
Clears a key from the flash.
## Examples
iex> clear_flash(socket, :info)
"""
defdelegate clear_flash(socket, key), to: Phoenix.LiveView.Utils
@doc """
Pushes an event to the client to be consumed by hooks.
*Note*: events will be dispatched to all active hooks on the client who are
handling the given `event`. Scoped events can be achieved by namespacing
your event names.
## Examples
{:noreply, push_event(socket, "scores", %{points: 100, user: "josé"})}
"""
defdelegate push_event(socket, event, payload), to: Phoenix.LiveView.Utils
@doc """
Annotates the socket for redirect to a destination path.
*Note*: LiveView redirects rely on instructing client
to perform a `window.location` update on the provided
redirect location. The whole page will be reloaded and
all state will be discarded.
## Options
* `:to` - the path to redirect to. It must always be a local path
* `:external` - an external path to redirect to
"""
def redirect(%Socket{} = socket, opts) do
url =
cond do
to = opts[:to] -> validate_local_url!(to, "redirect/2")
external = opts[:external] -> external
true -> raise ArgumentError, "expected :to or :external option in redirect/2"
end
put_redirect(socket, {:redirect, %{to: url}})
end
@doc """
Annotates the socket for navigation within the current LiveView.
When navigating to the current LiveView, `c:handle_params/3` is
immediately invoked to handle the change of params and URL state.
Then the new state is pushed to the client, without reloading the
whole page while also maintaining the current scroll position.
For live redirects to another LiveView, use `push_redirect/2`.
## Options
* `:to` - the required path to link to. It must always be a local path
* `:replace` - the flag to replace the current history or push a new state.
Defaults `false`.
## Examples
{:noreply, push_patch(socket, to: "/")}
{:noreply, push_patch(socket, to: "/", replace: true)}
"""
def push_patch(%Socket{} = socket, opts) do
%{to: to} = opts = push_opts!(opts, "push_patch/2")
case Phoenix.LiveView.Utils.live_link_info!(socket, socket.root_view, to) do
{:internal, params, action, _parsed_uri} ->
put_redirect(socket, {:live, {params, action}, opts})
{:external, _uri} ->
raise ArgumentError,
"cannot push_patch/2 to #{inspect(to)} because the given path " <>
"does not point to the current root view #{inspect(socket.root_view)}"
end
end
@doc """
Annotates the socket for navigation to another LiveView.
The current LiveView will be shutdown and a new one will be mounted
in its place, without reloading the whole page. This can
also be used to remount the same LiveView, in case you want to start
fresh. If you want to navigate to the same LiveView without remounting
it, use `push_patch/2` instead.
## Options
* `:to` - the required path to link to. It must always be a local path
* `:replace` - the flag to replace the current history or push a new state.
Defaults `false`.
## Examples
{:noreply, push_redirect(socket, to: "/")}
{:noreply, push_redirect(socket, to: "/", replace: true)}
"""
def push_redirect(%Socket{} = socket, opts) do
opts = push_opts!(opts, "push_redirect/2")
put_redirect(socket, {:live, :redirect, opts})
end
defp push_opts!(opts, context) do
to = Keyword.fetch!(opts, :to)
validate_local_url!(to, context)
kind = if opts[:replace], do: :replace, else: :push
%{to: to, kind: kind}
end
defp put_redirect(%Socket{redirected: nil} = socket, command) do
%Socket{socket | redirected: command}
end
defp put_redirect(%Socket{redirected: to} = _socket, _command) do
raise ArgumentError, "socket already prepared to redirect with #{inspect(to)}"
end
@invalid_local_url_chars ["\\"]
defp validate_local_url!("//" <> _ = to, where) do
raise_invalid_local_url!(to, where)
end
defp validate_local_url!("/" <> _ = to, where) do
if String.contains?(to, @invalid_local_url_chars) do
raise ArgumentError, "unsafe characters detected for #{where} in URL #{inspect(to)}"
else
to
end
end
defp validate_local_url!(to, where) do
raise_invalid_local_url!(to, where)
end
defp raise_invalid_local_url!(to, where) do
raise ArgumentError, "the :to option in #{where} expects a path but was #{inspect(to)}"
end
@doc """
Accesses the connect params sent by the client for use on connected mount.
Connect params are only sent when the client connects to the server and
only remain available during mount. `nil` is returned when called in a
disconnected state and a `RuntimeError` is raised if called after mount.
## Reserved params
The following params have special meaning in LiveView:
* "_csrf_token" - the CSRF Token which must be explicitly set by the user
when connecting
* "_mounts" - the number of times the current LiveView is mounted.
It is 0 on first mount, then increases on each reconnect. It resets
when navigating away from the current LiveView or on errors
* "_track_static" - set automatically with a list of all href/src from
tags with the "phx-track-static" annotation in them. If there are no
such tags, nothing is sent
## Examples
def mount(_params, _session, socket) do
{:ok, assign(socket, width: get_connect_params(socket)["width"] || @width)}
end
"""
def get_connect_params(%Socket{private: private} = socket) do
if connect_params = private[:connect_params] do
if connected?(socket), do: connect_params, else: nil
else
raise_connect_only!(socket, "connect_params")
end
end
@doc """
Accesses the connect info from the socket to use on connected mount.
Connect info are only sent when the client connects to the server and
only remain available during mount. `nil` is returned when called in a
disconnected state and a `RuntimeError` is raised if called after mount.
## Examples
First, when invoking the LiveView socket, you need to declare the
`connect_info` you want to receive. Typically, it includes at least
the session but it may include other keys, such as `:peer_data`.
See `Phoenix.Endpoint.socket/3`:
socket "/live", Phoenix.LiveView.Socket,
websocket: [connect_info: [:peer_data, session: @session_options]]
Those values can now be accessed on the connected mount as
`get_connect_info/1`:
def mount(_params, _session, socket) do
if info = get_connect_info(socket) do
{:ok, assign(socket, ip: info.peer_data.address)}
else
{:ok, assign(socket, ip: nil)}
end
end
"""
def get_connect_info(%Socket{private: private} = socket) do
if connect_info = private[:connect_info] do
if connected?(socket), do: connect_info, else: nil
else
raise_connect_only!(socket, "connect_info")
end
end
@doc """
Returns true if the socket is connected and the tracked static assets have changed.
This function is useful to detect if the client is running on an outdated
version of the marked static files. It works by comparing the static paths
sent by the client with the one on the server.
**Note:** this functionality requires Phoenix v1.5.2 or later.
To use this functionality, the first step is to annotate which static files
you want to be tracked by LiveView, with the `phx-track-static`. For example:
<link phx-track-static rel="stylesheet" href="<%= Routes.static_path(@conn, "/css/app.css") %>"/>
<script defer phx-track-static type="text/javascript" src="<%= Routes.static_path(@conn, "/js/app.js") %>"></script>
Now, whenever LiveView connects to the server, it will send a copy `src`
or `href` attributes of all tracked statics and compare those values with
the latest entries computed by `mix phx.digest` in the server.
The tracked statics on the client will match the ones on the server the
huge majority of times. However, if there is a new deployment, those values
may differ. You can use this function to detect those cases and show a
banner to the user, asking them to reload the page. To do so, first set the
assign on mount:
def mount(params, session, socket) do
{:ok, assign(socket, static_changed?: static_changed?(socket))}
end
And then in your views:
<%= if @static_change do %>
<div id="reload-static">
The app has been updated. Click here to <a href="#" onclick="window.location.reload()">reload</a>.
</div>
<% end %>
If you prefer, you can also send a JavaScript script that immediately
reloads the page.
**Note:** only set `phx-track-static` on your own assets. For example, do
not set it in external JavaScript files:
<script defer phx-track-static type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
Because you don't actually serve the file above, LiveView will interpret
the static above as missing, and this function will return true.
"""
def static_changed?(%Socket{private: private, endpoint: endpoint} = socket) do
if connect_params = private[:connect_params] do
connected?(socket) and
static_changed?(
connect_params["_track_static"],
endpoint.config(:cache_static_manifest_latest)
)
else
raise_connect_only!(socket, "static_changed?")
end
end
defp static_changed?([_ | _] = statics, %{} = latest) do
latest = Map.to_list(latest)
not Enum.all?(statics, fn static ->
[static | _] = :binary.split(static, "?")
Enum.any?(latest, fn {non_digested, digested} ->
String.ends_with?(static, non_digested) or String.ends_with?(static, digested)
end)
end)
end
defp static_changed?(_, _), do: false
defp raise_connect_only!(socket, fun) do
if child?(socket) do
raise RuntimeError, """
attempted to read #{fun} from a nested child LiveView #{inspect(socket.view)}.
Only the root LiveView has access to #{fun}.
"""
else
raise RuntimeError, """
attempted to read #{fun} outside of #{inspect(socket.view)}.mount/3.
#{fun} only exists while mounting. If you require access to this information
after mount, store the state in socket assigns.
"""
end
end
@doc """
Asynchronously updates a `Phoenix.LiveComponent` with new assigns.
The component that is updated must be stateful (the `:id` in the assigns must
match the `:id` associated with the component) and the component must be
mounted within the current LiveView.
When the component receives the update, the optional
[`preload/1`](`c:Phoenix.LiveComponent.preload/1`) callback is invoked, then
the updated values are merged with the component's assigns and
[`update/2`](`c:Phoenix.LiveComponent.update/2`) is called for the updated
component(s).
While a component may always be updated from the parent by updating some
parent assigns which will re-render the child, thus invoking
[`update/2`](`c:Phoenix.LiveComponent.update/2`) on the child component,
`send_update/2` is useful for updating a component that entirely manages its
own state, as well as messaging between components mounted in the same
LiveView.
**Note:** `send_update/2` cannot update a LiveComponent that is mounted in a
different LiveView. To update a component in a different LiveView you must
send a message to the LiveView process that the LiveComponent is mounted
within (often via `Phoenix.PubSub`).
## Examples
def handle_event("cancel-order", _, socket) do
...
send_update(Cart, id: "cart", status: "cancelled")
{:noreply, socket}
end
"""
def send_update(module, assigns) do
assigns = Enum.into(assigns, %{})
id =
assigns[:id] ||
raise ArgumentError, "missing required :id in send_update. Got: #{inspect(assigns)}"
Phoenix.LiveView.Channel.send_update(module, id, assigns)
end
@doc """
Returns the transport pid of the socket.
Raises `ArgumentError` if the socket is not connected.
## Examples
iex> transport_pid(socket)
#PID<0.107.0>
"""
def transport_pid(%Socket{}) do
case Process.get(:"$callers") do
[transport_pid | _] -> transport_pid
_ -> raise ArgumentError, "transport_pid/1 may only be called when the socket is connected."
end
end
defp child?(%Socket{parent_pid: pid}), do: is_pid(pid)
end
| 36.889864 | 148 | 0.68879 |
032a12c8085912b0a6bf702ee4b7261ee52cb31d | 1,133 | exs | Elixir | apps/aehttpclient/config/config.exs | wuminzhe/elixir-node | eb87b47339a8349bac767dd4cf597dfaf0ed75c6 | [
"ISC"
] | null | null | null | apps/aehttpclient/config/config.exs | wuminzhe/elixir-node | eb87b47339a8349bac767dd4cf597dfaf0ed75c6 | [
"ISC"
] | null | null | null | apps/aehttpclient/config/config.exs | wuminzhe/elixir-node | eb87b47339a8349bac767dd4cf597dfaf0ed75c6 | [
"ISC"
] | 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 :aehttpclient, key: :value
#
# and access this configuration in your application as:
#
# Application.get_env(:aehttpclient, :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.548387 | 73 | 0.753751 |
032a46ecbf6bff1d0f5a406e7a794343cde68469 | 26,265 | exs | Elixir | test/livebook/completion_test.exs | brettcannon/livebook | d6c9ab1783efa083aea2ead81e078bb920d57ad6 | [
"Apache-2.0"
] | null | null | null | test/livebook/completion_test.exs | brettcannon/livebook | d6c9ab1783efa083aea2ead81e078bb920d57ad6 | [
"Apache-2.0"
] | null | null | null | test/livebook/completion_test.exs | brettcannon/livebook | d6c9ab1783efa083aea2ead81e078bb920d57ad6 | [
"Apache-2.0"
] | 1 | 2021-07-07T06:18:36.000Z | 2021-07-07T06:18:36.000Z | defmodule Livebook.CompletionTest.Utils do
@moduledoc false
@doc """
Returns `{binding, env}` resulting from evaluating
the given block of code in a fresh context.
"""
defmacro eval(do: block) do
binding = []
env = :elixir.env_for_eval([])
{_, binding, env} = :elixir.eval_quoted(block, binding, env)
quote do
{unquote(Macro.escape(binding)), unquote(Macro.escape(env))}
end
end
end
defmodule Livebook.CompletionTest do
use ExUnit.Case, async: true
import Livebook.CompletionTest.Utils
alias Livebook.Completion
test "completion when no hint given" do
{binding, env} = eval(do: nil)
length_item = %{
label: "length/1",
kind: :function,
detail: "Kernel.length(list)",
documentation: """
Returns the length of `list`.
```
@spec length(list()) ::
non_neg_integer()
```\
""",
insert_text: "length"
}
assert length_item in Completion.get_completion_items("", binding, env)
assert length_item in Completion.get_completion_items("Enum.map(list, ", binding, env)
end
@tag :erl_docs
test "Erlang module completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "zlib",
kind: :module,
detail: "module",
documentation:
"This module provides an API for the zlib library (www.zlib.net). It is used to compress and decompress data. The data format is described by RFC 1950, RFC 1951, and RFC 1952.",
insert_text: "zlib"
}
] = Completion.get_completion_items(":zl", binding, env)
end
test "Erlang module no completion" do
{binding, env} = eval(do: nil)
assert [] = Completion.get_completion_items(":unknown", binding, env)
end
test "Erlang module multiple values completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "user",
kind: :module,
detail: "module",
documentation: _user_doc,
insert_text: "user"
},
%{
label: "user_drv",
kind: :module,
detail: "module",
documentation: _user_drv_doc,
insert_text: "user_drv"
},
%{
label: "user_sup",
kind: :module,
detail: "module",
documentation: _user_sup_doc,
insert_text: "user_sup"
}
] = Completion.get_completion_items(":user", binding, env)
end
@tag :erl_docs
test "Erlang root completion" do
{binding, env} = eval(do: nil)
lists_item = %{
label: "lists",
kind: :module,
detail: "module",
documentation: "This module contains functions for list processing.",
insert_text: "lists"
}
assert lists_item in Completion.get_completion_items(":", binding, env)
assert lists_item in Completion.get_completion_items(" :", binding, env)
end
test "Elixir proxy" do
{binding, env} = eval(do: nil)
assert %{
label: "Elixir",
kind: :module,
detail: "module",
documentation: nil,
insert_text: "Elixir"
} in Completion.get_completion_items("E", binding, env)
end
test "Elixir module completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "Enum",
kind: :module,
detail: "module",
documentation: "Provides a set of algorithms to work with enumerables.",
insert_text: "Enum"
},
%{
label: "Enumerable",
kind: :module,
detail: "module",
documentation: "Enumerable protocol used by `Enum` and `Stream` modules.",
insert_text: "Enumerable"
}
] = Completion.get_completion_items("En", binding, env)
assert [
%{
label: "Enumerable",
kind: :module,
detail: "module",
documentation: "Enumerable protocol used by `Enum` and `Stream` modules.",
insert_text: "Enumerable"
}
] = Completion.get_completion_items("Enumera", binding, env)
end
test "Elixir type completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "from/0",
kind: :type,
detail: "typespec",
documentation: "Tuple describing the client of a call request.",
insert_text: "from"
}
] = Completion.get_completion_items("GenServer.fr", binding, env)
assert [
%{
label: "name/0",
kind: :type,
detail: "typespec",
documentation: _name_doc,
insert_text: "name"
},
%{
label: "name_all/0",
kind: :type,
detail: "typespec",
documentation: _name_all_doc,
insert_text: "name_all"
}
] = Completion.get_completion_items(":file.nam", binding, env)
end
test "Elixir completion with self" do
{binding, env} = eval(do: nil)
assert [
%{
label: "Enumerable",
kind: :module,
detail: "module",
documentation: "Enumerable protocol used by `Enum` and `Stream` modules.",
insert_text: "Enumerable"
}
] = Completion.get_completion_items("Enumerable", binding, env)
end
test "Elixir completion on modules from load path" do
{binding, env} = eval(do: nil)
assert %{
label: "Jason",
kind: :module,
detail: "module",
documentation: "A blazing fast JSON parser and generator in pure Elixir.",
insert_text: "Jason"
} in Completion.get_completion_items("Jas", binding, env)
end
test "Elixir no completion" do
{binding, env} = eval(do: nil)
assert [] = Completion.get_completion_items(".", binding, env)
assert [] = Completion.get_completion_items("Xyz", binding, env)
assert [] = Completion.get_completion_items("x.Foo", binding, env)
assert [] = Completion.get_completion_items("x.Foo.get_by", binding, env)
end
test "Elixir root submodule completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "Access",
kind: :module,
detail: "module",
documentation: "Key-based access to data structures.",
insert_text: "Access"
}
] = Completion.get_completion_items("Elixir.Acce", binding, env)
end
test "Elixir submodule completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "ANSI",
kind: :module,
detail: "module",
documentation: "Functionality to render ANSI escape sequences.",
insert_text: "ANSI"
}
] = Completion.get_completion_items("IO.AN", binding, env)
end
test "Elixir submodule no completion" do
{binding, env} = eval(do: nil)
assert [] = Completion.get_completion_items("IEx.Xyz", binding, env)
end
test "Elixir function completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "version/0",
kind: :function,
detail: "System.version()",
documentation: """
Elixir version information.
```
@spec version() :: String.t()
```\
""",
insert_text: "version"
}
] = Completion.get_completion_items("System.ve", binding, env)
end
@tag :erl_docs
test "Erlang function completion" do
{binding, env} = eval(do: nil)
assert %{
label: "gzip/1",
kind: :function,
detail: "zlib.gzip/1",
documentation: """
Compresses data with gz headers and checksum.
```
@spec gzip(data) :: compressed
when data: iodata(),
compressed: binary()
```\
""",
insert_text: "gzip"
} in Completion.get_completion_items(":zlib.gz", binding, env)
end
test "function completion with arity" do
{binding, env} = eval(do: nil)
assert %{
label: "concat/1",
kind: :function,
detail: "Enum.concat(enumerables)",
documentation: """
Given an enumerable of enumerables, concatenates the `enumerables` into
a single list.
```
@spec concat(t()) :: t()
```\
""",
insert_text: "concat"
} in Completion.get_completion_items("Enum.concat/", binding, env)
end
test "function completion same name with different arities" do
{binding, env} = eval(do: nil)
assert [
%{
label: "concat/1",
kind: :function,
detail: "Enum.concat(enumerables)",
documentation: """
Given an enumerable of enumerables, concatenates the `enumerables` into
a single list.
```
@spec concat(t()) :: t()
```\
""",
insert_text: "concat"
},
%{
label: "concat/2",
kind: :function,
detail: "Enum.concat(left, right)",
documentation: """
Concatenates the enumerable on the `right` with the enumerable on the
`left`.
```
@spec concat(t(), t()) :: t()
```\
""",
insert_text: "concat"
}
] = Completion.get_completion_items("Enum.concat", binding, env)
end
test "function completion when has default args then documentation all arities have docs" do
{binding, env} = eval(do: nil)
assert [
%{
label: "join/1",
kind: :function,
detail: ~S{Enum.join(enumerable, joiner \\ "")},
documentation: """
Joins the given `enumerable` into a string using `joiner` as a
separator.
```
@spec join(t(), String.t()) ::
String.t()
```\
""",
insert_text: "join"
},
%{
label: "join/2",
kind: :function,
detail: ~S{Enum.join(enumerable, joiner \\ "")},
documentation: """
Joins the given `enumerable` into a string using `joiner` as a
separator.
```
@spec join(t(), String.t()) ::
String.t()
```\
""",
insert_text: "join"
}
] = Completion.get_completion_items("Enum.jo", binding, env)
end
test "function completion using a variable bound to a module" do
{binding, env} =
eval do
mod = System
end
assert [
%{
label: "version/0",
kind: :function,
detail: "System.version()",
documentation: """
Elixir version information.
```
@spec version() :: String.t()
```\
""",
insert_text: "version"
}
] = Completion.get_completion_items("mod.ve", binding, env)
end
test "map atom key completion" do
{binding, env} =
eval do
map = %{
foo: 1,
bar_1: ~r/pattern/,
bar_2: true
}
end
assert [
%{
label: "bar_1",
kind: :field,
detail: "field",
documentation: ~s{```\n~r/pattern/\n```},
insert_text: "bar_1"
},
%{
label: "bar_2",
kind: :field,
detail: "field",
documentation: ~s{```\ntrue\n```},
insert_text: "bar_2"
},
%{
label: "foo",
kind: :field,
detail: "field",
documentation: ~s{```\n1\n```},
insert_text: "foo"
}
] = Completion.get_completion_items("map.", binding, env)
assert [
%{
label: "foo",
kind: :field,
detail: "field",
documentation: ~s{```\n1\n```},
insert_text: "foo"
}
] = Completion.get_completion_items("map.f", binding, env)
end
test "nested map atom key completion" do
{binding, env} =
eval do
map = %{
nested: %{
deeply: %{
foo: 1,
bar_1: 23,
bar_2: 14,
mod: System
}
}
}
end
assert [
%{
label: "nested",
kind: :field,
detail: "field",
documentation: """
```
%{
deeply: %{
bar_1: 23,
bar_2: 14,
foo: 1,
mod: System
}
}
```\
""",
insert_text: "nested"
}
] = Completion.get_completion_items("map.nest", binding, env)
assert [
%{
label: "foo",
kind: :field,
detail: "field",
documentation: ~s{```\n1\n```},
insert_text: "foo"
}
] = Completion.get_completion_items("map.nested.deeply.f", binding, env)
assert [
%{
label: "version/0",
kind: :function,
detail: "System.version()",
documentation: """
Elixir version information.
```
@spec version() :: String.t()
```\
""",
insert_text: "version"
}
] = Completion.get_completion_items("map.nested.deeply.mod.ve", binding, env)
assert [] = Completion.get_completion_items("map.non.existent", binding, env)
end
test "map string key completion is not supported" do
{binding, env} =
eval do
map = %{"foo" => 1}
end
assert [] = Completion.get_completion_items("map.f", binding, env)
end
test "autocompletion off a bound variable only works for modules and maps" do
{binding, env} =
eval do
num = 5
map = %{nested: %{num: 23}}
end
assert [] = Completion.get_completion_items("num.print", binding, env)
assert [] = Completion.get_completion_items("map.nested.num.f", binding, env)
end
test "autocompletion using access syntax does is not supported" do
{binding, env} =
eval do
map = %{nested: %{deeply: %{num: 23}}}
end
assert [] = Completion.get_completion_items("map[:nested][:deeply].n", binding, env)
assert [] = Completion.get_completion_items("map[:nested].deeply.n", binding, env)
assert [] = Completion.get_completion_items("map.nested.[:deeply].n", binding, env)
end
test "macro completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "is_nil/1",
kind: :function,
detail: "Kernel.is_nil(term)",
documentation: "Returns `true` if `term` is `nil`, `false` otherwise.",
insert_text: "is_nil"
}
] = Completion.get_completion_items("Kernel.is_ni", binding, env)
end
test "special forms completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "quote/2",
kind: :function,
detail: "Kernel.SpecialForms.quote(opts, block)",
documentation: "Gets the representation of any expression.",
insert_text: "quote"
}
] = Completion.get_completion_items("quot", binding, env)
end
test "kernel import completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "put_in/2",
kind: :function,
detail: "Kernel.put_in(path, value)",
documentation: "Puts a value in a nested structure via the given `path`.",
insert_text: "put_in"
},
%{
label: "put_in/3",
kind: :function,
detail: "Kernel.put_in(data, keys, value)",
documentation: """
Puts a value in a nested structure.
```
@spec put_in(
Access.t(),
[term(), ...],
term()
) :: Access.t()
```\
""",
insert_text: "put_in"
}
] = Completion.get_completion_items("put_i", binding, env)
end
test "variable name completion" do
{binding, env} =
eval do
number = 3
numbats = ["numbat", "numbat"]
nothing = nil
end
assert [
%{
label: "numbats",
kind: :variable,
detail: "variable",
documentation: ~s{```\n["numbat", "numbat"]\n```},
insert_text: "numbats"
}
] = Completion.get_completion_items("numba", binding, env)
assert [
%{
label: "numbats",
kind: :variable,
detail: "variable",
documentation: ~s{```\n["numbat", "numbat"]\n```},
insert_text: "numbats"
},
%{
label: "number",
kind: :variable,
detail: "variable",
documentation: ~s{```\n3\n```},
insert_text: "number"
}
] = Completion.get_completion_items("num", binding, env)
assert [
%{
label: "nothing",
kind: :variable,
detail: "variable",
documentation: ~s{```\nnil\n```},
insert_text: "nothing"
},
%{label: "node/0"},
%{label: "node/1"},
%{label: "not/1"}
] = Completion.get_completion_items("no", binding, env)
end
test "completion of manually imported functions and macros" do
{binding, env} =
eval do
import Enum
import System, only: [version: 0]
import Protocol
end
assert [
%{label: "take/2"},
%{label: "take_every/2"},
%{label: "take_random/2"},
%{label: "take_while/2"}
] = Completion.get_completion_items("take", binding, env)
assert %{
label: "version/0",
kind: :function,
detail: "System.version()",
documentation: """
Elixir version information.
```
@spec version() :: String.t()
```\
""",
insert_text: "version"
} in Completion.get_completion_items("v", binding, env)
assert [
%{label: "derive/2"},
%{label: "derive/3"}
] = Completion.get_completion_items("der", binding, env)
end
test "ignores quoted variables when performing variable completion" do
{binding, env} =
eval do
quote do
var!(my_var_1, Elixir) = 1
end
my_var_2 = 2
end
assert [
%{label: "my_var_2"}
] = Completion.get_completion_items("my_var", binding, env)
end
test "completion inside expression" do
{binding, env} = eval(do: nil)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("1 En", binding, env)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("foo(En", binding, env)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("Test En", binding, env)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("foo(x,En", binding, env)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("[En", binding, env)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("{En", binding, env)
end
test "ampersand completion" do
{binding, env} = eval(do: nil)
assert [
%{label: "Enum"},
%{label: "Enumerable"}
] = Completion.get_completion_items("&En", binding, env)
assert [
%{label: "all?/1"},
%{label: "all?/2"}
] = Completion.get_completion_items("&Enum.al", binding, env)
assert [
%{label: "all?/1"},
%{label: "all?/2"}
] = Completion.get_completion_items("f = &Enum.al", binding, env)
end
test "negation operator completion" do
{binding, env} = eval(do: nil)
assert [
%{label: "is_binary/1"}
] = Completion.get_completion_items("!is_bin", binding, env)
end
test "pin operator completion" do
{binding, env} =
eval do
my_variable = 2
end
assert [
%{label: "my_variable"}
] = Completion.get_completion_items("^my_va", binding, env)
end
defmodule SublevelTest.LevelA.LevelB do
end
test "Elixir completion sublevel" do
{binding, env} = eval(do: nil)
assert [
%{label: "LevelA"}
] =
Completion.get_completion_items(
"Livebook.CompletionTest.SublevelTest.",
binding,
env
)
end
test "complete aliases of Elixir modules" do
{binding, env} =
eval do
alias List, as: MyList
end
assert [
%{label: "MyList"}
] = Completion.get_completion_items("MyL", binding, env)
assert [
%{label: "to_integer/1"},
%{label: "to_integer/2"}
] = Completion.get_completion_items("MyList.to_integ", binding, env)
end
@tag :erl_docs
test "complete aliases of Erlang modules" do
{binding, env} =
eval do
alias :lists, as: EList
end
assert [
%{label: "EList"}
] = Completion.get_completion_items("EL", binding, env)
assert [
%{label: "map/2"},
%{label: "mapfoldl/3"},
%{label: "mapfoldr/3"}
] = Completion.get_completion_items("EList.map", binding, env)
assert %{
label: "max/1",
kind: :function,
detail: "lists.max/1",
documentation: """
Returns the first element of List that compares greater than or equal to all other elements of List.
```
@spec max(list) :: max
when list: [t, ...],
max: t,
t: term()
```\
""",
insert_text: "max"
} in Completion.get_completion_items("EList.", binding, env)
assert [] = Completion.get_completion_items("EList.Invalid", binding, env)
end
test "completion for functions added when compiled module is reloaded" do
{binding, env} = eval(do: nil)
{:module, _, bytecode, _} =
defmodule Sample do
def foo(), do: 0
end
assert [
%{label: "foo/0"}
] = Completion.get_completion_items("Livebook.CompletionTest.Sample.foo", binding, env)
Code.compiler_options(ignore_module_conflict: true)
defmodule Sample do
def foo(), do: 0
def foobar(), do: 0
end
assert [
%{label: "foo/0"},
%{label: "foobar/0"}
] = Completion.get_completion_items("Livebook.CompletionTest.Sample.foo", binding, env)
after
Code.compiler_options(ignore_module_conflict: false)
:code.purge(Sample)
:code.delete(Sample)
end
defmodule MyStruct do
defstruct [:my_val]
end
test "completion for struct names" do
{binding, env} = eval(do: nil)
assert [
%{label: "MyStruct"}
] = Completion.get_completion_items("Livebook.CompletionTest.MyStr", binding, env)
end
test "completion for struct keys" do
{binding, env} =
eval do
struct = %Livebook.CompletionTest.MyStruct{}
end
assert [
%{label: "my_val"}
] = Completion.get_completion_items("struct.my", binding, env)
end
test "ignore invalid Elixir module literals" do
{binding, env} = eval(do: nil)
defmodule(:"Elixir.Livebook.CompletionTest.Unicodé", do: nil)
assert [] = Completion.get_completion_items("Livebook.CompletionTest.Unicod", binding, env)
after
:code.purge(:"Elixir.Livebook.CompletionTest.Unicodé")
:code.delete(:"Elixir.Livebook.CompletionTest.Unicodé")
end
test "known Elixir module attributes completion" do
{binding, env} = eval(do: nil)
assert [
%{
label: "moduledoc",
kind: :variable,
detail: "module attribute",
documentation: "Provides documentation for the current module.",
insert_text: "moduledoc"
}
] = Completion.get_completion_items("@modu", binding, env)
end
end
| 28.272336 | 194 | 0.491491 |
032a738131656d3f85ed4c1dbba0e26a842aa25f | 14,663 | ex | Elixir | clients/compute/lib/google_api/compute/v1/api/zone_operations.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/zone_operations.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"Apache-2.0"
] | null | null | null | clients/compute/lib/google_api/compute/v1/api/zone_operations.ex | ukrbublik/elixir-google-api | 364cec36bc76f60bec94cbcad34844367a29d174 | [
"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.Api.ZoneOperations do
@moduledoc """
API calls for all endpoints tagged `ZoneOperations`.
"""
alias GoogleApi.Compute.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@library_version Mix.Project.config() |> Keyword.get(:version, "")
@doc """
Deletes the specified zone-specific Operations resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for this request.
* `operation` (*type:* `String.t`) - Name of the Operations 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.
* `opts` (*type:* `keyword()`) - Call options
## Returns
* `{:ok, %{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_delete(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) :: {:ok, nil} | {:ok, Tesla.Env.t()} | {:error, any()}
def compute_zone_operations_delete(
connection,
project,
zone,
operation,
optional_params \\ [],
opts \\ []
) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query
}
request =
Request.new()
|> Request.method(:delete)
|> Request.url("/{project}/zones/{zone}/operations/{operation}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Retrieves the specified zone-specific Operations resource.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for this request.
* `operation` (*type:* `String.t`) - Name of the Operations 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.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_get(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def compute_zone_operations_get(
connection,
project,
zone,
operation,
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}/zones/{zone}/operations/{operation}", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &(URI.char_unreserved?(&1) || &1 == ?/))
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
@doc """
Retrieves a list of Operation resources contained within the specified zone.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for 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.OperationList{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_list(
Tesla.Env.client(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.OperationList.t()}
| {:ok, Tesla.Env.t()}
| {:error, any()}
def compute_zone_operations_list(connection, project, zone, 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}/zones/{zone}/operations", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.OperationList{}])
end
@doc """
Waits for the specified Operation resource to return as `DONE` or for the request to approach the 2 minute deadline, and retrieves the specified Operation resource. This method differs from the `GET` method in that it waits for no more than the default deadline (2 minutes) and then returns the current state of the operation, which might be `DONE` or still in progress.
This method is called on a best-effort basis. Specifically:
- In uncommon cases, when the server is overloaded, the request might return before the default deadline is reached, or might return after zero seconds.
- If the default deadline is reached, there is no guarantee that the operation is actually done when the method returns. Be prepared to retry if the operation is not `DONE`.
## Parameters
* `connection` (*type:* `GoogleApi.Compute.V1.Connection.t`) - Connection to server
* `project` (*type:* `String.t`) - Project ID for this request.
* `zone` (*type:* `String.t`) - Name of the zone for this request.
* `operation` (*type:* `String.t`) - Name of the Operations 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.Operation{}}` on success
* `{:error, info}` on failure
"""
@spec compute_zone_operations_wait(
Tesla.Env.client(),
String.t(),
String.t(),
String.t(),
keyword(),
keyword()
) ::
{:ok, GoogleApi.Compute.V1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, any()}
def compute_zone_operations_wait(
connection,
project,
zone,
operation,
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(:post)
|> Request.url("/{project}/zones/{zone}/operations/{operation}/wait", %{
"project" => URI.encode(project, &URI.char_unreserved?/1),
"zone" => URI.encode(zone, &URI.char_unreserved?/1),
"operation" => URI.encode(operation, &URI.char_unreserved?/1)
})
|> Request.add_optional_params(optional_params_config, optional_params)
|> Request.library_version(@library_version)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Compute.V1.Model.Operation{}])
end
end
| 47.453074 | 434 | 0.639705 |
032aa0b13ca8c0680f6834ece210aa863a4bec11 | 1,099 | ex | Elixir | test/support/channel_case.ex | DaveMuirhead/naboo-server | daf15d9b92ad6a3f85eb42bdbe7125c489a079c1 | [
"Apache-2.0"
] | null | null | null | test/support/channel_case.ex | DaveMuirhead/naboo-server | daf15d9b92ad6a3f85eb42bdbe7125c489a079c1 | [
"Apache-2.0"
] | null | null | null | test/support/channel_case.ex | DaveMuirhead/naboo-server | daf15d9b92ad6a3f85eb42bdbe7125c489a079c1 | [
"Apache-2.0"
] | null | null | null | defmodule NabooWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use NabooWeb.ChannelCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
import Phoenix.ChannelTest
import NabooWeb.ChannelCase
# The default endpoint for testing
@endpoint NabooWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Naboo.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Naboo.Repo, {:shared, self()})
end
:ok
end
end
| 26.804878 | 67 | 0.724295 |
032ab07d1e0dcf1034454628ecc0f0e108e84af1 | 4,871 | ex | Elixir | lib/membrane/caps/matcher.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | null | null | null | lib/membrane/caps/matcher.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | null | null | null | lib/membrane/caps/matcher.ex | eboskma/membrane_core | e216994fe1ba99c5d228a4b0959faa5fabb13b1c | [
"Apache-2.0"
] | null | null | null | defmodule Membrane.Caps.Matcher do
@moduledoc """
Module that allows to specify valid caps and verify that they match specification.
Caps specifications (specs) should be in one of the formats:
* simply module name of the desired caps (e.g. `Membrane.Caps.Audio.Raw` or `Raw` with proper alias)
* tuple with module name and keyword list of specs for specific caps fields (e.g. `{Raw, format: :s24le}`)
* list of the formats described above
Field values can be specified in following ways:
* By a raw value for the field (e.g. `:s24le`)
* Using `range/2` for values comparable with `Kernel.<=/2` and `Kernel.>=/2` (e.g. `Matcher.range(0, 255)`)
* With `one_of/1` and a list of valid values (e.g `Matcher.one_of([:u8, :s16le, :s32le])`)
Checks on the values from list are performed recursively i.e. it can contain another `range/2`,
for example `Matcher.one_of([0, Matcher.range(2, 4), Matcher.range(10, 20)])`
If the specs are defined inside of `Membrane.Element.WithInputPads.def_input_pad/2` and
`Membrane.Element.WithOutputPads.def_output_pad/2` module name can be omitted from
`range/2` and `one_of/1` calls.
## Example
Below is a pad definition with an example of specs for caps matcher:
alias Membrane.Caps.Video.Raw
def_input_pad :input,
demand_unit: :buffers,
caps: {Raw, format: one_of([:I420, :I422]), aligned: true}
"""
import Kernel, except: [match?: 2]
alias Bunch
require Record
@type caps_spec_t :: module() | {module(), keyword()}
@type caps_specs_t :: :any | caps_spec_t() | [caps_spec_t()]
defmodule Range do
@moduledoc false
@enforce_keys [:min, :max]
defstruct @enforce_keys
end
@opaque range_t :: %Range{min: any, max: any}
defimpl Inspect, for: Range do
import Inspect.Algebra
@impl true
def inspect(%Range{min: min, max: max}, opts) do
concat(["range(", to_doc(min, opts), ", ", to_doc(max, opts), ")"])
end
end
defmodule OneOf do
@moduledoc false
@enforce_keys [:list]
defstruct @enforce_keys
end
@opaque one_of_t :: %OneOf{list: list()}
defimpl Inspect, for: OneOf do
import Inspect.Algebra
@impl true
def inspect(%OneOf{list: list}, opts) do
concat(["one_of(", to_doc(list, opts), ")"])
end
end
@doc """
Returns opaque specification of range of valid values for caps field.
"""
@spec range(any, any) :: range_t()
def range(min, max) do
%Range{min: min, max: max}
end
@doc """
Returns opaque specification of list of valid values for caps field.
"""
@spec one_of(list()) :: one_of_t()
def one_of(values) when is_list(values) do
%OneOf{list: values}
end
@doc """
Function used to make sure caps specs are valid.
In particular, valid caps:
* Have shape described by `t:caps_specs_t/0` type
* If they contain keyword list, the keys are present in requested caps type
It returns `:ok` when caps are valid and `{:error, reason}` otherwise
"""
@spec validate_specs(caps_specs_t() | any()) :: :ok | {:error, reason :: tuple()}
def validate_specs(specs_list) when is_list(specs_list) do
specs_list |> Bunch.Enum.try_each(&validate_specs/1)
end
def validate_specs({type, keyword_specs}) do
caps = type.__struct__
caps_keys = caps |> Map.from_struct() |> Map.keys() |> MapSet.new()
spec_keys = keyword_specs |> Keyword.keys() |> MapSet.new()
if MapSet.subset?(spec_keys, caps_keys) do
:ok
else
invalid_keys = spec_keys |> MapSet.difference(caps_keys) |> MapSet.to_list()
{:error, {:invalid_keys, type, invalid_keys}}
end
end
def validate_specs(specs) when is_atom(specs), do: :ok
def validate_specs(specs), do: {:error, {:invalid_specs, specs}}
@doc """
Function determining whether the caps match provided specs.
When `:any` is used as specs, caps can by anything (i.e. they can be invalid)
"""
@spec match?(caps_specs_t(), struct() | any()) :: boolean()
def match?(:any, _caps), do: true
def match?(specs, %_{} = caps) when is_list(specs) do
specs |> Enum.any?(fn spec -> match?(spec, caps) end)
end
def match?({type, keyword_specs}, %caps_type{} = caps) do
type == caps_type && keyword_specs |> Enum.all?(fn kv -> kv |> match_caps_entry(caps) end)
end
def match?(type, %caps_type{}) when is_atom(type) do
type == caps_type
end
defp match_caps_entry({spec_key, spec_value}, %{} = caps) do
{:ok, caps_value} = caps |> Map.fetch(spec_key)
match_value(spec_value, caps_value)
end
defp match_value(%OneOf{list: specs}, value) when is_list(specs) do
specs |> Enum.any?(fn spec -> match_value(spec, value) end)
end
defp match_value(%Range{min: min, max: max}, value) do
min <= value && value <= max
end
defp match_value(spec, value) do
spec == value
end
end
| 30.254658 | 111 | 0.663313 |
032ab0c43e7919334fe773483add6879f8e81655 | 124 | ex | Elixir | lib/marine_diesel/error.ex | twostairs/marine_diesel | a8be4102ec0f726a48a3ad0dafdf2286ce9afae3 | [
"MIT"
] | 3 | 2017-04-10T20:12:47.000Z | 2017-09-11T04:50:22.000Z | lib/marine_diesel/error.ex | twostairs/marine_diesel | a8be4102ec0f726a48a3ad0dafdf2286ce9afae3 | [
"MIT"
] | null | null | null | lib/marine_diesel/error.ex | twostairs/marine_diesel | a8be4102ec0f726a48a3ad0dafdf2286ce9afae3 | [
"MIT"
] | null | null | null | defmodule MarineDiesel.Error do
@derive [Poison.Encoder]
defstruct [
:http_code,
:message
]
end
| 15.5 | 31 | 0.604839 |
032ac25bdc3add8bb09cdf087b56ab749f5ef340 | 949 | ex | Elixir | farmbot_os/platform/host/configurator.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | 1 | 2019-08-06T11:51:48.000Z | 2019-08-06T11:51:48.000Z | farmbot_os/platform/host/configurator.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | farmbot_os/platform/host/configurator.ex | SeppPenner/farmbot_os | 39ba5c5880f8aef71792e2c009514bed1177089c | [
"MIT"
] | null | null | null | defmodule FarmbotOS.Platform.Host.Configurator do
@moduledoc false
use Supervisor
@doc false
def start_link(args) do
Supervisor.start_link(__MODULE__, args, name: __MODULE__)
end
defp start_node() do
case Node.start(:"[email protected]") do
{:ok, _} -> :ok
_ -> :ok
end
end
def init(_) do
start_node()
# Get out authorization data out of the environment.
# for host environment this will be configured at compile time.
# for target environment it will be configured by `configurator`.
System.get_env("FARMBOT_EMAIL") || raise error("email")
System.get_env("FARMBOT_PASSWORD") || raise error("password")
System.get_env("FARMBOT_SERVER") || raise error("server")
:ignore
end
defp error(_field) do
"""
Your environment is not properly configured!
Please export FARMBOT_EMAIL, FARMBOT_PASSWORD and FARMBOT_SERVER
in your environment.
"""
end
end
| 26.361111 | 69 | 0.687039 |
032ad0bac35591399f7f1ff94694bc6485a3368c | 4,113 | exs | Elixir | test/unit/rest_v2_test.exs | Switch168/MongoosePush | d997bd9cd0e63e16684bec9495cd12790bcaa8f1 | [
"Apache-2.0"
] | null | null | null | test/unit/rest_v2_test.exs | Switch168/MongoosePush | d997bd9cd0e63e16684bec9495cd12790bcaa8f1 | [
"Apache-2.0"
] | null | null | null | test/unit/rest_v2_test.exs | Switch168/MongoosePush | d997bd9cd0e63e16684bec9495cd12790bcaa8f1 | [
"Apache-2.0"
] | null | null | null | defmodule RestV2Test do
use ExUnit.Case, async: false
import Mock
alias HTTPoison.Response
@url "/v2/notification/f534534543"
setup do
TestHelper.reload_app()
end
test "incorrect path returns 404" do
assert 404 = post("/notification", %{})
assert 404 = post("/v2/notification", %{})
assert 404 = post("/v2/notifications/test", %{})
end
test "incorrect tags return 400" do
args = %{
service: :fcm,
mode: :dev,
topic: "apns topic",
priority: :high,
mutable_content: false,
time_to_live: 200,
tags: ["non existing atom here"],
alert: %{
body: "body654",
title: "title345",
badge: 10,
tag: "tag123",
click_action: "on.click",
sound: "sound.wav"
}
}
assert 400 = post(@url, args)
end
test "incorrect params returns 400" do
assert 400 = post(@url, %{service: :apns})
assert 400 = post(@url, %{service: :fcm})
assert 400 = post(@url, %{service: :apns, body: "body"})
assert 400 = post(@url, %{service: :fcm, title: "title"})
assert 400 = post(@url, %{service: :fcm, body: "body", title: "title"})
assert 400 = post(@url, %{service: "other", body: "body", title: "title"})
end
test "invalid method returns 405" do
assert 405 = get("/v2/notification/test")
end
test "api crash returns 500" do
with_mock MongoosePush, push: fn _, _ -> raise "oops" end do
assert 500 = post(@url, %{service: :fcm, alert: %{body: "body", title: "title"}})
end
end
test "correct params return 200" do
with_mock MongoosePush, push: fn _, _ -> :ok end do
assert 200 = post(@url, %{service: :apns, alert: %{body: "body", title: "title"}})
assert 200 = post(@url, %{service: :fcm, alert: %{body: "body", title: "title"}})
assert 200 = post(@url, %{service: :apns, data: %{a1: "test", a2: "test"}})
assert 200 = post(@url, %{service: :fcm, data: %{a1: "test", a2: "test"}})
end
end
test "push error returns 500" do
with_mock MongoosePush, push: fn _, _ -> {:error, :something} end do
assert 500 = post(@url, %{service: :apns, alert: %{body: "body", title: "title"}})
assert 500 = post(@url, %{service: :fcm, alert: %{body: "body", title: "title"}})
end
end
test "unknown push error returns 500" do
with_mock MongoosePush, push: fn _, _ -> {:error, {1, "unknown"}} end do
assert 500 = post(@url, %{service: :apns, alert: %{body: "body", title: "title"}})
assert 500 = post(@url, %{service: :fcm, alert: %{body: "body", title: "title"}})
end
end
test "api gets correct request arguments" do
with_mock MongoosePush, push: fn _, _ -> :ok end do
args = %{
service: :fcm,
mode: :dev,
topic: "apns topic",
priority: :high,
mutable_content: false,
time_to_live: 200,
tags: [:pool, :type],
alert: %{
body: "body654",
title: "title345",
badge: 10,
tag: "tag123",
click_action: "on.click",
sound: "sound.wav"
}
}
assert 200 = post(@url, args)
assert called(MongoosePush.push("f534534543", args))
end
end
test "api gets raw data payload" do
with_mock MongoosePush, push: fn _, _ -> :ok end do
args = %{
service: :fcm,
mode: :dev,
priority: :normal,
mutable_content: true,
alert: %{body: "body654", title: "title345"},
data: %{"acme1" => "value1", "acme2" => "value2"}
}
assert 200 = post(@url, args)
assert called(MongoosePush.push("f534534543", args))
end
end
defp post(path, json) do
%Response{status_code: status_code} =
HTTPoison.post!(
"https://localhost:8443" <> path,
Poison.encode!(json),
[{"Content-Type", "application/json"}],
hackney: [:insecure]
)
status_code
end
defp get(path) do
%Response{status_code: status_code} =
HTTPoison.get!("https://localhost:8443" <> path, [], hackney: [:insecure])
status_code
end
end
| 28.964789 | 88 | 0.5699 |
032adf58d2c26301b781af2f28a47ecf2d7395e3 | 66 | exs | Elixir | test/test_helper.exs | jparadasb/ex_21 | 897a141afdb0697667a580eada727c8430e61b6d | [
"MIT"
] | null | null | null | test/test_helper.exs | jparadasb/ex_21 | 897a141afdb0697667a580eada727c8430e61b6d | [
"MIT"
] | null | null | null | test/test_helper.exs | jparadasb/ex_21 | 897a141afdb0697667a580eada727c8430e61b6d | [
"MIT"
] | null | null | null | ExUnit.start()
Ecto.Adapters.SQL.Sandbox.mode(Ex21.Repo, :manual)
| 22 | 50 | 0.772727 |
032b02d3cf7e22e6017f864cacab598de95ceecf | 2,789 | ex | Elixir | lib/sensor_sht31.ex | elcritch/nerves_sensors | 7cd38e329fcdaa8e2112e195bdfcdf1f265f121c | [
"Apache-2.0"
] | null | null | null | lib/sensor_sht31.ex | elcritch/nerves_sensors | 7cd38e329fcdaa8e2112e195bdfcdf1f265f121c | [
"Apache-2.0"
] | null | null | null | lib/sensor_sht31.ex | elcritch/nerves_sensors | 7cd38e329fcdaa8e2112e195bdfcdf1f265f121c | [
"Apache-2.0"
] | null | null | null | defmodule Sensors.Sht31 do
use Bitwise
@sht31_default_addr 0x44
@sht31_meas_highrep_stretch <<0x2C, 0x06>>
@sht31_meas_medrep_stretch <<0x2C, 0x0D>>
@sht31_meas_lowrep_stretch <<0x2C, 0x10>>
@sht31_meas_highrep <<0x24, 0x00>>
@sht31_meas_medrep <<0x24, 0x0B>>
@sht31_meas_lowrep <<0x24, 0x16>>
@sht31_readstatus <<0xF3, 0x2D>>
@sht31_clearstatus <<0x30, 0x41>>
@sht31_softreset <<0x30, 0xA2>>
@sht31_heateren <<0x30, 0x6D>>
@sht31_heaterdis <<0x30, 0x66>>
# Inspired by: https://github.com/adafruit/Adafruit_SHT31/blob/master/Adafruit_SHT31.cpp
# SHT31 Reference: https://www.sensirion.com/fileadmin/user_upload/customers/sensirion/Dokumente/Humidity_Sensors/Sensirion_Humidity_Sensors_SHT3x_Datasheet_digital.pdf
def init do
{:ok, pid} = I2c.start_link("i2c-1", @sht31_default_addr)
pid
end
def reset(pid) do
I2c.write(pid, @sht31_softreset);
Process.sleep(10);
end
def test do
IO.puts("test")
end
def readStatus(pid) do
I2c.write(pid, @sht31_readstatus);
<< stat :: size(16), stat_crc >> = I2c.read(pid, 3);
stat
end
def heater(pid, enabled) do
if (enabled) do
I2c.write(pid, @sht31_heateren);
else
I2c.write(pid, @sht31_heaterdis);
end
end
def readTempHum(pid) do
I2c.write(pid, @sht31_meas_highrep);
Process.sleep(500);
# Pattern match value into sensor readings, following SHT31 Documentation
<< st :: size(16), st_crc, srh :: size(16), srh_crc >> = reading = I2c.read(pid, 6);
<< st0, st1, _crc1, srh0, srh1, _crc2 >> = reading
temp = { ( st * 175 ) / 0xffff - 45.00, :celsius }
hum = { ( st * 100 ) / 0xffff, :rel_hum }
IO.puts("Raw values: st => #{st}, st_crc => #{st_crc} == #{crc([st0,st1 ])}")
IO.puts("Raw values: srh => #{srh}, srh_crc => #{srh_crc} / #{crc([srh0, srh1])}")
if crc([st0,st1]) == st_crc and crc([srh0,srh1]) == srh_crc do
{:ok, %{ temp: temp, humidity: hum }}
else
{:error, %{ temp_crc: crc([st0,st1]) == st_crc, humidity_crc: crc([srh0,srh1]) == srh_crc }}
end
end
# CRC-8 formula (page 14 of SHT spec pdf)
#
# Initialization data 0xFF
# Polynomial 0x31 (x8 + x5 +x4 +1)
# Final XOR 0x00
def crc(dataList) do
polynomial = 0x31
crc = 0xFF
# Equivalent to outer loop of C++ CRC function
# dataList = data |> Enum.map(fn << x >> -> x end)
checksum = fn _i, crc! ->
if (crc! &&& 0x80) > 0x0 do
(crc! <<< 1) ^^^ polynomial
else
(crc! <<< 1)
end
end
crc! = Enum.reduce dataList, crc, fn data, crc! ->
Enum.reduce(1..8, crc! ^^^ data, checksum)
end
crc! &&& 0xFF # reduce to single byte
end
end
| 27.89 | 170 | 0.601291 |
032b5a3dd42d5d6b71ad628c0dd21ca0d9eecee5 | 1,461 | exs | Elixir | config/config.exs | IgorRodriguez/postoffice | 9012193e0780f2403bd3db90b8f6258656780fee | [
"Apache-2.0"
] | null | null | null | config/config.exs | IgorRodriguez/postoffice | 9012193e0780f2403bd3db90b8f6258656780fee | [
"Apache-2.0"
] | null | null | null | config/config.exs | IgorRodriguez/postoffice | 9012193e0780f2403bd3db90b8f6258656780fee | [
"Apache-2.0"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
use Mix.Config
config :postoffice,
ecto_repos: [Postoffice.Repo],
pubsub_project_name: System.get_env("GCLOUD_PUBSUB_PROJECT_ID", "test")
config :postoffice, PostofficeWeb.Endpoint,
http: [port: 4000],
secret_key_base: "ltXgZliDmN0mLNWAF5iobiRF6G3q96oWvttpWlqb1hahcxgAwcxOGG9R5khNiWy5",
render_errors: [view: PostofficeWeb.ErrorView, accepts: ~w(json)],
pubsub: [name: Postoffice.PubSub, adapter: Phoenix.PubSub.PG2],
root: ".",
instrumenters: [PostofficeWeb.Metrics.Phoenix]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
config :phoenix, :template_engines, leex: Phoenix.LiveView.Engine
{:ok, current_directory} = File.cwd()
dummy_credentials_file = current_directory <> "/secrets/dummy-credentials.json"
config :goth,
json: System.get_env("GCLOUD_PUBSUB_CREDENTIALS_PATH", dummy_credentials_file) |> File.read!()
config :libcluster,
topologies: []
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 33.976744 | 96 | 0.772758 |
032b7a37194f5238ee2d35eb564d91f48a199d65 | 2,001 | exs | Elixir | config/dev.exs | zdenal/contex-samples | 44cfea6f218d7903451839c27bf48f75eb64d943 | [
"MIT"
] | 15 | 2020-01-26T16:46:14.000Z | 2021-07-06T07:27:44.000Z | config/dev.exs | zdenal/contex-samples | 44cfea6f218d7903451839c27bf48f75eb64d943 | [
"MIT"
] | 4 | 2020-01-26T09:06:24.000Z | 2021-10-05T01:41:23.000Z | config/dev.exs | zdenal/contex-samples | 44cfea6f218d7903451839c27bf48f75eb64d943 | [
"MIT"
] | 6 | 2020-05-13T02:00:03.000Z | 2022-02-14T17:55:56.000Z | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :contexsample, ContexSampleWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: [
node: [
"node_modules/webpack/bin/webpack.js",
"--mode",
"development",
"--watch-stdin",
cd: Path.expand("../assets", __DIR__)
]
]
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Watch static and templates for browser reloading.
config :contexsample, ContexSampleWeb.Endpoint,
live_reload: [
interval: 1000,
patterns: [
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/contexsample_web/views/.*(ex)$",
~r"lib/contexsample_web/live/.*(ex)$",
~r"lib/contexsample_web/templates/.*(eex)$"
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 28.585714 | 68 | 0.685657 |
032b97bfcce2ab4d25825df78460222a4bc3b25c | 699 | exs | Elixir | test/bump_test.exs | carlo-colombo/ex_bump | 0bed8f63d17025394e20e3f865e1b38a390f2f48 | [
"MIT"
] | 5 | 2015-04-21T01:15:13.000Z | 2021-03-14T20:57:02.000Z | test/bump_test.exs | carlo-colombo/ex_bump | 0bed8f63d17025394e20e3f865e1b38a390f2f48 | [
"MIT"
] | null | null | null | test/bump_test.exs | carlo-colombo/ex_bump | 0bed8f63d17025394e20e3f865e1b38a390f2f48 | [
"MIT"
] | 3 | 2016-12-02T01:10:11.000Z | 2022-03-17T22:06:03.000Z | defmodule BumpTest do
use ExUnit.Case
test "it interprets the height and width when given a properly dense matrix" do
Bump.write(filename: "_build/4x4.bmp", pixel_data: [[[0xFF,0xFF,0xFF],[0x00,0x00,0x00]],[[0x00,0x00,0x00],[0xFF,0xFF,0xFF]]])
{:ok, test_file} = File.read "_build/4x4.bmp"
{:ok, fixture_file} = File.read "test/fixtures/4x4.bmp"
assert(fixture_file == test_file)
end
test "it reads in pixel data" do
expected_pixel_data = [[[0x00,0x00,0x00],[0xFF,0xFF,0xFF]],[[0xFF,0xFF,0xFF],[0x00,0x00,0x00]]]
Bump.write(filename: "_build/4x4.bmp", pixel_data: expected_pixel_data)
assert(expected_pixel_data == Bump.pixel_data("_build/4x4.bmp"))
end
end
| 38.833333 | 129 | 0.701001 |
032ba1c65f95f5e5842aa6493192d30883fb271f | 1,829 | ex | Elixir | lib/cforum_web/views/forum_view.ex | campingrider/cforum_ex | cf27684c47d6dc26c9c37a946f1c729a79d27c70 | [
"MIT"
] | null | null | null | lib/cforum_web/views/forum_view.ex | campingrider/cforum_ex | cf27684c47d6dc26c9c37a946f1c729a79d27c70 | [
"MIT"
] | null | null | null | lib/cforum_web/views/forum_view.ex | campingrider/cforum_ex | cf27684c47d6dc26c9c37a946f1c729a79d27c70 | [
"MIT"
] | null | null | null | defmodule CforumWeb.ForumView do
use CforumWeb, :view
def page_title(:index, _), do: gettext("forums")
def page_title(:stats, %{current_forum: forum}) when not is_nil(forum),
do: gettext("forum statistics for forum „%{forum}“", forum: forum.name)
def page_title(:stats, _), do: gettext("forum statistics for all forums")
def page_heading(:stats, assigns), do: page_title(:stats, assigns)
def body_id(:index, _), do: "forums-index"
def body_id(:stats, _), do: "forums-stats"
def body_classes(:index, _), do: "forums index"
def body_classes(:stats, _), do: "forums stats"
def day_name_last_week() do
Timex.now()
|> Timex.subtract(Timex.Duration.from_days(7))
|> Timex.format!("%A", :strftime)
end
def state_heading(:today), do: gettext("state today")
def state_heading(:last_week), do: gettext("state %{day} last week", day: day_name_last_week())
def state_heading(:week), do: gettext("state of the last seven days")
def state_heading(:month), do: gettext("state of the last 30 days")
def state_heading(:year), do: gettext("state of the last 360 days")
def stats_json(stats) do
{:safe,
stats
|> Enum.map(fn {mon, threads, messages} ->
%{mon: Timex.lformat!(mon, "%FT%T%:z", "en", :strftime), threads: threads, messages: messages}
end)
|> Jason.encode!()}
end
def user_json(users) do
{:safe,
users
|> Enum.map(fn {mon, users} ->
%{mon: Timex.lformat!(mon, "%FT%T%:z", "en", :strftime), cnt: users}
end)
|> Jason.encode!()}
end
def posting_date(conn, message) do
if Timex.diff(Timex.now(), message.created_at, :days) < 1,
do: Timex.format!(VHelpers.local_date(message.created_at), "%H:%M", :strftime),
else: VHelpers.format_date(conn, message.created_at, "date_format_index")
end
end
| 33.254545 | 101 | 0.656096 |
032ba398b0b3c8c412001dc80bbe15bb9eb42b61 | 6,494 | ex | Elixir | lib/cryptozaur/connectors/yobit.ex | DenisGorbachev/crypto-cli | 94e5097ff24237fbc5fdd3fea371a5c9a1f727e4 | [
"MIT"
] | 5 | 2018-09-19T09:13:15.000Z | 2021-10-20T23:29:57.000Z | lib/cryptozaur/connectors/yobit.ex | DenisGorbachev/crypto-cli | 94e5097ff24237fbc5fdd3fea371a5c9a1f727e4 | [
"MIT"
] | 6 | 2018-07-29T05:33:02.000Z | 2018-09-18T20:42:19.000Z | lib/cryptozaur/connectors/yobit.ex | DenisGorbachev/crypto-cli | 94e5097ff24237fbc5fdd3fea371a5c9a1f727e4 | [
"MIT"
] | 3 | 2018-07-24T05:55:04.000Z | 2018-09-19T09:14:08.000Z | # Rate limit: 100 req/min (~1.6 req/sec)
defmodule Cryptozaur.Connectors.Yobit do
import OK, only: [success: 1, failure: 1]
alias Cryptozaur.Drivers.YobitRest, as: Rest
def credentials_valid?(key, secret) do
with success(rest) <- Cryptozaur.DriverSupervisor.get_driver(key, secret, Rest) do
case Rest.get_info(rest) do
success(_) -> success(true)
failure("invalid key, sign, method or nonce") -> success(false)
failure(message) -> failure(message)
end
end
end
# def pair_valid?(base, quote) do
# with success(rest) <- Cryptozaur.DriverSupervisor.get_public_driver(Rest)
# do
# case Rest.get_order_book(rest, base, quote) do
# success(_) -> success(true)
# failure("INVALID_MARKET") -> success(false)
# failure(message) -> failure(message)
# end
# end
# end
# def get_latest_trades(base, quote) do
# OK.for do
# rest <- Cryptozaur.DriverSupervisor.get_public_driver(Rest)
# trades <- Rest.get_latest_trades(rest, base, quote)
# symbol = to_symbol(base, quote)
# result = Enum.map trades, &(to_trade(symbol, &1))
# after
# result
# end
# end
#
# def place_order(key, secret, base, quote, amount, price, extra \\ %{}) do
# OK.for do
# rest <- Cryptozaur.DriverSupervisor.get_driver(key, secret, Rest)
# %{"uuid" => uuid} <- if amount > 0 do
# Rest.buy_limit(rest, base, quote, amount, price)
# else
# Rest.sell_limit(rest, base, quote, -amount, price)
# end
# after
# uuid
# end
# end
#
# def cancel_order(key, secret, uid) do
# OK.try do
# rest <- Cryptozaur.DriverSupervisor.get_driver(key, secret, Rest)
# nil <- Rest.cancel(rest, uid)
# after
# success(uid)
# rescue
# "ORDER_NOT_OPEN" ->
# {:error, :order_not_open}
# end
# end
#
# def get_orders(key, secret) do
# OK.for do
# rest <- Cryptozaur.DriverSupervisor.get_driver(key, secret, Rest)
# info <- Rest.get_info(rest)
# result = info["orders"]
# # check that all open_orders have "Closed" => nil
## orders |> Enum.each(fn(order) -> %{"Closed" => nil} = order end)
## closed_orders <- Rest.get_order_history(rest)
## result =
## Enum.map(open_orders, &to_order_from_opened_order/1)
## ++
## Enum.map(closed_orders, &to_order_from_closed_order/1)
# after
# result
# end
# end
#
# def get_levels(base, quote) do
# OK.for do
# rest <- Cryptozaur.DriverSupervisor.get_public_driver(Rest)
# levels <- Rest.get_order_book(rest, base, quote)
# symbol = to_symbol(base, quote)
#
# timestamp = Cryptozaur.Utils.now()
#
# buys = Enum.map(levels["buy"], &(to_level(symbol, 1, timestamp, &1)))
# sells = Enum.map(levels["sell"], &(to_level(symbol, -1, timestamp, &1)))
# after
# {buys, sells}
# end
# end
#
# defp to_trade(symbol, %{"Id" => id, "TimeStamp" => timestamp_string, "Quantity" => amount, "Price" => price, "OrderType" => type}) do
# sign = case type do
# "BUY" -> 1
# "SELL" -> -1
# end
#
# timestamp = parse_timestamp(timestamp_string)
#
# %Trade{uid: Integer.to_string(id), symbol: symbol, timestamp: timestamp, amount: amount * sign, price: price}
# end
#
# defp to_level(symbol, sign, timestamp, %{"Quantity" => amount, "Rate" => price}) do
# %Level{price: price, amount: sign * amount, symbol: symbol, timestamp: timestamp}
# end
#
# defp to_order_from_closed_order(proto) do
# order = to_order(proto)
# Map.put(order, :status, "closed")
# end
#
# defp to_order_from_opened_order(proto) do
# proto = Map.put(proto, "TimeStamp", proto["Opened"])
# order = to_order(proto)
# Map.put(order, :status, "opened")
# end
#
# defp to_order(%{
# "OrderUuid" => uid,
# "Exchange" => pair_in_yobit_format,
# "Limit" => price, # It looks like Yobit uses "PricePerUnit" as "actual price that you've got" (in case limit order turned into a market order)
# "TimeStamp" => timestamp_string,
# "Quantity" => amount_requested,
# "QuantityRemaining" => amount_remaining,
# "OrderType" => type
# }) do
# sign = case type do
# "LIMIT_BUY" -> 1
# "LIMIT_SELL" -> -1
# end
#
# [quote, base] = String.split(pair_in_yobit_format, "-")
# pair = to_pair(base, quote)
#
# timestamp = parse_timestamp(timestamp_string)
# amount_filled = amount_requested - amount_remaining
#
# %Order{
# uid: uid,
# pair: pair,
# price: price,
# amount_requested: amount_requested * sign,
# amount_filled: amount_filled * sign,
# status: "closed",
# timestamp: timestamp
# }
# end
#
# def validate_order(_base, quote, price, amount) do
# validate_dust_order(quote, price, amount)
# end
#
# defp validate_dust_order("BTC" = base, price, amount) do
# if price * amount >= @btc_dust_threshold do
# success(nil)
# else
# min = Float.ceil(@btc_dust_threshold / price, get_amount_precision(base))
# failure([%{key: "amount", message: "Minimum order amount at specified price is #{min} #{base}"}])
# end
# end
#
# defp validate_dust_order(_base, _price, _amount) do
# success(nil)
# # raise ~s'validate_order does NOT support "#{base}" quote'
# end
def get_min_price(_base, quote) do
case quote do
"BTC" -> 0.00000001
"ETH" -> 0.00000001
"USDT" -> 0.00000001
end
end
def get_min_amount(base, price) do
# DUST_TRADE_DISALLOWED_MIN_VALUE_50K_SAT
case base do
_ -> 0.00050000 / price
end
end
def get_amount_precision(base, _quote) do
case base do
_ -> 8
end
end
def get_price_precision(_base, quote) do
case quote do
_ -> 8
end
end
def get_tick(_base, quote) do
case quote do
_ -> 0.00000001
end
end
def get_link(base, quote) do
"https://yobit.com/Market/Index?MarketName=#{quote}-#{base}"
end
# defp to_symbol(base, quote) do
# "YOBIT:#{to_pair(base, quote)}"
# end
# defp to_pair(base, quote) do
# "#{base}:#{quote}"
# end
# defp parse_timestamp(string) do
# NaiveDateTime.from_iso8601!(string)
# end
end
| 29.518182 | 149 | 0.594087 |
032ba43f6fbd1f7834c164fccab3034021786f09 | 998 | ex | Elixir | server/lib/realtime/rls/subscriptions/subscription.ex | profencer/realtime | b3a20e8278276a98d47c2c938abe73cfd9e69a63 | [
"Apache-2.0"
] | 1 | 2020-06-03T10:49:40.000Z | 2020-06-03T10:49:40.000Z | server/lib/realtime/rls/subscriptions/subscription.ex | profencer/realtime | b3a20e8278276a98d47c2c938abe73cfd9e69a63 | [
"Apache-2.0"
] | null | null | null | server/lib/realtime/rls/subscriptions/subscription.ex | profencer/realtime | b3a20e8278276a98d47c2c938abe73cfd9e69a63 | [
"Apache-2.0"
] | null | null | null | defmodule Realtime.RLS.Subscriptions.Subscription do
use Ecto.Schema
import Ecto.Changeset
alias Realtime.RLS.Subscriptions.Subscription.Filters
@schema_prefix "realtime"
@primary_key {:id, :id, autogenerate: true}
schema "subscription" do
field(:subscription_id, Ecto.UUID)
field(:entity, :integer)
field(:filters, Filters)
field(:claims, :map)
field(:claims_role, :string, virtual: true)
field(:created_at, :utc_datetime_usec)
end
def changeset(subscription, attrs) do
subscription
|> cast(attrs, [:subscription_id, :entity, :filters, :claims, :claims_role, :created_at])
|> validate_required([:subscription_id, :entity, :filters, :claims, :claims_role])
|> validate_claims_map()
|> delete_change(:claims_role)
end
defp validate_claims_map(%Ecto.Changeset{changes: %{claims: %{"role" => _}}} = changeset),
do: changeset
defp validate_claims_map(changeset), do: add_error(changeset, :claims, "claims is missing role")
end
| 32.193548 | 98 | 0.716433 |
032bb7deda1c5b18d315a210e78a80d6c4ec2641 | 836 | ex | Elixir | lib/ptv/call.ex | jmargenberg/elixir-ptv | d5b50eca5c7ffc6d7beb68d2565ac1ae6dc8f0bd | [
"MIT"
] | 2 | 2019-02-26T08:05:19.000Z | 2019-05-30T00:16:00.000Z | lib/ptv/call.ex | jmargenberg/elixir-ptv | d5b50eca5c7ffc6d7beb68d2565ac1ae6dc8f0bd | [
"MIT"
] | null | null | null | lib/ptv/call.ex | jmargenberg/elixir-ptv | d5b50eca5c7ffc6d7beb68d2565ac1ae6dc8f0bd | [
"MIT"
] | null | null | null | defmodule PTV.Call do
@moduledoc """
Struct representing a call to the PTV API.
Strictly conforms to spec at https://timetableapi.ptv.vic.gov.au/swagger/ui/index.
* `:base_url`: the base url of the API server, defaults to `"http://timetableapi.ptv.vic.gov.au"`.
* `:api_version`: the version of the api being called, defaults to `"v3"`.
* `:api_name`: the name of the resource being called, .e.g. `"stops"`.
* `:search_string`: id or further path of the resource being called, .e.g `"10/route_type/3"`
* `:params`: map of query paramters, .e.g `%{stop_amenities: true}`
"""
@ptv_base_url "http://timetableapi.ptv.vic.gov.au"
@ptv_api_vesion "v3"
defstruct base_url: @ptv_base_url,
api_version: @ptv_api_vesion,
api_name: "",
search_string: "",
params: %{}
end
| 36.347826 | 100 | 0.651914 |
032bb7e9e9d3b21f6eb03aacd1b4e61a9dd86b56 | 565 | ex | Elixir | web/models/commit.ex | joakimk/exremit | 6c0a5fb32208b98cc1baac11d6a7bd248a1aa3bc | [
"Unlicense",
"MIT"
] | 27 | 2016-09-21T09:11:25.000Z | 2020-12-16T04:04:50.000Z | web/models/commit.ex | barsoom/exremit | 6c0a5fb32208b98cc1baac11d6a7bd248a1aa3bc | [
"Unlicense",
"MIT"
] | 2 | 2016-12-02T08:05:13.000Z | 2020-03-27T08:07:59.000Z | web/models/commit.ex | barsoom/exremit | 6c0a5fb32208b98cc1baac11d6a7bd248a1aa3bc | [
"Unlicense",
"MIT"
] | 4 | 2016-09-25T09:58:17.000Z | 2020-04-27T15:07:36.000Z | defmodule Review.Commit do
use Review.Web, :model
schema "commits" do
field :sha, :string
# This is the yaml payload the ruby app uses. It's difficult to load in elixir since is uses special syntax for symbols.
field :payload, :string
field :json_payload, :string
field :reviewed_at, Ecto.DateTime
field :review_started_at, Ecto.DateTime
timestamps inserted_at: :created_at
belongs_to :author, Review.Author
belongs_to :reviewed_by_author, Review.Author
belongs_to :review_started_by_author, Review.Author
end
end
| 26.904762 | 124 | 0.738053 |
032bf565b7676c243bd18e9f8b896825b7da4fce | 28,371 | exs | Elixir | lib/elixir/test/elixir/string_test.exs | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/string_test.exs | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/string_test.exs | kevsmith/elixir | 74825645e8cac770708f45139e651fd9d4e4264c | [
"Apache-2.0"
] | null | null | null | Code.require_file "test_helper.exs", __DIR__
defmodule StringTest do
use ExUnit.Case, async: true
doctest String
test "next codepoint" do
assert String.next_codepoint("ésoj") == {"é", "soj"}
assert String.next_codepoint(<<255>>) == {<<255>>, ""}
assert String.next_codepoint("") == nil
end
# test cases described in http://mortoray.com/2013/11/27/the-string-type-is-broken/
test "Unicode" do
assert String.reverse("noël") == "lëon"
assert String.slice("noël", 0..2) == "noë"
assert String.length("noël") == 4
assert String.length("") == 2
assert String.slice("", 1..1) == ""
assert String.reverse("") == ""
assert String.upcase("baffle") == "BAFFLE"
assert String.equivalent?("noël", "noël")
end
test "split" do
assert String.split("") == []
assert String.split("foo bar") == ["foo", "bar"]
assert String.split(" foo bar") == ["foo", "bar"]
assert String.split("foo bar ") == ["foo", "bar"]
assert String.split(" foo bar ") == ["foo", "bar"]
assert String.split("foo\t\n\v\f\r\sbar\n") == ["foo", "bar"]
assert String.split("foo" <> <<194, 133>> <> "bar") == ["foo", "bar"]
# information separators are not considered whitespace
assert String.split("foo\u001Fbar") == ["foo\u001Fbar"]
# no-break space is excluded
assert String.split("foo\00A0bar") == ["foo\00A0bar"]
assert String.split("foo\u202Fbar") == ["foo\u202Fbar"]
assert String.split("a,b,c", ",") == ["a", "b", "c"]
assert String.split("a,b", ".") == ["a,b"]
assert String.split("1,2 3,4", [" ", ","]) == ["1", "2", "3", "4"]
assert String.split("", ",") == [""]
assert String.split(" a b c ", " ") == ["", "a", "b", "c", ""]
assert String.split(" a b c ", " ", parts: :infinity) == ["", "a", "b", "c", ""]
assert String.split(" a b c ", " ", parts: 1) == [" a b c "]
assert String.split(" a b c ", " ", parts: 2) == ["", "a b c "]
assert String.split("", ",", trim: true) == []
assert String.split(" a b c ", " ", trim: true) == ["a", "b", "c"]
assert String.split(" a b c ", " ", trim: true, parts: :infinity) == ["a", "b", "c"]
assert String.split(" a b c ", " ", trim: true, parts: 1) == [" a b c "]
assert String.split(" a b c ", " ", trim: true, parts: 2) == ["a", "b c "]
assert String.split("abé", "") == ["a", "b", "é", ""]
assert String.split("abé", "", parts: :infinity) == ["a", "b", "é", ""]
assert String.split("abé", "", parts: 1) == ["abé"]
assert String.split("abé", "", parts: 2) == ["a", "bé"]
assert String.split("abé", "", parts: 10) == ["a", "b", "é", ""]
assert String.split("abé", "", trim: true) == ["a", "b", "é"]
assert String.split("abé", "", trim: true, parts: :infinity) == ["a", "b", "é"]
assert String.split("abé", "", trim: true, parts: 2) == ["a", "bé"]
assert String.split("noël", "") == ["n", "o", "ë", "l", ""]
end
test "split with regex" do
assert String.split("", ~r{,}) == [""]
assert String.split("", ~r{,}, trim: true) == []
assert String.split("a,b", ~r{,}) == ["a", "b"]
assert String.split("a,b,c", ~r{,}) == ["a", "b", "c"]
assert String.split("a,b,c", ~r{,}, parts: 2) == ["a", "b,c"]
assert String.split("a,b.c ", ~r{\W}) == ["a", "b", "c", ""]
assert String.split("a,b.c ", ~r{\W}, trim: false) == ["a", "b", "c", ""]
assert String.split("a,b", ~r{\.}) == ["a,b"]
end
test "splitter" do
assert String.splitter("a,b,c", ",") |> Enum.to_list == ["a", "b", "c"]
assert String.splitter("a,b", ".") |> Enum.to_list == ["a,b"]
assert String.splitter("1,2 3,4", [" ", ","]) |> Enum.to_list == ["1", "2", "3", "4"]
assert String.splitter("", ",") |> Enum.to_list == [""]
assert String.splitter("", ",", trim: true) |> Enum.to_list == []
assert String.splitter(" a b c ", " ", trim: true) |> Enum.to_list == ["a", "b", "c"]
assert String.splitter(" a b c ", " ", trim: true) |> Enum.take(1) == ["a"]
assert String.splitter(" a b c ", " ", trim: true) |> Enum.take(2) == ["a", "b"]
end
test "split at" do
assert String.split_at("", 0) == {"", ""}
assert String.split_at("", -1) == {"", ""}
assert String.split_at("", 1) == {"", ""}
assert String.split_at("abc", 0) == {"", "abc"}
assert String.split_at("abc", 2) == {"ab", "c"}
assert String.split_at("abc", 3) == {"abc", ""}
assert String.split_at("abc", 4) == {"abc", ""}
assert String.split_at("abc", 1000) == {"abc", ""}
assert String.split_at("abc", -1) == {"ab", "c"}
assert String.split_at("abc", -3) == {"", "abc"}
assert String.split_at("abc", -4) == {"", "abc"}
assert String.split_at("abc", -1000) == {"", "abc"}
assert_raise FunctionClauseError, fn ->
String.split_at("abc", 0.1)
end
assert_raise FunctionClauseError, fn ->
String.split_at("abc", -0.1)
end
end
test "upcase" do
assert String.upcase("123 abcd 456 efg hij ( %$#) kl mnop @ qrst = -_ uvwxyz") == "123 ABCD 456 EFG HIJ ( %$#) KL MNOP @ QRST = -_ UVWXYZ"
assert String.upcase("") == ""
assert String.upcase("abcD") == "ABCD"
end
test "upcase utf8" do
assert String.upcase("& % # àáâ ãäå 1 2 ç æ") == "& % # ÀÁÂ ÃÄÅ 1 2 Ç Æ"
assert String.upcase("àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ") == "ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ"
end
test "upcase utf8 multibyte" do
assert String.upcase("straße") == "STRASSE"
assert String.upcase("áüÈß") == "ÁÜÈSS"
end
test "downcase" do
assert String.downcase("123 ABcD 456 EfG HIJ ( %$#) KL MNOP @ QRST = -_ UVWXYZ") == "123 abcd 456 efg hij ( %$#) kl mnop @ qrst = -_ uvwxyz"
assert String.downcase("abcD") == "abcd"
assert String.downcase("") == ""
end
test "downcase utf8" do
assert String.downcase("& % # ÀÁÂ ÃÄÅ 1 2 Ç Æ") == "& % # àáâ ãäå 1 2 ç æ"
assert String.downcase("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝÞ") == "àáâãäåæçèéêëìíîïðñòóôõöøùúûüýþ"
assert String.downcase("áüÈß") == "áüèß"
end
test "capitalize" do
assert String.capitalize("") == ""
assert String.capitalize("abc") == "Abc"
assert String.capitalize("ABC") == "Abc"
assert String.capitalize("c b a") == "C b a"
assert String.capitalize("1ABC") == "1abc"
assert String.capitalize("_aBc1") == "_abc1"
assert String.capitalize(" aBc1") == " abc1"
end
test "capitalize utf8" do
assert String.capitalize("àáâ") == "Àáâ"
assert String.capitalize("ÀÁÂ") == "Àáâ"
assert String.capitalize("âáà") == "Âáà"
assert String.capitalize("ÂÁÀ") == "Âáà"
assert String.capitalize("òóôõö") == "Òóôõö"
assert String.capitalize("ÒÓÔÕÖ") == "Òóôõö"
assert String.capitalize("fin") == "Fin"
end
test "replace_leading" do
assert String.replace_leading("aa abc ", "a", "b") == "bb abc "
assert String.replace_leading("__ abc ", "_", "b") == "bb abc "
assert String.replace_leading("aaaaaaaa ", "a", "b") == "bbbbbbbb "
assert String.replace_leading("aaaaaaaa ", "aaa", "b") == "bbaa "
assert String.replace_leading("aaaaaaaaa", "a", "b") == "bbbbbbbbb"
assert String.replace_leading("]]]]]]", "]", "[]") == "[][][][][][]"
assert String.replace_leading("]]]]]]]]", "]", "") == ""
assert String.replace_leading("]]]]]] ]", "]", "") == " ]"
assert String.replace_leading("猫猫 cat ", "猫", "й") == "йй cat "
assert String.replace_leading("test", "t", "T") == "Test"
assert String.replace_leading("t", "t", "T") == "T"
assert String.replace_leading("aaa", "b", "c") == "aaa"
message = ~r/cannot use an empty string/
assert_raise ArgumentError, message, fn ->
String.replace_leading("foo", "", "bar")
end
assert_raise ArgumentError, message, fn ->
String.replace_leading("", "", "bar")
end
end
test "replace_trailing" do
assert String.replace_trailing(" abc aa", "a", "b") == " abc bb"
assert String.replace_trailing(" abc __", "_", "b") == " abc bb"
assert String.replace_trailing(" aaaaaaaa", "a", "b") == " bbbbbbbb"
assert String.replace_trailing(" aaaaaaaa", "aaa", "b") == " aabb"
assert String.replace_trailing("aaaaaaaaa", "a", "b") == "bbbbbbbbb"
assert String.replace_trailing("]]]]]]", "]", "[]") == "[][][][][][]"
assert String.replace_trailing("]]]]]]]]", "]", "") == ""
assert String.replace_trailing("] ]]]]]]", "]", "") == "] "
assert String.replace_trailing(" cat 猫猫", "猫", "й") == " cat йй"
assert String.replace_trailing("test", "t", "T") == "tesT"
assert String.replace_trailing("t", "t", "T") == "T"
assert String.replace_trailing("aaa", "b", "c") == "aaa"
message = ~r/cannot use an empty string/
assert_raise ArgumentError, message, fn ->
String.replace_trailing("foo", "", "bar")
end
assert_raise ArgumentError, message, fn ->
String.replace_trailing("", "", "bar")
end
end
test "trim" do
assert String.trim("") == ""
assert String.trim(" abc ") == "abc"
assert String.trim("a abc a\n\n") == "a abc a"
assert String.trim("a abc a\t\n\v\f\r\s") == "a abc a"
assert String.trim("___ abc ___", "_") == " abc "
assert String.trim("猫猫猫cat猫猫猫", "猫猫") == "猫cat猫"
# no-break space
assert String.trim("\u00A0a abc a\u00A0") == "a abc a"
# whitespace defined as a range
assert String.trim("\u2008a abc a\u2005") == "a abc a"
end
test "trim_leading" do
assert String.trim_leading("") == ""
assert String.trim_leading(" abc ") == "abc "
assert String.trim_leading("a abc a") == "a abc a"
assert String.trim_leading("\n\na abc a") == "a abc a"
assert String.trim_leading("\t\n\v\f\r\sa abc a") == "a abc a"
assert String.trim_leading(<<194, 133, "a abc a">>) == "a abc a"
# information separators are not whitespace
assert String.trim_leading("\u001F a abc a") == "\u001F a abc a"
# no-break space
assert String.trim_leading("\u00A0 a abc a") == "a abc a"
assert String.trim_leading("aa aaa", "aaa") == "aa aaa"
assert String.trim_leading("aaa aaa", "aa") == "a aaa"
assert String.trim_leading("aa abc ", "a") == " abc "
assert String.trim_leading("__ abc ", "_") == " abc "
assert String.trim_leading("aaaaaaaaa ", "a") == " "
assert String.trim_leading("aaaaaaaaaa", "a") == ""
assert String.trim_leading("]]]]]] ]", "]") == " ]"
assert String.trim_leading("猫猫 cat ", "猫") == " cat "
assert String.trim_leading("test", "t") == "est"
assert String.trim_leading("t", "t") == ""
assert String.trim_leading("", "t") == ""
end
test "trim_trailing" do
assert String.trim_trailing("") == ""
assert String.trim_trailing("1\n") == "1"
assert String.trim_trailing("\r\n") == ""
assert String.trim_trailing(" abc ") == " abc"
assert String.trim_trailing(" abc a") == " abc a"
assert String.trim_trailing("a abc a\n\n") == "a abc a"
assert String.trim_trailing("a abc a\t\n\v\f\r\s") == "a abc a"
assert String.trim_trailing(<<"a abc a", 194, 133>>) == "a abc a"
# information separators are not whitespace
assert String.trim_trailing("a abc a \u001F") == "a abc a \u001F"
# no-break space
assert String.trim_trailing("a abc a \u00A0") == "a abc a"
assert String.trim_trailing("aaa aa", "aaa") == "aaa aa"
assert String.trim_trailing("aaa aaa", "aa") == "aaa a"
assert String.trim_trailing(" abc aa", "a") == " abc "
assert String.trim_trailing(" abc __", "_") == " abc "
assert String.trim_trailing(" aaaaaaaaa", "a") == " "
assert String.trim_trailing("aaaaaaaaaa", "a") == ""
assert String.trim_trailing("] ]]]]]]", "]") == "] "
assert String.trim_trailing(" cat 猫猫", "猫") == " cat "
assert String.trim_trailing("test", "t") == "tes"
assert String.trim_trailing("t", "t") == ""
assert String.trim_trailing("", "t") == ""
end
test "pad_leading" do
assert String.pad_leading("", 5) == " "
assert String.pad_leading("abc", 5) == " abc"
assert String.pad_leading(" abc ", 9) == " abc "
assert String.pad_leading("猫", 5) == " 猫"
assert String.pad_leading("-", 0) == "-"
assert String.pad_leading("-", 1) == "-"
assert String.pad_leading("---", 5, "abc") == "ab---"
assert String.pad_leading("---", 9, "abc") == "abcabc---"
assert String.pad_leading("---", 5, ["abc"]) == "abcabc---"
assert String.pad_leading("--", 6, ["a", "bc"]) == "abcabc--"
assert_raise FunctionClauseError, fn ->
String.pad_leading("-", -1)
end
assert_raise FunctionClauseError, fn ->
String.pad_leading("-", 1, [])
end
message = "expected a string padding element, got: 10"
assert_raise ArgumentError, message, fn ->
String.pad_leading("-", 3, ["-", 10])
end
end
test "pad_trailing" do
assert String.pad_trailing("", 5) == " "
assert String.pad_trailing("abc", 5) == "abc "
assert String.pad_trailing(" abc ", 9) == " abc "
assert String.pad_trailing("猫", 5) == "猫 "
assert String.pad_trailing("-", 0) == "-"
assert String.pad_trailing("-", 1) == "-"
assert String.pad_trailing("---", 5, "abc") == "---ab"
assert String.pad_trailing("---", 9, "abc") == "---abcabc"
assert String.pad_trailing("---", 5, ["abc"]) == "---abcabc"
assert String.pad_trailing("--", 6, ["a", "bc"]) == "--abcabc"
assert_raise FunctionClauseError, fn ->
String.pad_trailing("-", -1)
end
assert_raise FunctionClauseError, fn ->
String.pad_trailing("-", 1, [])
end
message = "expected a string padding element, got: 10"
assert_raise ArgumentError, message, fn ->
String.pad_trailing("-", 3, ["-", 10])
end
end
test "reverse" do
assert String.reverse("") == ""
assert String.reverse("abc") == "cba"
assert String.reverse("Hello World") == "dlroW olleH"
assert String.reverse("Hello ∂og") == "go∂ olleH"
assert String.reverse("Ā̀stute") == "etutsĀ̀"
assert String.reverse(String.reverse("Hello World")) == "Hello World"
assert String.reverse(String.reverse("Hello \r\n World")) == "Hello \r\n World"
end
test "replace" do
assert String.replace("a,b,c", ",", "-") == "a-b-c"
assert String.replace("a,b,c", [",", "b"], "-") == "a---c"
assert String.replace("a,b,c", ",", "-", global: false) == "a-b,c"
assert String.replace("a,b,c", [",", "b"], "-", global: false) == "a-b,c"
assert String.replace("ãéã", "é", "e", global: false) == "ãeã"
assert String.replace("a,b,c", ",", "[]", insert_replaced: 2) == "a[],b[],c"
assert String.replace("a,b,c", ",", "[]", insert_replaced: [1, 1]) == "a[,,]b[,,]c"
assert String.replace("a,b,c", "b", "[]", insert_replaced: 1, global: false) == "a,[b],c"
assert String.replace("a,b,c", ~r/,(.)/, ",\\1\\1") == "a,bb,cc"
assert String.replace("a,b,c", ~r/,(.)/, ",\\1\\1", global: false) == "a,bb,c"
end
test "duplicate" do
assert String.duplicate("abc", 0) == ""
assert String.duplicate("abc", 1) == "abc"
assert String.duplicate("abc", 2) == "abcabc"
assert String.duplicate("&ã$", 2) == "&ã$&ã$"
assert_raise FunctionClauseError, fn ->
String.duplicate("abc", -1)
end
end
test "codepoints" do
assert String.codepoints("elixir") == ["e", "l", "i", "x", "i", "r"]
assert String.codepoints("elixír") == ["e", "l", "i", "x", "í", "r"] # slovak
assert String.codepoints("ոգելից ըմպելիք") == ["ո", "գ", "ե", "լ", "ի", "ց", " ", "ը", "մ", "պ", "ե", "լ", "ի", "ք"] # armenian
assert String.codepoints("эліксір") == ["э", "л", "і", "к", "с", "і", "р"] # belarussian
assert String.codepoints("ελιξήριο") == ["ε", "λ", "ι", "ξ", "ή", "ρ", "ι", "ο"] # greek
assert String.codepoints("סם חיים") == ["ס", "ם", " ", "ח", "י", "י", "ם"] # hebraic
assert String.codepoints("अमृत") == ["अ", "म", "ृ", "त"] # hindi
assert String.codepoints("স্পর্শমণি") == ["স", "্", "প", "র", "্", "শ", "ম", "ণ", "ি"] # bengali
assert String.codepoints("સર્વશ્રેષ્ઠ ઇલાજ") == ["સ", "ર", "્", "વ", "શ", "્", "ર", "ે", "ષ", "્", "ઠ", " ", "ઇ", "લ", "ા", "જ"] # gujarati
assert String.codepoints("世界中の一番") == ["世", "界", "中", "の", "一", "番"] # japanese
assert String.codepoints("がガちゃ") == ["が", "ガ", "ち", "ゃ"]
assert String.codepoints("") == []
assert String.codepoints("ϖͲϥЫݎߟΈټϘለДШव׆ש؇؊صلټܗݎޥޘ߉ऌ૫ሏᶆ℆ℙℱ ⅚Ⅷ↠∈⌘①ffi") ==
["ϖ", "Ͳ", "ϥ", "Ы", "ݎ", "ߟ", "Έ", "ټ", "Ϙ", "ለ", "Д", "Ш", "व", "׆", "ש", "؇", "؊", "ص", "ل", "ټ", "ܗ", "ݎ", "ޥ", "ޘ", "߉", "ऌ", "૫", "ሏ", "ᶆ", "℆", "ℙ", "ℱ", " ", "⅚", "Ⅷ", "↠", "∈", "⌘", "①", "ffi"]
end
test "equivalent?" do
assert String.equivalent?("", "")
assert String.equivalent?("elixir", "elixir")
assert String.equivalent?("뢴", "뢴")
assert String.equivalent?("ṩ", "ṩ")
refute String.equivalent?("ELIXIR", "elixir")
refute String.equivalent?("døge", "dóge")
end
test "normalize" do
assert String.normalize("ŝ", :nfd) == "ŝ"
assert String.normalize("ḇravô", :nfd) == "ḇravô"
assert String.normalize("ṩierra", :nfd) == "ṩierra"
assert String.normalize("뢴", :nfd) == "뢴"
assert String.normalize("êchǭ", :nfc) == "êchǭ"
assert String.normalize("거̄", :nfc) == "거̄"
assert String.normalize("뢴", :nfc) == "뢴"
## Cases from NormalizationTest.txt
# 05B8 05B9 05B1 0591 05C3 05B0 05AC 059F
# 05B1 05B8 05B9 0591 05C3 05B0 05AC 059F
# HEBREW POINT QAMATS, HEBREW POINT HOLAM, HEBREW POINT HATAF SEGOL,
# HEBREW ACCENT ETNAHTA, HEBREW PUNCTUATION SOF PASUQ, HEBREW POINT SHEVA,
# HEBREW ACCENT ILUY, HEBREW ACCENT QARNEY PARA
assert String.normalize("ֱָֹ֑׃ְ֬֟", :nfc) == "ֱָֹ֑׃ְ֬֟"
# 095D (exclusion list)
# 0922 093C
# DEVANAGARI LETTER RHA
assert String.normalize("ढ़", :nfc) == "ढ़"
# 0061 0315 0300 05AE 0340 0062
# 00E0 05AE 0300 0315 0062
# LATIN SMALL LETTER A, COMBINING COMMA ABOVE RIGHT, COMBINING GRAVE ACCENT,
# HEBREW ACCENT ZINOR, COMBINING GRAVE TONE MARK, LATIN SMALL LETTER B
assert String.normalize("à֮̀̕b", :nfc) == "à֮̀̕b"
# 0344
# 0308 0301
# COMBINING GREEK DIALYTIKA TONOS
assert String.normalize("\u0344", :nfc) == "\u0308\u0301"
# 115B9 0334 115AF
# 115B9 0334 115AF
# SIDDHAM VOWEL SIGN AI, COMBINING TILDE OVERLAY, SIDDHAM VOWEL SIGN AA
assert String.normalize("𑖹̴𑖯", :nfc) == "𑖹̴𑖯"
end
test "graphemes" do
# Extended
assert String.graphemes("Ā̀stute") == ["Ā̀", "s", "t", "u", "t", "e"]
# CLRF
assert String.graphemes("\r\n\f") == ["\r\n", "\f"]
# Regional indicator
assert String.graphemes("\u{1F1E6}\u{1F1E7}\u{1F1E8}") == ["\u{1F1E6}\u{1F1E7}\u{1F1E8}"]
# Hangul
assert String.graphemes("\u1100\u115D\uB4A4") == ["ᄀᅝ뒤"]
# Special Marking with Extended
assert String.graphemes("a\u0300\u0903") == ["a\u0300\u0903"]
end
test "next grapheme" do
assert String.next_grapheme("Ā̀stute") == {"Ā̀", "stute"}
assert String.next_grapheme("") == nil
end
test "first" do
assert String.first("elixir") == "e"
assert String.first("íelixr") == "í"
assert String.first("եոգլից ըմպելիք") == "ե"
assert String.first("лэіксір") == "л"
assert String.first("ελιξήριο") == "ε"
assert String.first("סם חיים") == "ס"
assert String.first("がガちゃ") == "が"
assert String.first("Ā̀stute") == "Ā̀"
assert String.first("") == nil
end
test "last" do
assert String.last("elixir") == "r"
assert String.last("elixrí") == "í"
assert String.last("եոգլից ըմպելիքե") == "ե"
assert String.last("ліксірэ") == "э"
assert String.last("ειξήριολ") == "λ"
assert String.last("סם ייםח") == "ח"
assert String.last("がガちゃ") == "ゃ"
assert String.last("Ā̀") == "Ā̀"
assert String.last("") == nil
end
test "length" do
assert String.length("elixir") == 6
assert String.length("elixrí") == 6
assert String.length("եոգլից") == 6
assert String.length("ліксрэ") == 6
assert String.length("ειξήριολ") == 8
assert String.length("סם ייםח") == 7
assert String.length("がガちゃ") == 4
assert String.length("Ā̀stute") == 6
assert String.length("") == 0
end
test "at" do
assert String.at("л", 0) == "л"
assert String.at("elixir", 1) == "l"
assert String.at("がガちゃ", 2) == "ち"
assert String.at("л", 10) == nil
assert String.at("elixir", -1) == "r"
assert String.at("がガちゃ", -2) == "ち"
assert String.at("л", -3) == nil
assert String.at("Ā̀stute", 1) == "s"
assert String.at("elixir", 6) == nil
assert_raise FunctionClauseError, fn ->
String.at("elixir", 0.1)
end
assert_raise FunctionClauseError, fn ->
String.at("elixir", -0.1)
end
end
test "slice" do
assert String.slice("elixir", 1, 3) == "lix"
assert String.slice("あいうえお", 2, 2) == "うえ"
assert String.slice("ειξήριολ", 2, 3) == "ξήρ"
assert String.slice("elixir", 3, 4) == "xir"
assert String.slice("あいうえお", 3, 5) == "えお"
assert String.slice("ειξήριολ", 5, 4) == "ιολ"
assert String.slice("elixir", -3, 2) == "xi"
assert String.slice("あいうえお", -4, 3) == "いうえ"
assert String.slice("ειξήριολ", -5, 3) == "ήρι"
assert String.slice("elixir", -10, 1) == ""
assert String.slice("あいうえお", -10, 2) == ""
assert String.slice("ειξήριολ", -10, 3) == ""
assert String.slice("elixir", 8, 2) == ""
assert String.slice("あいうえお", 6, 2) == ""
assert String.slice("ειξήριολ", 8, 1) == ""
assert String.slice("ειξήριολ", 9, 1) == ""
assert String.slice("elixir", 0, 0) == ""
assert String.slice("elixir", 5, 0) == ""
assert String.slice("elixir", -5, 0) == ""
assert String.slice("", 0, 1) == ""
assert String.slice("", 1, 1) == ""
assert String.slice("elixir", 0..-2) == "elixi"
assert String.slice("elixir", 1..3) == "lix"
assert String.slice("elixir", -5..-3) == "lix"
assert String.slice("elixir", -5..3) == "lix"
assert String.slice("あいうえお", 2..3) == "うえ"
assert String.slice("ειξήριολ", 2..4) == "ξήρ"
assert String.slice("elixir", 3..6) == "xir"
assert String.slice("あいうえお", 3..7) == "えお"
assert String.slice("ειξήριολ", 5..8) == "ιολ"
assert String.slice("elixir", -3..-2) == "xi"
assert String.slice("あいうえお", -4..-2) == "いうえ"
assert String.slice("ειξήριολ", -5..-3) == "ήρι"
assert String.slice("elixir", 8..9) == ""
assert String.slice("あいうえお", 6..7) == ""
assert String.slice("ειξήριολ", 8..8) == ""
assert String.slice("ειξήριολ", 9..9) == ""
assert String.slice("", 0..0) == ""
assert String.slice("", 1..1) == ""
assert String.slice("あいうえお", -2..-4) == ""
assert String.slice("あいうえお", -10..-15) == ""
assert String.slice("hello あいうえお unicode", 8..-1) == "うえお unicode"
assert String.slice("abc", -1..14) == "c"
end
test "valid?" do
assert String.valid?("afds")
assert String.valid?("øsdfh")
assert String.valid?("dskfjあska")
refute String.valid?(<<0xFFFF :: 16>>)
refute String.valid?("asd" <> <<0xFFFF :: 16>>)
end
test "chunk valid" do
assert String.chunk("", :valid) == []
assert String.chunk("ødskfjあ\x11ska", :valid)
== ["ødskfjあ\x11ska"]
assert String.chunk("abc\u{0ffff}def", :valid)
== ["abc", <<0x0FFFF::utf8>>, "def"]
assert String.chunk("\u{0FFFE}\u{3FFFF}привет\u{0FFFF}мир", :valid)
== [<<0x0FFFE::utf8, 0x3FFFF::utf8>>, "привет", <<0x0FFFF::utf8>>, "мир"]
assert String.chunk("日本\u{0FFFF}\u{FDEF}ござございます\u{FDD0}", :valid)
== ["日本", <<0x0FFFF::utf8, 0xFDEF::utf8>>, "ござございます", <<0xFDD0::utf8>>]
end
test "chunk printable" do
assert String.chunk("", :printable) == []
assert String.chunk("ødskfjあska", :printable)
== ["ødskfjあska"]
assert String.chunk("abc\u{0FFFF}def", :printable)
== ["abc", <<0x0FFFF::utf8>>, "def"]
assert String.chunk("\x06ab\x05cdef\x03\0", :printable)
== [<<6>>, "ab", <<5>>, "cdef", <<3, 0>>]
end
test "starts_with?" do
assert String.starts_with? "hello", "he"
assert String.starts_with? "hello", "hello"
refute String.starts_with? "hello", []
assert String.starts_with? "hello", ["hellö", "hell"]
assert String.starts_with? "エリクシア", "エリ"
refute String.starts_with? "hello", "lo"
refute String.starts_with? "hello", "hellö"
refute String.starts_with? "hello", ["hellö", "goodbye"]
refute String.starts_with? "エリクシア", "仙丹"
end
test "ends_with?" do
assert String.ends_with? "hello", "lo"
assert String.ends_with? "hello", "hello"
refute String.ends_with? "hello", []
assert String.ends_with? "hello", ["hell", "lo", "xx"]
assert String.ends_with? "hello", ["hellö", "lo"]
assert String.ends_with? "エリクシア", "シア"
refute String.ends_with? "hello", "he"
refute String.ends_with? "hello", "hellö"
refute String.ends_with? "hello", ["hel", "goodbye"]
refute String.ends_with? "エリクシア", "仙丹"
end
test "contains?" do
assert String.contains? "elixir of life", "of"
assert String.contains? "エリクシア", "シ"
refute String.contains? "elixir of life", []
assert String.contains? "elixir of life", ["mercury", "life"]
refute String.contains? "elixir of life", "death"
refute String.contains? "エリクシア", "仙"
refute String.contains? "elixir of life", ["death", "mercury", "eternal life"]
end
test "to charlist" do
assert String.to_charlist("æß") == [?æ, ?ß]
assert String.to_charlist("abc") == [?a, ?b, ?c]
assert_raise UnicodeConversionError,
"invalid encoding starting at <<223, 255>>", fn ->
String.to_charlist(<< 0xDF, 0xFF >>)
end
assert_raise UnicodeConversionError,
"incomplete encoding starting at <<195>>", fn ->
String.to_charlist(<< 106, 111, 115, 195 >>)
end
end
test "to float" do
assert String.to_float("3.0") == 3.0
three = fn -> "3" end
assert_raise ArgumentError, fn -> String.to_float(three.()) end
end
test "jaro distance" do
assert String.jaro_distance("same", "same") == 1.0
assert String.jaro_distance("any", "") == 0.0
assert String.jaro_distance("", "any") == 0.0
assert String.jaro_distance("martha", "marhta") == 0.9444444444444445
assert String.jaro_distance("martha", "marhha") == 0.888888888888889
assert String.jaro_distance("marhha", "martha") == 0.888888888888889
assert String.jaro_distance("dwayne", "duane") == 0.8222222222222223
assert String.jaro_distance("dixon", "dicksonx") == 0.7666666666666666
assert String.jaro_distance("xdicksonx", "dixon") == 0.7851851851851852
assert String.jaro_distance("shackleford", "shackelford") == 0.9696969696969697
assert String.jaro_distance("dunningham", "cunnigham") == 0.8962962962962964
assert String.jaro_distance("nichleson", "nichulson") == 0.9259259259259259
assert String.jaro_distance("jones", "johnson") == 0.7904761904761904
assert String.jaro_distance("massey", "massie") == 0.888888888888889
assert String.jaro_distance("abroms", "abrams") == 0.888888888888889
assert String.jaro_distance("hardin", "martinez") == 0.7222222222222222
assert String.jaro_distance("itman", "smith") == 0.4666666666666666
assert String.jaro_distance("jeraldine", "geraldine") == 0.9259259259259259
assert String.jaro_distance("michelle", "michael") == 0.8690476190476191
assert String.jaro_distance("julies", "julius") == 0.888888888888889
assert String.jaro_distance("tanya", "tonya") == 0.8666666666666667
assert String.jaro_distance("sean", "susan") == 0.7833333333333333
assert String.jaro_distance("jon", "john") == 0.9166666666666666
assert String.jaro_distance("jon", "jan") == 0.7777777777777777
assert String.jaro_distance("семена", "стремя") == 0.6666666666666666
end
test "difference/2" do
assert String.myers_difference("", "abc") == [ins: "abc"]
assert String.myers_difference("abc", "") == [del: "abc"]
assert String.myers_difference("", "") == []
assert String.myers_difference("abc", "abc") == [eq: "abc"]
assert String.myers_difference("abc", "aйbc") == [eq: "a", ins: "й", eq: "bc"]
assert String.myers_difference("aйbc", "abc") == [eq: "a", del: "й", eq: "bc"]
end
end
| 41.538799 | 211 | 0.573508 |
032c0102623325b6ea101b35e19f937817964299 | 2,412 | ex | Elixir | elixir/lib/homework/transactions.ex | ztoolson/web-homework | 09865a5df66fe8f380dfe0d848bbfae8398be1ef | [
"MIT"
] | null | null | null | elixir/lib/homework/transactions.ex | ztoolson/web-homework | 09865a5df66fe8f380dfe0d848bbfae8398be1ef | [
"MIT"
] | null | null | null | elixir/lib/homework/transactions.ex | ztoolson/web-homework | 09865a5df66fe8f380dfe0d848bbfae8398be1ef | [
"MIT"
] | null | null | null | defmodule Homework.Transactions do
@moduledoc """
The Transactions context.
"""
import Ecto.Query, warn: false
alias Homework.Repo
alias Homework.Transactions.Transaction
@doc """
Returns the list of transactions.
## Examples
iex> list_transactions([])
[%Transaction{}, ...]
"""
def list_transactions(args) do
args
|> Enum.reduce(Transaction, fn
{_, nil}, query ->
query
{:min, min}, query ->
from(t in query, where: t.amount >= ^min)
{:max, max}, query ->
from(t in query, where: t.amount <= ^max)
{:description, description}, query ->
from(t in query, where: ilike(t.description, ^"%#{description}%"))
end)
|> Repo.all()
end
@doc """
Gets a single transaction.
Raises `Ecto.NoResultsError` if the Transaction does not exist.
## Examples
iex> get_transaction!(123)
%Transaction{}
iex> get_transaction!(456)
** (Ecto.NoResultsError)
"""
def get_transaction!(id), do: Repo.get!(Transaction, id)
@doc """
Creates a transaction.
## Examples
iex> create_transaction(%{field: value})
{:ok, %Transaction{}}
iex> create_transaction(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_transaction(attrs \\ %{}) do
%Transaction{}
|> Transaction.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a transaction.
## Examples
iex> update_transaction(transaction, %{field: new_value})
{:ok, %Transaction{}}
iex> update_transaction(transaction, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_transaction(%Transaction{} = transaction, attrs) do
transaction
|> Transaction.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a transaction.
## Examples
iex> delete_transaction(transaction)
{:ok, %Transaction{}}
iex> delete_transaction(transaction)
{:error, %Ecto.Changeset{}}
"""
def delete_transaction(%Transaction{} = transaction) do
Repo.delete(transaction)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking transaction changes.
## Examples
iex> change_transaction(transaction)
%Ecto.Changeset{data: %Transaction{}}
"""
def change_transaction(%Transaction{} = transaction, attrs \\ %{}) do
Transaction.changeset(transaction, attrs)
end
end
| 20.268908 | 74 | 0.621476 |
032c112867a7d26981ff1ff781d97e7bb84880f6 | 26,745 | ex | Elixir | lib/faker/address/pt_br.ex | igas/faker | 73f6602cf493c87f7a4454e12e4333d42c050c94 | [
"MIT"
] | 540 | 2015-01-05T16:31:49.000Z | 2019-09-25T00:40:27.000Z | lib/faker/address/pt_br.ex | igas/faker | 73f6602cf493c87f7a4454e12e4333d42c050c94 | [
"MIT"
] | 172 | 2015-01-06T03:55:17.000Z | 2019-10-03T12:58:02.000Z | lib/faker/address/pt_br.ex | igas/faker | 73f6602cf493c87f7a4454e12e4333d42c050c94 | [
"MIT"
] | 163 | 2015-01-05T21:24:54.000Z | 2019-10-03T07:59:42.000Z | defmodule Faker.Address.PtBr do
import Faker, only: [sampler: 2]
alias Faker.Person.PtBr
@moduledoc """
Functions for generating addresses in Portuguese
"""
@doc """
Return random building number.
## Examples
iex> Faker.Address.PtBr.building_number()
"s/n"
iex> Faker.Address.PtBr.building_number()
"5426"
iex> Faker.Address.PtBr.building_number()
"6"
iex> Faker.Address.PtBr.building_number()
"0832"
"""
@spec building_number() :: String.t()
def building_number do
["s/n", "####", "###", "##", "#"]
|> Enum.at(Faker.random_between(0, 4))
|> Faker.format()
end
@doc """
Return city name.
## Examples
iex> Faker.Address.PtBr.city()
"Senador Kaique Paulista"
iex> Faker.Address.PtBr.city()
"São Roberta dos Dourados"
iex> Faker.Address.PtBr.city()
"Salto das Flores"
iex> Faker.Address.PtBr.city()
"Kléber"
"""
@spec city() :: String.t()
def city do
city(Faker.random_between(0, 6))
end
def city(0), do: "#{PtBr.first_name()} #{city_suffixes()}"
def city(1), do: "#{PtBr.first_name()} #{city_suffixes()}"
def city(2), do: "#{city_prefix()} #{PtBr.first_name()} #{city_suffixes()}"
def city(3), do: "#{PtBr.first_name()}"
def city(4), do: "#{city_prefix()} #{PtBr.first_name()}"
def city(5), do: "#{city_prefix()} #{city_suffixes()}"
def city(6), do: "#{city_prefix()} #{PtBr.first_name()} #{city_suffixes()}"
@doc """
Return city suffixes.
## Examples
iex> Faker.Address.PtBr.city_suffixes()
"da Serra"
iex> Faker.Address.PtBr.city_suffixes()
"dos Dourados"
iex> Faker.Address.PtBr.city_suffixes()
"da Serra"
iex> Faker.Address.PtBr.city_suffixes()
"Paulista"
"""
@spec city_suffixes() :: String.t()
sampler(:city_suffixes, [
"do Sul",
"do Norte",
"de Minas",
"do Campo",
"Grande",
"da Serra",
"do Oeste",
"de Goiás",
"Paulista",
"da Mata",
"Alegre",
"da Praia",
"das Flores",
"das Pedras",
"dos Dourados",
"do Amparo",
"do Galho",
"da Prata",
"Verde"
])
@doc """
Return city suffixes.
## Examples
iex> Faker.Address.PtBr.city_prefix()
"Santo"
iex> Faker.Address.PtBr.city_prefix()
"Senador"
iex> Faker.Address.PtBr.city_prefix()
"Senador"
iex> Faker.Address.PtBr.city_prefix()
"Alta"
"""
@spec city_prefix() :: String.t()
sampler(:city_prefix, [
"Agua",
"Boa",
"Barra",
"Coronel",
"Nova",
"Boa",
"Alta",
"Bento",
"Porto",
"Praia",
"Ribeirão",
"Rio",
"Salto",
"Santa",
"Santo",
"Santana",
"São",
"Senador",
"Serra",
"Três",
"Vale",
"Vila"
])
@doc """
Return country.
## Examples
iex> Faker.Address.PtBr.country()
"Ilhas Virgens Britânicas"
iex> Faker.Address.PtBr.country()
"Coreia do Sul"
iex> Faker.Address.PtBr.country()
"Bolívia"
iex> Faker.Address.PtBr.country()
"Mongólia"
"""
@spec country() :: String.t()
sampler(:country, [
"Afeganistão",
"África do Sul",
"Akrotiri",
"Albânia",
"Alemanha",
"Andorra",
"Angola",
"Anguila",
"Antártica",
"Antígua e Barbuda",
"Antilhas Holandesas",
"Arábia Saudita",
"Argélia",
"Argentina",
"Armênia",
"Aruba",
"Ashmore and Cartier Islands",
"Austrália",
"Áustria",
"Azerbaijão",
"Bahamas",
"Bangladesh",
"Barbados",
"Barein",
"Bélgica",
"Belize",
"Benim",
"Bermudas",
"Bielorrússia",
"Birmânia",
"Bolívia",
"Bósnia e Herzegovina",
"Botsuana",
"Brasil",
"Brunei",
"Bulgária",
"Burquina Faso",
"Burundi",
"Butão",
"Cabo Verde",
"Camarões",
"Camboja",
"Canadá",
"Catar",
"Cazaquistão",
"Chade",
"Chile",
"China",
"Chipre",
"Clipperton Island",
"Colômbia",
"Comores",
"Congo-Brazzaville",
"Congo-Kinshasa",
"Coral Sea Islands",
"Coreia do Norte",
"Coreia do Sul",
"Costa do Marfim",
"Costa Rica",
"Croácia",
"Cuba",
"Dhekelia",
"Dinamarca",
"Domínica",
"Egito",
"Costa do Marfim",
"Costa Rica",
"Croácia",
"Cuba",
"Dhekelia",
"Dinamarca",
"Domínica",
"Egito",
"Emirados Árabes Unidos",
"Equador",
"Eritreia",
"Eslováquia",
"Eslovênia",
"Espanha",
"Estados Unidos",
"Estônia",
"Etiópia",
"Faroé",
"Fiji",
"Filipinas",
"Finlândia",
"França",
"Gabão",
"Gâmbia",
"Gana",
"Geórgia",
"Geórgia do Sul e Sandwich do Sul",
"Gibraltar",
"Granada",
"Grécia",
"Gronelândia",
"Guam",
"Guatemala",
"Guernsey",
"Guiana",
"Guiné",
"Guiné Equatorial",
"Guiné-Bissau",
"Haiti",
"Honduras",
"Hong Kong",
"Hungria",
"Iêmen",
"Ilha Bouvet",
"Ilha do Natal",
"Ilha Norfolk",
"Ilhas Caiman",
"Ilhas Cook",
"Ilhas dos Cocos",
"Ilhas Falkland",
"Ilhas Heard e McDonald",
"Ilhas Marshall",
"Ilhas Salomão",
"Ilhas Turcas e Caicos",
"Ilhas Virgens Americanas",
"Ilhas Virgens Britânicas",
"Índia",
"Indonésia",
"Iran",
"Iraque",
"Irlanda",
"Islândia",
"Israel",
"Itália",
"Jamaica",
"Jan Mayen",
"Japão",
"Jersey",
"Jibuti",
"Jordânia",
"Kuwait",
"Laos",
"Lesoto",
"Letônia",
"Líbano",
"Libéria",
"Líbia",
"Liechtenstein",
"Lituânia",
"Luxemburgo",
"Macau",
"Macedônia",
"Madagáscar",
"Malásia",
"Malávi",
"Maldivas",
"Mali",
"Malta",
"Man, Isle of",
"Marianas do Norte",
"Marrocos",
"Maurícia",
"Mauritânia",
"Mayotte",
"México",
"Micronésia",
"Moçambique",
"Moldávia",
"Mônaco",
"Mongólia",
"Monserrate",
"Montenegro",
"Namíbia",
"Nauru",
"Navassa Island",
"Nepal",
"Nicarágua",
"Níger",
"Nigéria",
"Niue",
"Noruega",
"Nova Caledónia",
"Nova Zelândia",
"Omã",
"Países Baixos",
"Palau",
"Panamá",
"Papua-Nova Guiné",
"Paquistão",
"Paracel Islands",
"Paraguai",
"Peru",
"Pitcairn",
"Polinésia Francesa",
"Polônia",
"Porto Rico",
"Portugal",
"Quênia",
"Quirguizistão",
"Quiribáti",
"Reino Unido",
"República Centro-Africana",
"República Checa",
"República Dominicana",
"Roménia",
"Ruanda",
"Rússia",
"Salvador",
"Samoa",
"Samoa Americana",
"Santa Helena",
"Santa Lúcia",
"São Cristóvão e Neves",
"São Marinho",
"São Pedro e Miquelon",
"São Tomé e Príncipe",
"São Vicente e Granadinas",
"Sara Ocidental",
"Seicheles",
"Senegal",
"Serra Leoa",
"Sérvia",
"Singapura",
"Síria",
"Somália",
"Sri Lanka",
"Suazilândia",
"Sudão",
"Suécia",
"Suíça",
"Suriname",
"Svalbard e Jan Mayen",
"Tailândia",
"Taiwan",
"Tajiquistão",
"Tanzânia",
"Território Britânico do Oceano Índico",
"Territórios Austrais Franceses",
"Timor Leste",
"Togo",
"Tokelau",
"Tonga",
"Trindade e Tobago",
"Tunísia",
"Turquemenistão",
"Turquia",
"Tuvalu",
"Ucrânia",
"Uganda",
"União Europeia",
"Uruguai",
"Usbequistão",
"Vanuatu",
"Vaticano",
"Venezuela",
"Vietnam",
"Wake Island",
"Wallis e Futuna",
"Zâmbia",
"Zimbabu"
])
@doc """
Return country code.
## Examples
iex> Faker.Address.PtBr.country_code()
"BR"
"""
@spec country_code() :: String.t()
sampler(:country_code, ["BR"])
@doc """
Return random secondary address.
## Examples
iex> Faker.Address.PtBr.secondary_address()
"Sala 154"
iex> Faker.Address.PtBr.secondary_address()
"Sala 646"
iex> Faker.Address.PtBr.secondary_address()
"AP 083"
iex> Faker.Address.PtBr.secondary_address()
"Sala 970"
"""
@spec secondary_address() :: String.t()
def secondary_address do
["Sala ###", "AP ###"]
|> Enum.at(Faker.random_between(0, 1))
|> Faker.format()
end
@doc """
Return state.
## Examples
iex> Faker.Address.PtBr.state()
"Rondônia"
iex> Faker.Address.PtBr.state()
"Rio Grande do Sul"
iex> Faker.Address.PtBr.state()
"Distrito Federal"
iex> Faker.Address.PtBr.state()
"Ceará"
"""
@spec state() :: String.t()
sampler(:state, [
"Acre",
"Alagoas",
"Amapá",
"Amazonas",
"Bahia",
"Ceará",
"Distrito Federal",
"Espírito Santo",
"Goiás",
"Maranhão",
"Mato Grosso",
"Mato Grosso do Sul",
"Minas Gerais",
"Pará",
"Paraíba",
"Paraná",
"Pernambuco",
"Piauí",
"Rio de Janeiro",
"Rio Grande do Norte",
"Rio Grande do Sul",
"Rondônia",
"Roraima",
"Santa Catarina",
"São Paulo",
"Sergipe",
"Tocantins"
])
@doc """
Return neighborhood.
## Examples
iex> Faker.Address.PtBr.neighborhood()
"Granja De Freitas"
iex> Faker.Address.PtBr.neighborhood()
"Novo Ouro Preto"
iex> Faker.Address.PtBr.neighborhood()
"Padre Eustáquio"
iex> Faker.Address.PtBr.neighborhood()
"Nossa Senhora Aparecida"
"""
@spec neighborhood() :: String.t()
sampler(:neighborhood, [
"Aarão Reis",
"Acaba Mundo",
"Acaiaca",
"Ademar Maldonado",
"Aeroporto",
"Aguas Claras",
"Alípio De Melo",
"Alpes",
"Alta Tensão 1ª Seção",
"Alta Tensão 2ª Seção",
"Alto Caiçaras",
"Alto Das Antenas",
"Alto Dos Pinheiros",
"Alto Vera Cruz",
"Álvaro Camargos",
"Ambrosina",
"Andiroba",
"Antonio Ribeiro De Abreu 1ª Seção",
"Aparecida 7ª Seção",
"Ápia",
"Apolonia",
"Araguaia",
"Atila De Paiva",
"Bacurau",
"Bairro Das Indústrias Ii",
"Baleia",
"Barão Homem De Melo 1ª Seção",
"Barão Homem De Melo 2ª Seção",
"Barão Homem De Melo 3ª Seção",
"Barreiro",
"Beija Flor",
"Beira Linha",
"Bela Vitoria",
"Belmonte",
"Bernadete",
"Betânia",
"Biquinhas",
"Boa Esperança",
"Boa União 1ª Seção",
"Boa União 2ª Seção",
"Boa Viagem",
"Boa Vista",
"Bom Jesus",
"Bonfim",
"Bonsucesso",
"Brasil Industrial",
"Braúnas",
"Buraco Quente",
"Cabana Do Pai Tomás",
"Cachoeirinha",
"Caetano Furquim",
"Caiçara - Adelaide",
"Calafate",
"Califórnia",
"Camargos",
"Campo Alegre",
"Camponesa 1ª Seção",
"Camponesa 2ª Seção",
"Canaa",
"Canadá",
"Candelaria",
"Capitão Eduardo",
"Cardoso",
"Casa Branca",
"Castanheira",
"Cdi Jatoba",
"Cenaculo",
"Céu Azul",
"Chácara Leonina",
"Cidade Jardim Taquaril",
"Cinquentenário",
"Colégio Batista",
"Comiteco",
"Concórdia",
"Cônego Pinheiro 1ª Seção",
"Cônego Pinheiro 2ª Seção",
"Confisco",
"Conjunto Bonsucesso",
"Conjunto Califórnia I",
"Conjunto Califórnia Ii",
"Conjunto Capitão Eduardo",
"Conjunto Celso Machado",
"Conjunto Floramar",
"Conjunto Jardim Filadélfia",
"Conjunto Jatoba",
"Conjunto Lagoa",
"Conjunto Minas Caixa",
"Conjunto Novo Dom Bosco",
"Conjunto Paulo Vi",
"Conjunto Providencia",
"Conjunto Santa Maria",
"Conjunto São Francisco De Assis",
"Conjunto Serra Verde",
"Conjunto Taquaril",
"Copacabana",
"Coqueiros",
"Corumbiara",
"Custodinha",
"Das Industrias I",
"Delta",
"Diamante",
"Distrito Industrial Do Jatoba",
"Dom Bosco",
"Dom Cabral",
"Dom Joaquim",
"Dom Silverio",
"Dona Clara",
"Embaúbas",
"Engenho Nogueira",
"Ermelinda",
"Ernesto Nascimento",
"Esperança",
"Estrela",
"Estrela Do Oriente",
"Etelvina Carneiro",
"Europa",
"Eymard",
"Fazendinha",
"Flamengo",
"Flavio De Oliveira",
"Flavio Marques Lisboa",
"Floramar",
"Frei Leopoldo",
"Gameleira",
"Garças",
"Glória",
"Goiania",
"Graça",
"Granja De Freitas",
"Granja Werneck",
"Grota",
"Grotinha",
"Guarani",
"Guaratã",
"Havaí",
"Heliopolis",
"Horto Florestal",
"Inconfidência",
"Indaiá",
"Independência",
"Ipe",
"Itapoa",
"Itatiaia",
"Jaqueline",
"Jaraguá",
"Jardim Alvorada",
"Jardim Atlântico",
"Jardim Do Vale",
"Jardim Dos Comerciarios",
"Jardim Felicidade",
"Jardim Guanabara",
"Jardim Leblon",
"Jardim Montanhês",
"Jardim São José",
"Jardim Vitoria",
"Jardinópolis",
"Jatobá",
"João Alfredo",
"João Paulo Ii",
"Jonas Veiga",
"Juliana",
"Lagoa",
"Lagoinha",
"Lagoinha Leblon",
"Lajedo",
"Laranjeiras",
"Leonina",
"Leticia",
"Liberdade",
"Lindéia",
"Lorena",
"Madre Gertrudes",
"Madri",
"Mala E Cuia",
"Manacas",
"Mangueiras",
"Mantiqueira",
"Marajó",
"Maravilha",
"Marçola",
"Maria Goretti",
"Maria Helena",
"Maria Tereza",
"Maria Virgínia",
"Mariano De Abreu",
"Marieta 1ª Seção",
"Marieta 2ª Seção",
"Marieta 3ª Seção",
"Marilandia",
"Mariquinhas",
"Marmiteiros",
"Milionario",
"Minas Brasil",
"Minas Caixa",
"Minaslandia",
"Mineirão",
"Miramar",
"Mirante",
"Mirtes",
"Monsenhor Messias",
"Monte Azul",
"Monte São José",
"Morro Dos Macacos",
"Nazare",
"Nossa Senhora Aparecida",
"Nossa Senhora Da Aparecida",
"Nossa Senhora Da Conceição",
"Nossa Senhora De Fátima",
"Nossa Senhora Do Rosário",
"Nova America",
"Nova Cachoeirinha",
"Nova Cintra",
"Nova Esperança",
"Nova Floresta",
"Nova Gameleira",
"Nova Pampulha",
"Novo Aarão Reis",
"Novo Das Industrias",
"Novo Glória",
"Novo Santa Cecilia",
"Novo Tupi",
"Oeste",
"Olaria",
"Olhos D'água",
"Ouro Minas",
"Pantanal",
"Paquetá",
"Paraíso",
"Parque São José",
"Parque São Pedro",
"Paulo Vi",
"Pedreira Padro Lopes",
"Penha",
"Petropolis",
"Pilar",
"Pindorama",
"Pindura Saia",
"Piraja",
"Piratininga",
"Pirineus",
"Pompéia",
"Pongelupe",
"Pousada Santo Antonio",
"Primeiro De Maio",
"Providencia",
"Ribeiro De Abreu",
"Rio Branco",
"Salgado Filho",
"Santa Amelia",
"Santa Branca",
"Santa Cecilia",
"Santa Cruz",
"Santa Helena",
"Santa Inês",
"Santa Isabel",
"Santa Margarida",
"Santa Maria",
"Santa Rita",
"Santa Rita De Cássia",
"Santa Sofia",
"Santa Terezinha",
"Santana Do Cafezal",
"Santo André",
"São Benedito",
"São Bernardo",
"São Cristóvão",
"São Damião",
"São Francisco",
"São Francisco Das Chagas",
"São Gabriel",
"São Geraldo",
"São Gonçalo",
"São João",
"São João Batista",
"São Jorge 1ª Seção",
"São Jorge 2ª Seção",
"São Jorge 3ª Seção",
"São José",
"São Marcos",
"São Paulo",
"São Salvador",
"São Sebastião",
"São Tomaz",
"São Vicente",
"Satelite",
"Saudade",
"Senhor Dos Passos",
"Serra Do Curral",
"Serra Verde",
"Serrano",
"Solar Do Barreiro",
"Solimoes",
"Sport Club",
"Suzana",
"Taquaril",
"Teixeira Dias",
"Tiradentes",
"Tirol",
"Tres Marias",
"Trevo",
"Túnel De Ibirité",
"Tupi A",
"Tupi B",
"União",
"Unidas",
"Universitário",
"Universo",
"Urca",
"Vale Do Jatoba",
"Varzea Da Palma",
"Venda Nova",
"Ventosa",
"Vera Cruz",
"Vila Aeroporto",
"Vila Aeroporto Jaraguá",
"Vila Antena",
"Vila Antena Montanhês",
"Vila Atila De Paiva",
"Vila Bandeirantes",
"Vila Barragem Santa Lúcia",
"Vila Batik",
"Vila Betânia",
"Vila Boa Vista",
"Vila Calafate",
"Vila Califórnia",
"Vila Canto Do Sabiá",
"Vila Cemig",
"Vila Cloris",
"Vila Copacabana",
"Vila Copasa",
"Vila Coqueiral",
"Vila Da Amizade",
"Vila Da Ária",
"Vila Da Luz",
"Vila Da Paz",
"Vila Das Oliveiras",
"Vila Do Pombal",
"Vila Dos Anjos",
"Vila Ecológica",
"Vila Engenho Nogueira",
"Vila Esplanada",
"Vila Formosa",
"Vila Fumec",
"Vila Havaí",
"Vila Independencia 1ª Seção",
"Vila Independencia 2ª Seção",
"Vila Independencia 3ª Seção",
"Vila Inestan",
"Vila Ipiranga",
"Vila Jardim Alvorada",
"Vila Jardim Leblon",
"Vila Jardim São José",
"Vila Madre Gertrudes 1ª Seção",
"Vila Madre Gertrudes 2ª Seção",
"Vila Madre Gertrudes 3ª Seção",
"Vila Madre Gertrudes 4ª Seção",
"Vila Maloca",
"Vila Mangueiras",
"Vila Mantiqueira",
"Vila Maria",
"Vila Minaslandia",
"Vila Nossa Senhora Do Rosário",
"Vila Nova",
"Vila Nova Cachoeirinha 1ª Seção",
"Vila Nova Cachoeirinha 2ª Seção",
"Vila Nova Cachoeirinha 3ª Seção",
"Vila Nova Dos Milionarios",
"Vila Nova Gameleira 1ª Seção",
"Vila Nova Gameleira 2ª Seção",
"Vila Nova Gameleira 3ª Seção",
"Vila Nova Paraíso",
"Vila Novo São Lucas",
"Vila Oeste",
"Vila Olhos D'água",
"Vila Ouro Minas",
"Vila Paquetá",
"Vila Paraíso",
"Vila Petropolis",
"Vila Pilar",
"Vila Pinho",
"Vila Piratininga",
"Vila Piratininga Venda Nova",
"Vila Primeiro De Maio",
"Vila Puc",
"Vila Real 1ª Seção",
"Vila Real 2ª Seção",
"Vila Rica",
"Vila Santa Monica 1ª Seção",
"Vila Santa Monica 2ª Seção",
"Vila Santa Rosa",
"Vila Santo Antônio",
"Vila Santo Antônio Barroquinha",
"Vila São Dimas",
"Vila São Francisco",
"Vila São Gabriel",
"Vila São Gabriel Jacui",
"Vila São Geraldo",
"Vila São João Batista",
"Vila São Paulo",
"Vila São Rafael",
"Vila Satélite",
"Vila Sesc",
"Vila Sumaré",
"Vila Suzana Primeira Seção",
"Vila Suzana Segunda Seção",
"Vila Tirol",
"Vila Trinta E Um De Março",
"Vila União",
"Vila Vista Alegre",
"Virgínia",
"Vista Alegre",
"Vista Do Sol",
"Vitoria",
"Vitoria Da Conquista",
"Xangri-Lá",
"Xodo-Marize",
"Zilah Sposito",
"Outro",
"Novo São Lucas",
"Esplanada",
"Estoril",
"Novo Ouro Preto",
"Ouro Preto",
"Padre Eustáquio",
"Palmares",
"Palmeiras",
"Vila De Sá",
"Floresta",
"Anchieta",
"Aparecida",
"Grajaú",
"Planalto",
"Bandeirantes",
"Gutierrez",
"Jardim América",
"Renascença",
"Barro Preto",
"Barroca",
"Sagrada Família",
"Ipiranga",
"Belvedere",
"Santa Efigênia",
"Santa Lúcia",
"Santa Monica",
"Vila Jardim Montanhes",
"Santa Rosa",
"Santa Tereza",
"Buritis",
"Vila Paris",
"Santo Agostinho",
"Santo Antônio",
"Caiçaras",
"São Bento",
"Prado",
"Lourdes",
"Fernão Dias",
"Carlos Prates",
"Carmo",
"Luxemburgo",
"São Lucas",
"São Luiz",
"Mangabeiras",
"São Pedro",
"Horto",
"Cidade Jardim",
"Castelo",
"Cidade Nova",
"Savassi",
"Serra",
"Silveira",
"Sion",
"Centro",
"Alto Barroca",
"Nova Vista",
"Coração De Jesus",
"Coração Eucarístico",
"Funcionários",
"Cruzeiro",
"João Pinheiro",
"Nova Granada",
"Nova Suíça",
"Itaipu"
])
@doc """
Return state abbr.
## Examples
iex> Faker.Address.PtBr.state_abbr()
"RO"
iex> Faker.Address.PtBr.state_abbr()
"RS"
iex> Faker.Address.PtBr.state_abbr()
"DF"
iex> Faker.Address.PtBr.state_abbr()
"CE"
"""
@spec state_abbr() :: String.t()
sampler(:state_abbr, [
"AC",
"AL",
"AP",
"AM",
"BA",
"CE",
"DF",
"ES",
"GO",
"MA",
"MT",
"MS",
"MG",
"PA",
"PB",
"PR",
"PE",
"PI",
"RJ",
"RN",
"RS",
"RO",
"RR",
"SC",
"SP",
"SE",
"TO"
])
@doc """
Return street address.
## Examples
iex> Faker.Address.PtBr.street_address()
"Estação Kaique, 2"
iex> Faker.Address.PtBr.street_address()
"Lagoa Matheus, 0832"
iex> Faker.Address.PtBr.street_address()
"Estrada Diegues, s/n"
iex> Faker.Address.PtBr.street_address()
"Praia Limeira, 020"
"""
@spec street_address() :: String.t()
def street_address do
"#{street_name()}, #{building_number()}"
end
@doc """
Return `street_address/0` or if argument is `true` adds `secondary_address/0`.
## Examples
iex> Faker.Address.PtBr.street_address(true)
"Estação Kaique, 2 Sala 461"
iex> Faker.Address.PtBr.street_address(false)
"Conjunto Rodrigo, 970"
iex> Faker.Address.PtBr.street_address(false)
"Trecho Davi Luiz Limeira, 020"
iex> Faker.Address.PtBr.street_address(false)
"Sítio Maria Eduarda, 097"
"""
@spec street_address(true | any) :: String.t()
def street_address(true), do: street_address() <> " " <> secondary_address()
def street_address(_), do: street_address()
@doc """
Return street name.
## Examples
iex> Faker.Address.PtBr.street_name()
"Estação Kaique"
iex> Faker.Address.PtBr.street_name()
"Morro Louise Macieira"
iex> Faker.Address.PtBr.street_name()
"Loteamento Maria Alice Junqueira"
iex> Faker.Address.PtBr.street_name()
"Condomínio da Maia"
"""
@spec street_name() :: String.t()
def street_name do
street_name(Faker.random_between(0, 2))
end
defp street_name(0), do: "#{street_prefix()} #{PtBr.first_name()}"
defp street_name(1), do: "#{street_prefix()} #{PtBr.last_name()}"
defp street_name(2),
do: "#{street_prefix()} #{PtBr.first_name()} #{PtBr.last_name()}"
@doc """
Return street prefix.
## Examples
iex> Faker.Address.PtBr.street_prefix()
"Recanto"
iex> Faker.Address.PtBr.street_prefix()
"Estação"
iex> Faker.Address.PtBr.street_prefix()
"Feira"
iex> Faker.Address.PtBr.street_prefix()
"Fazenda"
"""
@spec street_prefix() :: String.t()
sampler(:street_prefix, [
"Aeroporto",
"Alameda",
"Área",
"Avenida",
"Campo",
"Chácara",
"Colônia",
"Condomínio",
"Conjunto",
"Distrito",
"Esplanada",
"Estação",
"Estrada",
"Favela",
"Fazenda",
"Feira",
"Jardim",
"Ladeira",
"Lago",
"Lagoa",
"Largo",
"Loteamento",
"Morro",
"Núcleo",
"Parque",
"Passarela",
"Pátio",
"Praça",
"Praia",
"Quadra",
"Recanto",
"Residencial",
"Rodovia",
"Rua",
"Setor",
"Sítio",
"Travessa",
"Trecho",
"Trevo",
"Vale",
"Vereda",
"Via",
"Viaduto",
"Viela",
"Vila"
])
@doc """
Return time zone.
## Examples
iex> Faker.Address.PtBr.time_zone()
"Australia/Sydney"
iex> Faker.Address.PtBr.time_zone()
"America/Guyana"
iex> Faker.Address.PtBr.time_zone()
"Asia/Kathmandu"
iex> Faker.Address.PtBr.time_zone()
"Europa/Vienna"
"""
@spec time_zone() :: String.t()
sampler(:time_zone, [
"Pacífico/Midway",
"Pacífico/Pago_Pago",
"Pacífico/Honolulu",
"America/Juneau",
"America/Los_Angeles",
"America/Tijuana",
"America/Denver",
"America/Phoenix",
"America/Chihuahua",
"America/Mazatlan",
"America/Chicago",
"America/Regina",
"America/Mexico_City",
"America/Monterrey",
"America/Guatemala",
"America/New_York",
"America/Indiana/Indianapolis",
"America/Bogota",
"America/Lima",
"America/Halifax",
"America/Caracas",
"America/La_Paz",
"America/Santiago",
"America/St_Johns",
"America/Sao_Paulo",
"America/Argentina/Buenos_Aires",
"America/Guyana",
"America/Godthab",
"Atlantic/South_Georgia",
"Atlantic/Azores",
"Atlantic/Cape_Verde",
"Europa/Dublin",
"Europa/Lisbon",
"Europa/London",
"Africa/Casablanca",
"Africa/Monrovia",
"Etc/UTC",
"Europa/Belgrade",
"Europa/Bratislava",
"Europa/Budapest",
"Europa/Ljubljana",
"Europa/Prague",
"Europa/Sarajevo",
"Europa/Skopje",
"Europa/Warsaw",
"Europa/Zagreb",
"Europa/Brussels",
"Europa/Copenhagen",
"Europa/Madrid",
"Europa/Paris",
"Europa/Amsterdam",
"Europa/Berlin",
"Europa/Rome",
"Europa/Stockholm",
"Europa/Vienna",
"Africa/Algiers",
"Europa/Bucharest",
"Africa/Cairo",
"Europa/Helsinki",
"Europa/Kiev",
"Europa/Riga",
"Europa/Sofia",
"Europa/Tallinn",
"Europa/Vilnius",
"Europa/Athens",
"Europa/Istanbul",
"Europa/Minsk",
"Asia/Jerusalen",
"Africa/Harare",
"Africa/Johannesburg",
"Europa/Moscú",
"Asia/Kuwait",
"Asia/Riyadh",
"Africa/Nairobi",
"Asia/Baghdad",
"Asia/Tehran",
"Asia/Muscat",
"Asia/Baku",
"Asia/Tbilisi",
"Asia/Yerevan",
"Asia/Kabul",
"Asia/Yekaterinburg",
"Asia/Karachi",
"Asia/Tashkent",
"Asia/Kolkata",
"Asia/Kathmandu",
"Asia/Dhaka",
"Asia/Colombo",
"Asia/Almaty",
"Asia/Novosibirsk",
"Asia/Rangoon",
"Asia/Bangkok",
"Asia/Jakarta",
"Asia/Krasnoyarsk",
"Asia/Shanghai",
"Asia/Chongqing",
"Asia/Hong_Kong",
"Asia/Urumqi",
"Asia/Kuala_Lumpur",
"Asia/Singapore",
"Asia/Taipei",
"Australia/Perth",
"Asia/Irkutsk",
"Asia/Ulaanbaatar",
"Asia/Seoul",
"Asia/Tokyo",
"Asia/Yakutsk",
"Australia/Darwin",
"Australia/Adelaide",
"Australia/Melbourne",
"Australia/Sydney",
"Australia/Brisbane",
"Australia/Hobart",
"Asia/Vladivostok",
"Pacífico/Guam",
"Pacífico/Port_Moresby",
"Asia/Magadan",
"Pacífico/Noumea",
"Pacífico/Fiji",
"Asia/Kamchatka",
"Pacífico/Majuro",
"Pacífico/Auckland",
"Pacífico/Tongatapu",
"Pacífico/Fakaofo",
"Pacífico/Apia"
])
@doc """
Return random postcode.
## Examples
iex> Faker.Address.PtBr.zip_code()
"15426461"
iex> Faker.Address.PtBr.zip_code()
"83297052"
iex> Faker.Address.PtBr.zip_code()
"57.020-303"
iex> Faker.Address.PtBr.zip_code()
"09733-760"
"""
@spec zip_code() :: String.t()
def zip_code do
["########", "##.###-###", "#####-###"]
|> Enum.at(Faker.random_between(0, 2))
|> Faker.format()
end
end
| 20.261364 | 80 | 0.560852 |
032c2561698efed138679d749dc6f76586429d69 | 760 | exs | Elixir | priv/repo/migrations/20201104054113_create_users_auth_tables.exs | BCrawfordScott/horizons | 04ee6ba579517e6a35c1347de4be1bceea8e4b36 | [
"MIT"
] | null | null | null | priv/repo/migrations/20201104054113_create_users_auth_tables.exs | BCrawfordScott/horizons | 04ee6ba579517e6a35c1347de4be1bceea8e4b36 | [
"MIT"
] | null | null | null | priv/repo/migrations/20201104054113_create_users_auth_tables.exs | BCrawfordScott/horizons | 04ee6ba579517e6a35c1347de4be1bceea8e4b36 | [
"MIT"
] | null | null | null | defmodule Horizons.Repo.Migrations.CreateUsersAuthTables do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
create table(:users) do
add :email, :citext, null: false
add :hashed_password, :string, null: false
add :confirmed_at, :naive_datetime
timestamps()
end
create unique_index(:users, [:email])
create table(:users_tokens) do
add :user_id, references(:users, on_delete: :delete_all), null: false
add :token, :binary, null: false
add :context, :string, null: false
add :sent_to, :string
timestamps(updated_at: false)
end
create index(:users_tokens, [:user_id])
create unique_index(:users_tokens, [:context, :token])
end
end
| 27.142857 | 75 | 0.673684 |
032c31039cf529570567134f4030870de2ea9069 | 1,205 | ex | Elixir | lib/hunter/domain.ex | 4DA/hunter | 0264d40bc8d3a23f81b7976b636c0726934dac60 | [
"Apache-2.0"
] | 38 | 2017-04-09T16:43:58.000Z | 2021-10-30T00:47:41.000Z | lib/hunter/domain.ex | 4DA/hunter | 0264d40bc8d3a23f81b7976b636c0726934dac60 | [
"Apache-2.0"
] | 51 | 2017-04-14T13:02:42.000Z | 2022-02-28T11:16:44.000Z | lib/hunter/domain.ex | 4DA/hunter | 0264d40bc8d3a23f81b7976b636c0726934dac60 | [
"Apache-2.0"
] | 8 | 2017-04-14T12:45:18.000Z | 2020-09-04T23:08:30.000Z | defmodule Hunter.Domain do
@moduledoc """
Domain blocks
"""
alias Hunter.Config
@doc """
Fetch user's blocked domains
## Parameters
* `conn` - connection credentials
* `options` - option list
## Options
* `max_id` - get a list of blocks with id less than or equal this value
* `since_id` - get a list of blocks with id greater than this value
* `limit` - maximum number of blocks to get, default: 40, max: 80
"""
@spec blocked_domains(Hunter.Client.t(), Keyword.t()) :: list
def blocked_domains(conn, options \\ []) do
Config.hunter_api().blocked_domains(conn, options)
end
@doc """
Block a domain
## Parameters
* `conn` - connection credentials
* `domain` - domain to block
"""
@spec block_domain(Hunter.Client.t(), String.t()) :: boolean
def block_domain(conn, domain) do
Config.hunter_api().block_domain(conn, domain)
end
@doc """
Unblock a domain
## Parameters
* `conn` - connection credentials
* `domain` - domain to unblock
"""
@spec unblock_domain(Hunter.Client.t(), String.t()) :: boolean
def unblock_domain(conn, domain) do
Config.hunter_api().unblock_domain(conn, domain)
end
end
| 21.517857 | 75 | 0.653112 |
032c4a48f8cd517c3e52614d2ce1b149b2950a98 | 931 | ex | Elixir | lib/dbfs_web/controllers/api_v1/block.ex | EnriqueAldana/Block_Chain_Attendance | 5ed0d16d1d2bdae16c7131acedbea362ea80163b | [
"Apache-2.0"
] | null | null | null | lib/dbfs_web/controllers/api_v1/block.ex | EnriqueAldana/Block_Chain_Attendance | 5ed0d16d1d2bdae16c7131acedbea362ea80163b | [
"Apache-2.0"
] | null | null | null | lib/dbfs_web/controllers/api_v1/block.ex | EnriqueAldana/Block_Chain_Attendance | 5ed0d16d1d2bdae16c7131acedbea362ea80163b | [
"Apache-2.0"
] | null | null | null | defmodule DBFS.Web.Controllers.API.V1.Block do
use DBFS.Web, :controller
@doc "GET: All Blocks"
def index(conn, params) do
render(conn, :index, pager: DBFS.Block.paged(page: params[:page]))
end
@doc "GET: Block Status"
def show(conn, %{hash: hash}) do
with {:ok, block} <- get(hash) do
render(conn, :show, block: block)
end
end
@doc "GET: Block Data"
def file(conn, %{hash: hash}) do
with {:ok, block} <- get(hash) do
render(conn, :file, file: DBFS.Block.File.load!(block))
end
end
@doc "POST: Create a new block"
def create(conn, %{data: data, block: block}) do
transaction = DBFS.Blockchain.File.insert(block, data)
with {:ok, %{block: block}} <- transaction do
render(conn, :show, block: block)
end
end
defp get(hash) do
case DBFS.Block.get(hash) do
nil -> {:error, :not_found}
block -> {:ok, block}
end
end
end
| 19.808511 | 70 | 0.607948 |
032c8d6ee9c31dcd91a8b9b6919107856edc25b9 | 3,287 | ex | Elixir | clients/search_console/lib/google_api/search_console/v1/model/wmx_sitemap.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/search_console/lib/google_api/search_console/v1/model/wmx_sitemap.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/search_console/lib/google_api/search_console/v1/model/wmx_sitemap.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.SearchConsole.V1.Model.WmxSitemap do
@moduledoc """
Contains detailed information about a specific URL submitted as a [sitemap](https://support.google.com/webmasters/answer/156184).
## Attributes
* `contents` (*type:* `list(GoogleApi.SearchConsole.V1.Model.WmxSitemapContent.t)`, *default:* `nil`) - The various content types in the sitemap.
* `errors` (*type:* `String.t`, *default:* `nil`) - Number of errors in the sitemap. These are issues with the sitemap itself that need to be fixed before it can be processed correctly.
* `isPending` (*type:* `boolean()`, *default:* `nil`) - If true, the sitemap has not been processed.
* `isSitemapsIndex` (*type:* `boolean()`, *default:* `nil`) - If true, the sitemap is a collection of sitemaps.
* `lastDownloaded` (*type:* `DateTime.t`, *default:* `nil`) - Date & time in which this sitemap was last downloaded. Date format is in RFC 3339 format (yyyy-mm-dd).
* `lastSubmitted` (*type:* `DateTime.t`, *default:* `nil`) - Date & time in which this sitemap was submitted. Date format is in RFC 3339 format (yyyy-mm-dd).
* `path` (*type:* `String.t`, *default:* `nil`) - The url of the sitemap.
* `type` (*type:* `String.t`, *default:* `nil`) - The type of the sitemap. For example: `rssFeed`.
* `warnings` (*type:* `String.t`, *default:* `nil`) - Number of warnings for the sitemap. These are generally non-critical issues with URLs in the sitemaps.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:contents => list(GoogleApi.SearchConsole.V1.Model.WmxSitemapContent.t()) | nil,
:errors => String.t() | nil,
:isPending => boolean() | nil,
:isSitemapsIndex => boolean() | nil,
:lastDownloaded => DateTime.t() | nil,
:lastSubmitted => DateTime.t() | nil,
:path => String.t() | nil,
:type => String.t() | nil,
:warnings => String.t() | nil
}
field(:contents, as: GoogleApi.SearchConsole.V1.Model.WmxSitemapContent, type: :list)
field(:errors)
field(:isPending)
field(:isSitemapsIndex)
field(:lastDownloaded, as: DateTime)
field(:lastSubmitted, as: DateTime)
field(:path)
field(:type)
field(:warnings)
end
defimpl Poison.Decoder, for: GoogleApi.SearchConsole.V1.Model.WmxSitemap do
def decode(value, options) do
GoogleApi.SearchConsole.V1.Model.WmxSitemap.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SearchConsole.V1.Model.WmxSitemap do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.295775 | 189 | 0.688774 |
032cad6a5210062e522500aeea942631d3d25e3b | 396 | exs | Elixir | clients/url_shortener/test/test_helper.exs | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/url_shortener/test/test_helper.exs | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | null | null | null | clients/url_shortener/test/test_helper.exs | leandrocp/elixir-google-api | a86e46907f396d40aeff8668c3bd81662f44c71e | [
"Apache-2.0"
] | 1 | 2020-11-10T16:58:27.000Z | 2020-11-10T16:58:27.000Z | ExUnit.start()
defmodule GoogleApi.UrlShortener.V1.TestHelper do
defmacro __using__(opts) do
quote do
use ExUnit.Case, unquote(opts)
import GoogleApi.UrlShortener.V1.TestHelper
end
end
def for_scope(scopes) when is_list(scopes), do: for_scope(Enum.join(scopes, " "))
def for_scope(scope) do
{:ok, token} = Goth.Token.for_scope(scope)
token.token
end
end
| 20.842105 | 83 | 0.704545 |
032cc773ccb26561cfe040a1daea11cc085838fd | 14,784 | ex | Elixir | lib/typo/pdf/page.ex | john-vinters/typo | 71a0fabca7cec380a5a76b2199554f87ff8aaf73 | [
"Apache-2.0"
] | null | null | null | lib/typo/pdf/page.ex | john-vinters/typo | 71a0fabca7cec380a5a76b2199554f87ff8aaf73 | [
"Apache-2.0"
] | null | null | null | lib/typo/pdf/page.ex | john-vinters/typo | 71a0fabca7cec380a5a76b2199554f87ff8aaf73 | [
"Apache-2.0"
] | null | null | null | #
# Copyright 2022, John Vinters <[email protected]>
#
# 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.
#
# lib/typo/pdf/page.ex
#
# 21-Apr-2022 - File created.
#
defmodule Typo.PDF.Page do
@moduledoc """
Low-level PDF Page related functions.
"""
use Typo.Utils.Macros
import Typo.PDF, only: [load_page: 2, save_page: 1]
import Typo.Utils.Guards
alias Typo.PDF
alias Typo.PDF.IdMap
alias Typo.Utils.PageSize
@doc """
Adds the current page as a destination.
`options` is a keyword list, and can be one of the following:
* `:type` - specifies how the destination should be displayed, and can be
one of the following options:
* `:fit` - the entire page fits in the window (default if no type
specified).
* `:fit_h` - the optional `:top` option specifies the top coordinate of the
window, and the document page is scaled to fit horizontally.
* `:fit_r` - the required options `:left`, `:top`, `:right` and `:bottom`
specify the visible rectangle, which will be scaled to fit the window.
* `:fit_v` - the optional `:left` option specifies the left coordinate of the
window, and the document page is scaled to fit vertically.
* `:xyz` - the optional `:left`, `:top` and `:zoom` options specify the page
coordinate of the top left of the window, and `:zoom` specifies the
percentage zoom level.
If a destination with the same `dest_id` already exists, then it is overwritten.
"""
@spec add_destination(PDF.t(), Typo.id(), Keyword.t()) :: PDF.t()
def add_destination(%PDF{} = pdf, dest_id, options \\ [])
when is_id(dest_id) and is_list(options) do
page = {:page, pdf.user_page}
dest =
case Keyword.get(options, :type, :fit) do
:fit -> {page, :fit, []}
:fit_h -> {page, :fit_h, add_destination_opts(options, [], [:top])}
:fit_r -> {page, :fit_r, add_destination_opts(options, [:left, :top, :right, :bottom])}
:fit_v -> {page, :fit_v, add_destination_opts(options, [], [:left])}
:xyz -> {page, :xyz, add_destination_opts(options, [], [:left, :top, :zoom])}
other -> raise ArgumentError, "invalid add_destination type: #{inspect(other)}"
end
destinations = IdMap.add_item(pdf.destinations, dest_id, dest)
%PDF{pdf | destinations: destinations}
end
@doc """
Gets default page rotation.
"""
@spec get_default_page_rotation(PDF.t()) :: Typo.page_rotation()
def get_default_page_rotation(%PDF{} = pdf), do: Map.get(pdf.page_rotation, :default)
@doc """
Gets default page size.
"""
@spec get_default_page_size(PDF.t()) :: Typo.page_dimensions()
def get_default_page_size(%PDF{} = pdf), do: Map.get(pdf.page_size, :default)
@doc """
Gets the current page number.
"""
@spec get_page(PDF.t()) :: integer()
def get_page(%PDF{} = pdf), do: pdf.user_page
@doc """
Gets the number of pages in the document.
NOTE: the count always includes the current page (even if blank).
"""
@spec get_page_count(PDF.t()) :: non_neg_integer()
def get_page_count(%PDF{} = pdf) do
pdf
|> get_pages()
|> Enum.count()
end
@doc """
Gets the page height for the current page.
"""
@spec get_page_height(PDF.t()) :: number()
def get_page_height(%PDF{} = pdf) do
{_w, h} =
case Map.get(pdf.page_size, pdf.page) do
{_w, _h} = s -> s
nil -> Map.get(pdf.page_size, :default)
end
h
end
@doc """
Gets the document page layout style.
"""
@spec get_page_layout(PDF.t()) :: Typo.page_layout()
def get_page_layout(%PDF{} = pdf), do: pdf.page_layout
@doc """
Gets page rotation for the current page.
"""
@spec get_page_rotation(PDF.t()) :: Typo.page_rotation()
def get_page_rotation(%PDF{} = pdf) do
case Map.get(pdf.page_rotation, pdf.page) do
r when is_integer(r) -> r
nil -> Map.get(pdf.page_rotation, :default)
end
end
@doc """
Gets the page size for the current page.
"""
@spec get_page_size(PDF.t()) :: Typo.page_dimensions()
def get_page_size(%PDF{} = pdf) do
case Map.get(pdf.page_size, pdf.page) do
{_w, _h} = s -> s
nil -> Map.get(pdf.page_size, :default)
end
end
@doc """
Gets the page width for the current page.
"""
@spec get_page_width(PDF.t()) :: number()
def get_page_width(%PDF{} = pdf) do
{w, _h} =
case Map.get(pdf.page_size, pdf.page) do
{_w, _h} = s -> s
nil -> Map.get(pdf.page_size, :default)
end
w
end
@doc """
Returns the list of page numbers.
"""
@spec get_pages(Typo.PDF.t()) :: [integer()]
def get_pages(%PDF{} = pdf) do
r =
pdf.pages
|> Map.keys()
|> Enum.flat_map(fn p ->
case p do
{:page, page} -> [page]
_ -> []
end
end)
r = if Map.has_key?(pdf.pages, {:page, pdf.user_page}), do: r, else: [pdf.user_page] ++ r
Enum.sort(r)
end
@doc """
Appends a page onto the document.
The page number is automatically allocated, and is the current highest page
number + 1.
The current page is automatically saved before switching to the new page.
NOTE: it is faster to just call `set_page/2` with a new page number if you
are keeping track of page numbers yourself.
"""
@spec new_page(PDF.t()) :: PDF.t()
def new_page(%PDF{} = pdf) do
check_state!(pdf, [:page])
highest =
pdf
|> get_pages()
|> Enum.max()
set_page(pdf, highest + 1)
end
@doc """
Sets default page rotation to `page_rotation`, which should be one of
0, 90, 180 or 270 degrees.
"""
@spec set_default_page_rotation(PDF.t(), Typo.page_rotation()) :: PDF.t()
def set_default_page_rotation(%PDF{} = pdf, page_rotation)
when is_page_rotation(page_rotation) do
new_page_rotation = Map.put(pdf.page_rotation, :default, page_rotation)
%PDF{pdf | page_rotation: new_page_rotation}
end
@doc """
Sets default page size to `page_size`.
"""
@spec set_default_page_size(PDF.t(), atom() | binary() | tuple()) :: PDF.t()
def set_default_page_size(%PDF{} = pdf, page_size) when is_page_dimensions(page_size) do
new_page_size = Map.put(pdf.page_size, :default, page_size)
%PDF{pdf | page_size: new_page_size}
end
@doc """
Sets default page size.
`page_size` sets the default page size and can be either:
* an `atom` - the atom is converted to a binary string and processed as binary
strings are.
* a `binary` string - the string is downcased and then `_` characters converted
into spaces before being used to lookup the paper size.
`page_orientation` can be one of:
* `:portrait` - shortest side is horizontal, longest side vertical.
* `:landscape` - longest side is horizontal, shortest side vertical.
To get the list of supported paper sizes call
`Typo.Utils.PageSize.get_supported_sizes/0`, which will return a list of size
names which can be used as the `page_size` argument.
Raises ArgumentError if the `page_size` is invalid.
"""
@spec set_default_page_size(PDF.t(), atom() | binary() | tuple(), :landscape | :portrait) ::
PDF.t()
def set_default_page_size(%PDF{} = pdf, page_size, page_orientation \\ :portrait)
when (is_atom(page_size) or is_binary(page_size)) and is_page_orientation(page_orientation) do
case PageSize.page_size(page_size, page_orientation) do
{:error, :invalid_page_size} ->
raise ArgumentError, "invalid page size: #{inspect(page_size)}"
{:ok, {_w, _h} = size} ->
set_default_page_size(pdf, size)
end
end
@doc """
Sets the current page number. The current page is saved, and the
desired page number loaded. Any further edits to the page are
appended to whatever is already present on the page.
Raises `Typo.GraphicsStateError` if an attempt is made to change the
page whilst a form is under construction.
"""
@spec set_page(PDF.t(), integer()) :: PDF.t()
def set_page(%PDF{} = pdf, page_number) when is_page_number(page_number) do
check_state!(pdf, [:page])
pdf.form && raise(Typo.GraphicsStateError, "can't change page while form under construction")
pdf
|> save_page()
|> load_page({:page, page_number})
end
@doc """
Sets page layout style to `page_layout`:
* `:single_page` - one page is displayed at a time.
* `:one_column` - pages are displayed in one column.
* `:two_column_left` - pages are displayed in two columns, odd numbered pages on left.
* `:two_column_right` - pages are displayed in two columns, odd numbered pages on right.
* `:two_page_left` - pages are displayed two at a time, odd numbered pages on left.
* `:two_page_right` - pages are displayed two at a time, odd numbered pages on right.
"""
@spec set_page_layout(PDF.t(), Typo.page_layout()) :: PDF.t()
def set_page_layout(%PDF{} = pdf, page_layout) when is_page_layout(page_layout),
do: %PDF{pdf | page_layout: page_layout}
@doc """
Sets page rotation to `page_rotation`, which should be one of
0, 90, 180 or 270 degrees.
"""
@spec set_page_rotation(Typo.PDF.t(), 0 | 90 | 180 | 270) :: Typo.PDF.t()
def set_page_rotation(%PDF{} = pdf, page_rotation) when is_page_rotation(page_rotation) do
new_page_rotation = Map.put(pdf.page_rotation, pdf.page, page_rotation)
%PDF{pdf | page_rotation: new_page_rotation}
end
@doc """
Sets page size to `page_size`, which is a `{width, height}` tuple.
"""
@spec set_page_size(PDF.t(), atom() | binary() | tuple()) :: PDF.t()
def set_page_size(%PDF{} = pdf, page_size) when is_page_dimensions(page_size) do
new_page_size = Map.put(pdf.page_size, pdf.page, page_size)
%PDF{pdf | page_size: new_page_size}
end
@doc """
Sets page size.
`page_size` sets the page size and can be either:
* an `atom` - the atom is converted to a binary string and processed as binary
strings are.
* a `binary` string - the string is downcased and then `_` characters converted
into spaces before being used to lookup the paper size.
`page_orientation` can be one of:
* `:portrait` - shortest side is horizontal, longest side vertical.
* `:landscape` - longest side is horizontal, shortest side vertical.
To get the list of supported paper sizes call
`Typo.Utils.PageSize.get_supported_sizes/0`, which will return a list of size
names which can be used as the `page_size` argument.
Raises ArgumentError if the `page_size` is invalid.
"""
@spec set_page_size(PDF.t(), atom() | binary() | tuple(), :landscape | :portrait) :: PDF.t()
def set_page_size(%PDF{} = pdf, page_size, page_orientation \\ :portrait)
when (is_atom(page_size) or is_binary(page_size)) and is_page_orientation(page_orientation) do
case PageSize.page_size(page_size, page_orientation) do
{:error, :invalid_page_size} ->
raise ArgumentError, "invalid page size: #{inspect(page_size)}"
{:ok, {_w, _h} = size} ->
set_page_size(pdf, size)
end
end
@doc """
Calls function `fun` for each page that `filter` matches.
`filter` may be one of the following:
* a list of pages (e.g. `[2, 4, 6, 8]`)
* a range (e.g. `1..10`, which specifies the pages 1 to 10 inclusive).
* filter function - every page that this function returns true.
* `:even` - every even page in the document.
* `:odd` - every odd page in the document.
* `:all` - every page in the document.
If `filter` is a function, it is passed the page number as a parameter
and should return either `false` to skip the page, or `true` to run
`fun` on the page.
`fun` is a function which receives `pdf` and the page number as
parameters and should return the updated `pdf` struct.
"""
@spec with_page(
PDF.t(),
list(integer) | Range.t() | Typo.filter_fun() | :even | :odd | :all,
Typo.filter_op_fun()
) :: PDF.t()
def with_page(%PDF{} = pdf, filter, fun)
when (is_list(filter) or is_range(filter)) and is_function(fun) do
check_state!(pdf, [:page])
current = pdf.user_page
Enum.reduce(filter, pdf, fn page, acc ->
if Map.has_key?(pdf.pages, {:page, page}) do
acc
|> set_page(page)
|> fun.(page)
else
acc
end
end)
|> set_page(current)
end
def with_page(%PDF{} = pdf, filter, fun) when is_function(filter) and is_function(fun) do
check_state!(pdf, [:page])
current = pdf.user_page
Enum.reduce(get_pages(pdf), pdf, fn page, acc ->
if filter.(page) do
acc
|> set_page(page)
|> fun.(page)
else
acc
end
end)
|> set_page(current)
end
def with_page(%PDF{} = pdf, :all, fun) when is_function(fun),
do: with_page(pdf, get_pages(pdf), fun)
def with_page(%PDF{} = pdf, :even, fun) when is_function(fun),
do: with_page(pdf, fn page -> rem(page, 2) == 0 end, fun)
def with_page(%PDF{} = pdf, :odd, fun) when is_function(fun),
do: with_page(pdf, fn page -> rem(page, 2) != 0 end, fun)
############################################################################
# Internal Functions #
############################################################################
# parses destination options.
defp add_destination_opts(options, required, optional \\ [])
when is_list(options) and is_list(required) and is_list(optional) do
Enum.each(required, fn option -> add_destination_check(options, option, true) end)
Enum.each(optional, fn option -> add_destination_check(options, option, false) end)
Keyword.take(options, required ++ optional)
end
# checks an individual option is present and numeric.
defp add_destination_check(options, option, required)
when is_list(options) and is_atom(option) and is_boolean(required) do
case Keyword.get(options, option) do
nil ->
if required,
do: raise(ArgumentError, "add_destination required option \"#{option}\" not present")
n when is_number(n) ->
:ok
other ->
raise ArgumentError,
"add_destination invalid required option \"#{option}\": #{inspect(other)}"
end
end
end
| 34.301624 | 100 | 0.644142 |
032cf5bf24143b3527caa866276fd62fc15c110b | 781 | ex | Elixir | lib/line_pay/environment.ex | yuki-toida/line_pay | 5c11869650bf09353598b2b95fbc4ae53fbe742e | [
"MIT"
] | null | null | null | lib/line_pay/environment.ex | yuki-toida/line_pay | 5c11869650bf09353598b2b95fbc4ae53fbe742e | [
"MIT"
] | null | null | null | lib/line_pay/environment.ex | yuki-toida/line_pay | 5c11869650bf09353598b2b95fbc4ae53fbe742e | [
"MIT"
] | null | null | null | defmodule LinePay.Environment do
def channel_id do
Application.fetch_env!(:line_pay, :channel_id)
end
def channel_secret do
Application.get_env(:line_pay, :channel_secret, System.get_env("CHANNEL_SECRET"))
end
def sandbox do
Application.get_env(:line_pay, :sandbox, true)
end
def confirm_url_browser do
Application.get_env(:line_pay, :confirm_url_browser, nil)
end
def confirm_url_ios do
Application.get_env(:line_pay, :confirm_url_ios, nil)
end
def confirm_url_android do
Application.get_env(:line_pay, :confirm_url_android, nil)
end
def cancel_url_ios do
Application.get_env(:line_pay, :cancel_url_ios, nil)
end
def cancel_url_android do
Application.get_env(:line_pay, :cancel_url_android, nil)
end
end
| 22.314286 | 85 | 0.747759 |
032d0224255c3735d7f6519b0e9c893c682901b7 | 3,292 | ex | Elixir | lib/cachex/actions/reset.ex | botwerk/cachex | d37996d3be35b0d8281e347d44c024ecf2735131 | [
"MIT"
] | 946 | 2017-06-26T00:36:58.000Z | 2022-03-29T19:52:31.000Z | lib/cachex/actions/reset.ex | botwerk/cachex | d37996d3be35b0d8281e347d44c024ecf2735131 | [
"MIT"
] | 152 | 2017-06-28T10:01:24.000Z | 2022-03-24T18:46:13.000Z | lib/cachex/actions/reset.ex | botwerk/cachex | d37996d3be35b0d8281e347d44c024ecf2735131 | [
"MIT"
] | 84 | 2017-06-30T05:30:31.000Z | 2022-03-01T20:23:16.000Z | defmodule Cachex.Actions.Reset do
@moduledoc false
# Command module to enable complete reset of a cache.
#
# This command allows the caller to reset a cache to an empty state, reset
# the hooks associated with a cache, or both.
#
# This is not executed inside an action context as there is no need to
# notify on reset (as otherwise a reset would always be the first message).
alias Cachex.Actions.Clear
alias Cachex.Services.Locksmith
# add the specification
import Cachex.Spec
##############
# Public API #
##############
@doc """
Resets the internal cache state.
This will either reset a list of cache hooks, all attached cache hooks, the
backing cache table, or all of the aforementioned. This is done by reusing
the `clear()` command to empty the table as needed, and by using the reset
listener exposed by the hook servers.
Nothing in here will notify any hooks of resets occurring as it's basically
quite redundant and it's evident that a reset has happened when you see that
your hook has reinitialized.
"""
def execute(cache() = cache, options) do
Locksmith.transaction(cache, [ ], fn ->
only =
options
|> Keyword.get(:only, [ :cache, :hooks ])
|> List.wrap
reset_cache(cache, only, options)
reset_hooks(cache, only, options)
{ :ok, true }
end)
end
###############
# Private API #
###############
# Handles reset of the backing cache table.
#
# A cache is only emptied if the `:cache` property appears in the list of
# cache components to reset. If not provided, this will short circut and
# leave the cache table exactly as-is.
defp reset_cache(cache, only, _options) do
with true <- :cache in only do
Clear.execute(cache, [])
end
end
# Handles reset of cache hooks.
#
# This has the ability to clear either all hooks or a subset of hooks. We have a small
# optimization here to detect when we want to reset all hooks to avoid filtering without
# a real need to. We also convert the list of hooks to a set to avoid O(N) lookups.
defp reset_hooks(cache(hooks: hooks(pre: pre_hooks, post: post_hooks)), only, opts) do
if :hooks in only do
case Keyword.get(opts, :hooks) do
nil ->
pre_hooks
|> Enum.concat(post_hooks)
|> Enum.each(¬ify_reset/1)
val ->
hook_sets = List.wrap(val)
pre_hooks
|> Enum.concat(post_hooks)
|> Enum.filter(&should_reset?(&1, hook_sets))
|> Enum.each(¬ify_reset/1)
end
end
end
# Determines if a hook should be reset.
#
# This is just sugar around set membership whilst unpacking a hook record,
# used in Enum iterations to avoid inlining functions for readability.
defp should_reset?(hook(module: module), hook_set),
do: module in hook_set
# Notifies a hook of a reset.
#
# This simply sends the hook state back to the hook alongside a reset
# message to signal that the hook needs to reinitialize. Hooks have a
# listener built into the server implementatnion in order to handle this
# automatically, so there's nothing more we need to do.
defp notify_reset(hook(state: state, name: name)),
do: send(name, { :cachex_reset, state })
end
| 33.252525 | 90 | 0.668287 |
032d1150e481bf0baee4d82afbe77156f54c7e17 | 2,224 | ex | Elixir | clients/android_publisher/lib/google_api/android_publisher/v2/model/inappproducts_list_response.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v2/model/inappproducts_list_response.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v2/model/inappproducts_list_response.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.AndroidPublisher.V2.Model.InappproductsListResponse do
@moduledoc """
## Attributes
- inappproduct ([InAppProduct]): Defaults to: `null`.
- kind (String.t): Identifies what kind of resource this is. Value: the fixed string \"androidpublisher#inappproductsListResponse\". Defaults to: `null`.
- pageInfo (PageInfo): Defaults to: `null`.
- tokenPagination (TokenPagination): Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:inappproduct => list(GoogleApi.AndroidPublisher.V2.Model.InAppProduct.t()),
:kind => any(),
:pageInfo => GoogleApi.AndroidPublisher.V2.Model.PageInfo.t(),
:tokenPagination => GoogleApi.AndroidPublisher.V2.Model.TokenPagination.t()
}
field(:inappproduct, as: GoogleApi.AndroidPublisher.V2.Model.InAppProduct, type: :list)
field(:kind)
field(:pageInfo, as: GoogleApi.AndroidPublisher.V2.Model.PageInfo)
field(:tokenPagination, as: GoogleApi.AndroidPublisher.V2.Model.TokenPagination)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidPublisher.V2.Model.InappproductsListResponse do
def decode(value, options) do
GoogleApi.AndroidPublisher.V2.Model.InappproductsListResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidPublisher.V2.Model.InappproductsListResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 39.017544 | 165 | 0.75 |
032d20d9c779ccdd2332a7ea101f72798090b748 | 8,183 | exs | Elixir | apps/bytepack_web/test/bytepack_web/live/product_live_test.exs | dashbitco/bytepack_archive | 79f8e62149d020f2afcc501592ed399f7ce7a60b | [
"Unlicense"
] | 313 | 2020-12-03T17:26:24.000Z | 2022-03-18T09:05:14.000Z | apps/bytepack_web/test/bytepack_web/live/product_live_test.exs | dashbitco/bytepack_archive | 79f8e62149d020f2afcc501592ed399f7ce7a60b | [
"Unlicense"
] | null | null | null | apps/bytepack_web/test/bytepack_web/live/product_live_test.exs | dashbitco/bytepack_archive | 79f8e62149d020f2afcc501592ed399f7ce7a60b | [
"Unlicense"
] | 57 | 2020-12-03T17:41:53.000Z | 2022-03-17T17:28:16.000Z | defmodule BytepackWeb.ProductLiveTest do
use BytepackWeb.ConnCase, async: true
import Phoenix.LiveViewTest
import Bytepack.AccountsFixtures
import Bytepack.OrgsFixtures
import Bytepack.PackagesFixtures
import Bytepack.SalesFixtures
setup :register_and_login_user
setup %{org: org, user: user} do
foo = hex_package_fixture(org, "foo-1.0.0/foo-1.0.0.tar")
bar =
hex_package_fixture(org, "bar-1.0.0/bar-1.0.0.tar", fn r ->
put_in(r.metadata["requirements"]["foo"]["repository"], org.slug)
end)
baz =
hex_package_fixture(org, "baz-1.0.0/baz-1.0.0.tar", fn r ->
put_in(r.metadata["requirements"]["bar"]["repository"], org.slug)
end)
%{foo: foo, bar: bar, baz: baz, user: user}
end
describe "Index" do
test "lists products", %{conn: conn, org: org, foo: foo} do
product1 = product_fixture(org, package_ids: [foo.id])
product2 = product_fixture(org_fixture(user_fixture()))
{:ok, _, html} = live(conn, Routes.product_index_path(conn, :index, org))
assert html =~ product1.name
refute html =~ product2.name
assert html =~ foo.name
end
test "ensures only sellers can access products", %{conn: conn, org: org} do
Ecto.Changeset.change(org, is_seller: false) |> Bytepack.Repo.update!()
{:ok, _, html} =
live(conn, Routes.product_index_path(conn, :index, org))
|> follow_redirect(conn, Routes.dashboard_index_path(conn, :index))
assert html =~ "Access denied"
end
test "show blank banner when there are no products and no packages", %{conn: conn, user: user} do
org_without_packages = org_fixture(user)
{:ok, _, html} = live(conn, Routes.product_index_path(conn, :index, org_without_packages))
assert html =~ "You have not published any packages yet."
assert html =~ "Add new package"
end
test "show blank banner when there are no products but with packages", %{conn: conn, org: org} do
{:ok, _, html} = live(conn, Routes.product_index_path(conn, :index, org))
assert html =~ "You have not added any products yet."
assert html =~ "Add new product"
end
end
describe "New" do
test "renders new product form", %{conn: conn, org: org, foo: foo, bar: bar, baz: baz} do
product_name = unique_product_name()
{:ok, live, html} = live(conn, Routes.product_new_path(conn, :new, org))
assert html =~ "New Product"
assert html =~ foo.name
assert html =~ bar.name
assert html =~ baz.name
refute has_element?(live, "#form-product_package_ids_#{foo.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
html =
live
|> element("#form-product")
|> render_change(%{
product: %{
name: product_name,
description: "Lorem ipsum.",
url: "https://acme.com",
custom_instructions: "one two **strong** <em>em</em>",
package_ids: [baz.id]
}
})
assert html =~ "one two <strong>strong</strong>"
assert html =~ ~s|<div class="markdown-preview"|
refute html =~ ~s|<em>em</em>|
assert has_element?(live, "#form-product_package_ids_#{foo.id}:checked")
assert has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
assert has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
live
|> element("#form-product")
|> render_change(%{product: %{package_ids: [bar.id]}})
assert has_element?(live, "#form-product_package_ids_#{foo.id}:checked")
assert has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
{:ok, _, html} =
live
|> form("#form-product")
|> render_submit()
|> follow_redirect(conn)
assert html =~ "Product created successfully"
assert html =~ product_name
assert html =~ foo.name
assert html =~ bar.name
refute html =~ baz.name
end
test "redirects to index when there is no packages", %{conn: conn, user: user} do
org_without_packages = org_fixture(user)
assert {:error, {:redirect, %{to: path}}} =
live(conn, Routes.product_new_path(conn, :new, org_without_packages))
assert path == Routes.product_index_path(conn, :index, org_without_packages)
package_fixture(org_without_packages)
assert {:ok, _, html} =
live(conn, Routes.product_new_path(conn, :new, org_without_packages))
assert html =~ "New Product"
end
end
describe "Edit" do
test "renders unsold product form", %{conn: conn, org: org, foo: foo, bar: bar, baz: baz} do
product = product_fixture(org, package_ids: [foo.id])
{:ok, live, _html} = live(conn, Routes.product_edit_path(conn, :edit, org, product.id))
assert has_element?(live, "#form-product_package_ids_#{foo.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
html =
live
|> element("#form-product")
|> render_change(%{
product: %{
name: "Updated name",
custom_instructions: "one two *em* <strong>strong</strong>",
package_ids: [baz.id]
}
})
assert html =~ "one two <em>em</em>"
assert html =~ ~s|<div class="markdown-preview"|
refute html =~ ~s|<strong>strong</strong>|
assert has_element?(live, "#form-product_package_ids_#{foo.id}:checked")
assert has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
assert has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
refute html =~ "Note:"
end
test "renders sold product form", %{conn: conn, org: org, foo: foo, bar: bar, baz: baz} do
product = product_fixture(org, package_ids: [foo.id])
sale_fixture(org, product, email: "[email protected]")
{:ok, live, html} = live(conn, Routes.product_edit_path(conn, :edit, org, product.id))
assert html =~ "Note: This product already has sales"
assert has_element?(live, "#form-product_package_ids_#{foo.id}[disabled=disabled]:checked")
assert has_element?(live, "input[type=hidden][value=#{foo.id}]")
refute has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
# Updating only the name does not uncheck packages
{:error, {:live_redirect, _}} =
live
|> element("#form-product")
|> render_submit(%{
product: %{
name: "Updated name without packages"
}
})
{:ok, live, _html} = live(conn, Routes.product_edit_path(conn, :edit, org, product.id))
assert has_element?(live, "#form-product_package_ids_#{foo.id}[disabled=disabled]:checked")
assert has_element?(live, "input[type=hidden][value=#{foo.id}]")
refute has_element?(live, "#form-product_package_ids_#{bar.id}:checked")
refute has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
# Updating name with packages changes only relevant packages
{:error, {:live_redirect, _}} =
live
|> element("#form-product")
|> render_submit(%{
product: %{
name: "Updated name with packages",
package_ids: [bar.id]
}
})
{:ok, live, _html} = live(conn, Routes.product_edit_path(conn, :edit, org, product.id))
assert has_element?(live, "#form-product_package_ids_#{foo.id}[disabled=disabled]::checked")
assert has_element?(live, "input[type=hidden][value=#{foo.id}]")
assert has_element?(live, "#form-product_package_ids_#{bar.id}[disabled=disabled]::checked")
assert has_element?(live, "input[type=hidden][value=#{bar.id}]")
refute has_element?(live, "#form-product_package_ids_#{baz.id}:checked")
end
end
end
| 37.709677 | 101 | 0.633264 |
032d65229960d9cf1422416051231cfa154d15de | 1,285 | ex | Elixir | elixir/lib/homework_web/resolvers/merchants_resolver.ex | Billzabob/divvy-homework | 1be2b35d6436dbb3ff1536ed232b2bc61730081d | [
"MIT"
] | null | null | null | elixir/lib/homework_web/resolvers/merchants_resolver.ex | Billzabob/divvy-homework | 1be2b35d6436dbb3ff1536ed232b2bc61730081d | [
"MIT"
] | null | null | null | elixir/lib/homework_web/resolvers/merchants_resolver.ex | Billzabob/divvy-homework | 1be2b35d6436dbb3ff1536ed232b2bc61730081d | [
"MIT"
] | null | null | null | defmodule HomeworkWeb.Resolvers.MerchantsResolver do
alias Homework.Merchants
@doc """
Get a list of merchants
"""
def merchants(_root, args, _info) do
{:ok, Merchants.list_merchants(args)}
end
def merchant_count(_root, _args, _info) do
{:ok, Merchants.count_merchants()}
end
@doc """
Create a new merchant
"""
def create_merchant(_root, args, _info) do
case Merchants.create_merchant(args) do
{:ok, merchant} ->
{:ok, merchant}
error ->
{:error, "could not create merchant: #{inspect(error)}"}
end
end
@doc """
Updates a merchant for an id with args specified.
"""
def update_merchant(_root, %{id: id} = args, _info) do
merchant = Merchants.get_merchant!(id)
case Merchants.update_merchant(merchant, args) do
{:ok, merchant} ->
{:ok, merchant}
error ->
{:error, "could not update merchant: #{inspect(error)}"}
end
end
@doc """
Deletes a merchant for an id
"""
def delete_merchant(_root, %{id: id}, _info) do
merchant = Merchants.get_merchant!(id)
case Merchants.delete_merchant(merchant) do
{:ok, merchant} ->
{:ok, merchant}
error ->
{:error, "could not update merchant: #{inspect(error)}"}
end
end
end
| 22.155172 | 64 | 0.622568 |
032dddbec67acdb7603b6e89139751bddc6b42ed | 946 | ex | Elixir | lib/ibanity/api/reporting/xs2a/nbb_report_ai_synchronization.ex | ibanity/ibanity-elixir | c2e1feedbfc2376678c9db78c6365a82a654b00b | [
"MIT"
] | 3 | 2018-11-17T18:12:15.000Z | 2020-12-09T06:26:59.000Z | lib/ibanity/api/reporting/xs2a/nbb_report_ai_synchronization.ex | ibanity/ibanity-elixir | c2e1feedbfc2376678c9db78c6365a82a654b00b | [
"MIT"
] | 2 | 2018-12-12T14:14:56.000Z | 2019-07-01T14:13:57.000Z | lib/ibanity/api/reporting/xs2a/nbb_report_ai_synchronization.ex | ibanity/ibanity-elixir | c2e1feedbfc2376678c9db78c6365a82a654b00b | [
"MIT"
] | null | null | null | defmodule Ibanity.Reporting.Xs2a.NbbReportAiSynchronization do
use Ibanity.Resource
@api_schema_path ~w(reporting xs2a customer nbbReportAiSynchronization)
defstruct account_reference_hash: nil,
aspsp_name: nil,
aspsp_type: nil,
external_customer_id_hash: nil,
region: nil,
type: nil,
occurred_at: nil
def find(%Request{} = request) do
request
|> Client.execute(:get, @api_schema_path)
end
def key_mapping do
[
account_reference_hash: {~w(attributes accountReferenceHash), :string},
aspsp_name: {~w(attributes aspspName), :string},
aspsp_type: {~w(attributes aspspType), :string},
external_customer_id_hash: {~w(attributes externalCustomerIdHash), :string},
region: {~w(attributes region), :string},
type: {~w(attributes type), :string},
occurred_at: {~w(attributes occurredAt), :string}
]
end
end
| 30.516129 | 82 | 0.664905 |
032df86a6a12abed9410f3fd483aa4bba5d61385 | 2,066 | ex | Elixir | lib/blog_web/controllers/post_controller.ex | eltoncampos1/blog_elixir | 99fd5d5415192229cda749a88b30bf63d5817c4f | [
"MIT"
] | null | null | null | lib/blog_web/controllers/post_controller.ex | eltoncampos1/blog_elixir | 99fd5d5415192229cda749a88b30bf63d5817c4f | [
"MIT"
] | null | null | null | lib/blog_web/controllers/post_controller.ex | eltoncampos1/blog_elixir | 99fd5d5415192229cda749a88b30bf63d5817c4f | [
"MIT"
] | null | null | null | defmodule BlogWeb.PostController do
use BlogWeb, :controller
alias Blog.Posts
alias Posts.Post
plug BlogWeb.Plug.RequireAuth when action in [:create, :new, :edit, :update, :delete]
plug :check_owner when action in [:edit, :update, :delete]
def index(conn, _params) do
posts = Posts.list_posts()
render(conn, "index.html", posts: posts)
end
def new(conn, _params) do
changeset = Post.changeset(%Post{})
render(conn, "new.html", changeset: changeset)
end
def edit(conn, %{"id" => id}) do
post = Posts.get_post(id)
changeset = Post.changeset(post)
render(conn, "edit.html", post: post, changeset: changeset)
end
def show(conn, %{"id" => id}) do
post = Posts.get_post(id)
render(conn, "show.html", post: post)
end
def create(conn, %{"post" => post}) do
case Posts.create_post(conn.assigns[:user], post) do
{:ok, post} ->
conn
|> put_flash(:info, "Post successfully created!")
|> redirect(to: Routes.post_path(conn, :show, post))
{:error, changeset} ->
render(conn, "new.html", changeset: changeset)
end
end
def delete(conn, %{"id" => id}) do
Posts.delete_post(id)
conn
|> put_flash(:info, "Post Successfully deleted.")
|> redirect(to: Routes.post_path(conn, :index))
end
def update(conn, %{"id" => id, "post" => post_params}) do
post = Posts.get_post(id)
case Posts.update_post(post, post_params) do
{:ok, post} ->
conn
|> put_flash(:info, "Post successfully updated!")
|> redirect(to: Routes.post_path(conn, :show, post))
{:error, changeset} ->
render(conn, "edit.html", changeset: changeset, post: post)
end
end
def check_owner(conn, _params) do
%{params: %{"id" => post_id}} = conn
if Posts.get_post(post_id).user_id == conn.assigns.user.id do
conn
else
conn
|> put_flash(:error, "You don't have authorization to do this operation.")
|> redirect(to: Routes.page_path(conn, :index))
|> halt()
end
end
end
| 26.487179 | 87 | 0.618103 |
032e21a05c8499958379ebb330794e5e9203e988 | 4,009 | ex | Elixir | lib/autox/controllers/resource_controller.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | null | null | null | lib/autox/controllers/resource_controller.ex | autoxjs/autox-phoenix | 6446f4487e3af28955f6560973cff6add34be4d4 | [
"MIT"
] | 20 | 2016-04-05T06:28:58.000Z | 2016-05-12T15:45:37.000Z | lib/autox/controllers/resource_controller.ex | foxnewsnetwork/autox | 66ea3f0f7ba8b3f9e910984a2ed3cdf0ef5ef29a | [
"MIT"
] | null | null | null | defmodule Autox.ResourceController do
alias Fox.ListExt
def infer_changeset_view(module) do
module
|> Module.split
|> ListExt.head
|> Kernel.++(["ChangesetView"])
|> Module.safe_concat
end
defmacro __using__(_) do
quote location: :keep do
alias Fox.AtomExt
alias Autox.ResourceController
alias Autox.ContextUtils
alias Autox.ChangesetUtils
alias Autox.MetaUtils
alias Autox.QueryUtils
@collection_key Module.get_attribute(__MODULE__, :collection_key)
|| AtomExt.infer_collection_key(__MODULE__)
@model_key Module.get_attribute(__MODULE__, :model_key)
|| AtomExt.infer_model_module(__MODULE__)
@repo Module.get_attribute(__MODULE__, :repo)
def repo(conn), do: @repo || ContextUtils.get!(conn, :repo)
def preload_fields, do: []
def model_class(conn) do
conn
|> ContextUtils.get(:parent)
|> case do
nil -> @model_key
parent -> parent |> Ecto.assoc(@collection_key)
end
end
def index_query(conn, params) do
conn |> model_class |> QueryUtils.construct(params)
end
def index_meta(conn, params) do
conn |> model_class |> QueryUtils.meta(params)
end
def index(conn, params) do
models = conn
|> index_query(params)
|> repo(conn).all
meta = conn
|> index_meta(params)
|> repo(conn).one
|> MetaUtils.from_conn(conn)
render(conn, "index.json", data: models, meta: meta)
end
def create(conn, params) do
make_params = params
|> ChangesetUtils.activemodel_paramify
case conn |> ContextUtils.get(:parent) do
nil -> struct(@model_key)
parent -> parent |> Ecto.build_assoc(@collection_key)
end
|> @model_key.create_changeset(make_params)
|> repo(conn).insert
|> case do
{:ok, model} ->
meta = conn |> MetaUtils.from_conn
conn
|> put_status(:created)
|> render("show.json", data: model, meta: meta)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render("error.json", changeset: changeset)
end
end
def show(conn, %{"model" => nil}) do
show_core(conn, nil)
end
def show(conn, %{"model" => model}) do
model = repo(conn)
|> apply(:preload, [model, preload_fields])
show_core(conn, model)
end
defp show_core(conn, model) do
meta = conn |> MetaUtils.from_conn
conn |> render("show.json", data: model, meta: meta)
end
def delete(conn, %{"model" => model}) do
model
|> repo(conn).delete
|> case do
{:ok, model} ->
conn
|> assign(:data, model)
|> assign(:meta, MetaUtils.from_conn(conn))
|> send_resp(:no_content, "")
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render("error.json", changeset: changeset)
end
end
def update(conn, %{"model" => model}=params) do
change_params = params
|> ChangesetUtils.activemodel_paramify
|| params
|> Dict.fetch!(@model_key |> Atom.to_string)
model
|> @model_key.update_changeset(change_params)
|> repo(conn).update
|> case do
{:ok, model} ->
meta = conn |> MetaUtils.from_conn
conn |> render("show.json", data: model, meta: meta)
{:error, changeset} ->
conn
|> put_status(:unprocessable_entity)
|> render("error.json", changeset: changeset)
end
end
defoverridable [create: 2,
delete: 2,
show: 2,
update: 2,
index: 2,
index_query: 2,
index_meta: 2,
preload_fields: 0]
end
end
end | 29.477941 | 72 | 0.556747 |
032e3f4b69c641371f4cd8520f48ed35868963a4 | 410 | ex | Elixir | lib/brando/sequence/migration.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | lib/brando/sequence/migration.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | lib/brando/sequence/migration.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | defmodule Brando.Sequence.Migration do
@moduledoc """
Sequencing macro for migrations.
## Usage
use Brando.Sequence.Migration
alter table(:example) do
sequenced()
end
"""
defmacro __using__(_) do
quote do
import unquote(__MODULE__)
end
end
defmacro sequenced do
quote do
Ecto.Migration.add(:sequence, :integer, default: 0)
end
end
end
| 15.769231 | 57 | 0.641463 |
032e438d7bda8cb1f4320dd0b4b951b37c3dc041 | 185 | ex | Elixir | lib/hexpm/repository/download.ex | findmypast/hexfmp | 38a50f5e1057833fd98748faac230bf4b9cc26a3 | [
"Apache-2.0"
] | null | null | null | lib/hexpm/repository/download.ex | findmypast/hexfmp | 38a50f5e1057833fd98748faac230bf4b9cc26a3 | [
"Apache-2.0"
] | null | null | null | lib/hexpm/repository/download.ex | findmypast/hexfmp | 38a50f5e1057833fd98748faac230bf4b9cc26a3 | [
"Apache-2.0"
] | null | null | null | defmodule Hexpm.Repository.Download do
use Hexpm.Web, :schema
schema "downloads" do
belongs_to :release, Release
field :downloads, :integer
field :day, :date
end
end
| 18.5 | 38 | 0.708108 |
032e4825b58be3e124e7aaf60b84f04abc3691be | 61 | exs | Elixir | test/nacha_test.exs | tokkenops/nacha.ex | 0232ed5578d01b89cb554cd8cd0e574504aa5137 | [
"Apache-2.0"
] | 8 | 2020-02-06T17:38:02.000Z | 2022-01-01T01:41:07.000Z | test/nacha_test.exs | tokkenops/nacha.ex | 0232ed5578d01b89cb554cd8cd0e574504aa5137 | [
"Apache-2.0"
] | 2 | 2019-06-28T03:40:09.000Z | 2019-06-28T04:10:34.000Z | test/nacha_test.exs | tokkenops/nacha.ex | 0232ed5578d01b89cb554cd8cd0e574504aa5137 | [
"Apache-2.0"
] | 2 | 2020-01-18T22:27:17.000Z | 2021-12-29T17:21:57.000Z | defmodule NachaTest do
use ExUnit.Case
doctest Nacha
end
| 12.2 | 22 | 0.786885 |
032e6bf435de6e6bff63ad0dc91193019ab11d73 | 3,047 | exs | Elixir | test/runlet_cmd_tls_test.exs | msantos/runlet_net | 41174f0b3e3cc0a8d05f221aa6eb2e837f146ff1 | [
"0BSD"
] | 1 | 2020-04-25T15:31:46.000Z | 2020-04-25T15:31:46.000Z | test/runlet_cmd_tls_test.exs | msantos/runlet_net | 41174f0b3e3cc0a8d05f221aa6eb2e837f146ff1 | [
"0BSD"
] | null | null | null | test/runlet_cmd_tls_test.exs | msantos/runlet_net | 41174f0b3e3cc0a8d05f221aa6eb2e837f146ff1 | [
"0BSD"
] | null | null | null | defmodule RunletCmdTLSTest do
use ExUnit.Case
url = Runlet.Cmd.TLS.exec("httpbin.org")
urlport = Runlet.Cmd.TLS.exec("httpbin.org:443")
arity2 = Runlet.Cmd.TLS.exec("httpbin.org", 443)
# ensure bad certificates can be dumped
untrusted_root = Runlet.Cmd.TLS.exec("untrusted-root.badssl.com")
expired = Runlet.Cmd.TLS.exec("expired.badssl.com")
sha1 = Runlet.Cmd.TLS.exec("sha1-intermediate.badssl.com")
des3 = Runlet.Cmd.TLS.exec("3des.badssl.com")
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: _,
host: "httpbin.org:443",
service: "tls",
time: ""
},
query: "tls httpbin.org:443"
}
| _
] = url
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: _,
host: "httpbin.org:443",
service: "tls",
time: ""
},
query: "tls httpbin.org:443"
}
| _
] = urlport
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: _,
host: "httpbin.org:443",
service: "tls",
time: ""
},
query: "tls httpbin.org:443"
}
| _
] = arity2
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: <<"[protocol: :\"tlsv", _::binary>>,
host: "untrusted-root.badssl.com:443",
service: "tls",
time: ""
},
query: "tls untrusted-root.badssl.com:443"
}
| _
] = untrusted_root
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: <<"[protocol: :\"tlsv", _::binary>>,
host: "expired.badssl.com:443",
service: "tls",
time: ""
},
query: "tls expired.badssl.com:443"
}
| _
] = expired
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: <<"[protocol: :\"tlsv", _::binary>>,
host: "sha1-intermediate.badssl.com:443",
service: "tls",
time: ""
},
query: "tls sha1-intermediate.badssl.com:443"
}
| _
] = sha1
assert [
%Runlet.Event{
attr: %{},
event: %Runlet.Event.Stdout{
description: <<"[protocol: :\"tlsv", _::binary>>,
host: "3des.badssl.com:443",
service: "tls",
time: ""
},
query: "tls 3des.badssl.com:443"
}
| _
] = des3
end
| 27.205357 | 67 | 0.423039 |
032e722225576a51f8faf2ff7f08dbf504d30dbb | 452 | exs | Elixir | test/models/sale__type_test.exs | GoberInfinity/ExamplePhoenix | 4f2e016000a55dd4dbc28409dd214f0923e38e32 | [
"MIT"
] | null | null | null | test/models/sale__type_test.exs | GoberInfinity/ExamplePhoenix | 4f2e016000a55dd4dbc28409dd214f0923e38e32 | [
"MIT"
] | null | null | null | test/models/sale__type_test.exs | GoberInfinity/ExamplePhoenix | 4f2e016000a55dd4dbc28409dd214f0923e38e32 | [
"MIT"
] | null | null | null | defmodule Otherpool.Sale_TypeTest do
use Otherpool.ModelCase
alias Otherpool.Sale_Type
@valid_attrs %{name_sale: "some content"}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = Sale_Type.changeset(%Sale_Type{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = Sale_Type.changeset(%Sale_Type{}, @invalid_attrs)
refute changeset.valid?
end
end
| 23.789474 | 65 | 0.743363 |
032e83acd6e5d7822bfc3b799714caedafb0632c | 714 | exs | Elixir | test/models/user_board_test.exs | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | test/models/user_board_test.exs | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | test/models/user_board_test.exs | drdean/jelly | 44ca6d90e0c7ce62ccd458795f54dac4d10e8cfc | [
"MIT"
] | null | null | null | defmodule JellyBoard.UserBoardTest do
use JellyBoard.ModelCase, async: true
import JellyBoard.Factory
alias JellyBoard.UserBoard
@valid_attrs %{}
@invalid_attrs %{}
setup do
user = create(:user)
board = create(:board)
{:ok, user: user, board: board}
end
test "changeset with valid attributes", %{user: user, board: board} do
attributes = @valid_attrs
|> Map.put(:user_id, user.id)
|> Map.put(:board_id, board.id)
changeset = UserBoard.changeset(%UserBoard{}, attributes)
assert changeset.valid?
end
test "changeset with invalid attributes", _ do
changeset = UserBoard.changeset(%UserBoard{}, @invalid_attrs)
refute changeset.valid?
end
end
| 22.3125 | 72 | 0.686275 |
032e89a456781aad8c637bb450d1b2e810baf799 | 509 | ex | Elixir | api/web/views/category_view.ex | AlexYanai/microblogger | 833320759cddd276bc31dabaec6f0c9e2eabb05a | [
"MIT"
] | null | null | null | api/web/views/category_view.ex | AlexYanai/microblogger | 833320759cddd276bc31dabaec6f0c9e2eabb05a | [
"MIT"
] | null | null | null | api/web/views/category_view.ex | AlexYanai/microblogger | 833320759cddd276bc31dabaec6f0c9e2eabb05a | [
"MIT"
] | null | null | null | defmodule Microblogger.CategoryView do
use Microblogger.Web, :view
def render("index.json", %{categories: categories}) do
%{data: render_many(categories, Microblogger.CategoryView, "category.json")}
end
def render("show.json", %{category: category}) do
%{data: render_one(category, Microblogger.CategoryView, "category.json")}
end
def render("category.json", %{category: category}) do
%{id: category.id,
name: category.name,
description: category.description}
end
end
| 28.277778 | 80 | 0.707269 |
032e8df30e401aceb2cbe0adacb4c89c4de8d2e2 | 1,368 | ex | Elixir | clients/service_usage/lib/google_api/service_usage/v1/connection.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/service_usage/lib/google_api/service_usage/v1/connection.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/service_usage/lib/google_api/service_usage/v1/connection.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ServiceUsage.V1.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.ServiceUsage.V1.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [
# View and manage your data across Google Cloud Platform services
"https://www.googleapis.com/auth/cloud-platform",
# View your data across Google Cloud Platform services
"https://www.googleapis.com/auth/cloud-platform.read-only",
# Manage your Google API service configuration
"https://www.googleapis.com/auth/service.management"
],
otp_app: :google_api_service_usage,
base_url: "https://serviceusage.googleapis.com/"
end
| 35.076923 | 74 | 0.736842 |
032ebece82452682a0f497be5958e9ce1c73f536 | 1,762 | exs | Elixir | mix.exs | noizu/que | 065b069c3dafe0f90bf858ae77080af7b310ae62 | [
"MIT"
] | null | null | null | mix.exs | noizu/que | 065b069c3dafe0f90bf858ae77080af7b310ae62 | [
"MIT"
] | null | null | null | mix.exs | noizu/que | 065b069c3dafe0f90bf858ae77080af7b310ae62 | [
"MIT"
] | null | null | null | defmodule Que.Mixfile do
use Mix.Project
@app :que
@name "Que"
@version "0.10.1"
@github "https://github.com/noizu/#{@app}"
# NOTE:
# To publish package or update docs, use the `docs`
# mix environment to not include support modules
# that are normally included in the `dev` environment
#
# MIX_ENV=docs hex.publish
#
def project do
[
# Project
app: @app,
version: @version,
elixir: "~> 1.4",
description: description(),
package: package(),
deps: deps(),
elixirc_paths: elixirc_paths(Mix.env),
# ExDoc
name: @name,
source_url: @github,
homepage_url: @github,
docs: [
main: @name,
canonical: "https://hexdocs.pm/#{@app}",
extras: ["README.md"]
]
]
end
def application do
[
mod: {Que, []},
applications: [:logger, :memento, :ex_utils]
]
end
defp deps do
[
{:memento, "~> 0.3.0" },
{:ex_utils, "~> 0.1.6" },
{:ex_doc, ">= 0.0.0", only: :docs },
{:inch_ex, ">= 0.0.0", only: :docs },
]
end
defp description do
"Simple Background Job Processing with Mnesia, with Task Priority and MultiNode support."
end
# Compilation Paths
defp elixirc_paths(:dev), do: elixirc_paths(:test)
defp elixirc_paths(:test), do: ["lib", "test/support.ex"]
defp elixirc_paths(:noizu_test), do: ["lib", "test/support.ex"]
defp elixirc_paths(_), do: ["lib"]
defp package do
[
name: @app,
maintainers: ["Keith Brings"],
licenses: ["MIT"],
files: ~w(mix.exs lib README.md),
links: %{"Github" => @github}
]
end
end
| 21.228916 | 93 | 0.53235 |
032ebee63abd868745ba8c5a69346c8111254c58 | 129 | exs | Elixir | test/bard_test.exs | sizumita/Bard | b2e5bb2d44b4a5700e38d56be7f6d88eff3f9218 | [
"MIT"
] | null | null | null | test/bard_test.exs | sizumita/Bard | b2e5bb2d44b4a5700e38d56be7f6d88eff3f9218 | [
"MIT"
] | 1 | 2020-07-01T11:23:35.000Z | 2020-07-01T11:23:35.000Z | test/bard_test.exs | sizumita/Bard | b2e5bb2d44b4a5700e38d56be7f6d88eff3f9218 | [
"MIT"
] | null | null | null | defmodule BardTest do
use ExUnit.Case
doctest Bard
test "greets the world" do
assert Bard.hello() == :world
end
end
| 14.333333 | 33 | 0.689922 |
032eca80b2affe63cc39dcf354817837870e6ffb | 1,806 | ex | Elixir | clients/android_publisher/lib/google_api/android_publisher/v2/model/track.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v2/model/track.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | clients/android_publisher/lib/google_api/android_publisher/v2/model/track.ex | mocknen/elixir-google-api | dac4877b5da2694eca6a0b07b3bd0e179e5f3b70 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.AndroidPublisher.V2.Model.Track do
@moduledoc """
## Attributes
- track (String.t): Identifier for this track. Defaults to: `null`.
- userFraction (float()): Defaults to: `null`.
- versionCodes ([integer()]): Version codes to make active on this track. Note that this list should contain all versions you wish to be active, including those you wish to retain from previous releases. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:track => any(),
:userFraction => any(),
:versionCodes => list(any())
}
field(:track)
field(:userFraction)
field(:versionCodes, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AndroidPublisher.V2.Model.Track do
def decode(value, options) do
GoogleApi.AndroidPublisher.V2.Model.Track.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AndroidPublisher.V2.Model.Track do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.444444 | 226 | 0.726467 |
032ece994a37fbb7d477eb9bf22f21066792bd9c | 291 | ex | Elixir | lib/phone/nanp/ca/bc.ex | davidkovsky/phone | 83108ab1042efe62778c7363f5d02ef888883408 | [
"Apache-2.0"
] | 97 | 2016-04-05T13:08:41.000Z | 2021-12-25T13:08:34.000Z | lib/phone/nanp/ca/bc.ex | davidkovsky/phone | 83108ab1042efe62778c7363f5d02ef888883408 | [
"Apache-2.0"
] | 70 | 2016-06-14T00:56:00.000Z | 2022-02-10T19:43:14.000Z | lib/phone/nanp/ca/bc.ex | davidkovsky/phone | 83108ab1042efe62778c7363f5d02ef888883408 | [
"Apache-2.0"
] | 31 | 2016-04-21T22:26:12.000Z | 2022-01-24T21:40:00.000Z | defmodule Phone.NANP.CA.BC do
@moduledoc false
use Helper.Area
def regex, do: ~r/^(1)(604|778|236|250|672)([2-9].{6})$/
def area_name, do: "British Columbia"
def area_type, do: "province"
def area_abbreviation, do: "BC"
matcher(["1604", "1778", "1236", "1250", "1672"])
end
| 22.384615 | 58 | 0.639175 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.