hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
list | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
list | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
list | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7368a1b48a0629f7b153ab8ce38ade74d9252070
| 10,153 |
exs
|
Elixir
|
test/credo/code/token_test.exs
|
isaacsanders/credo
|
5623570bb2e3944345f1bf11819ca613533b5e10
|
[
"MIT"
] | null | null | null |
test/credo/code/token_test.exs
|
isaacsanders/credo
|
5623570bb2e3944345f1bf11819ca613533b5e10
|
[
"MIT"
] | null | null | null |
test/credo/code/token_test.exs
|
isaacsanders/credo
|
5623570bb2e3944345f1bf11819ca613533b5e10
|
[
"MIT"
] | 1 |
2020-06-30T16:32:44.000Z
|
2020-06-30T16:32:44.000Z
|
defmodule Credo.Code.TokenTest do
use Credo.TestHelper
alias Credo.Code.Token
@heredoc_interpolations_source """
def fun() do
a = \"\"\"
MyModule.\#{fun(Module.value() + 1)}.SubModule.\#{name}"
\"\"\"
end
"""
@heredoc_interpolations_position {1, 5, 1, 60}
@multiple_interpolations_source ~S[a = "MyModule.#{fun(Module.value() + 1)}.SubModule.#{name}"]
@multiple_interpolations_position {1, 5, 1, 60}
@single_interpolations_bin_string_source ~S[a = "MyModule.SubModule.#{name}"]
@single_interpolations_bin_string_position {1, 5, 1, 33}
@no_interpolations_source ~S[134 + 145]
@no_interpolations_position {1, 7, 1, 10}
# Elixir >= 1.6.0
if Version.match?(System.version(), ">= 1.6.0-rc") do
@single_interpolations_list_string_source ~S[a = 'MyModule.SubModule.#{name}']
@single_interpolations_list_string_position {1, 5, 1, 33}
@tag :token_position
test "should give correct token position" do
source = @no_interpolations_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:int, {1, 1, 134}, '134'},
{:dual_op, {1, 5, nil}, :+},
{:int, {1, 7, 145}, '145'}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @no_interpolations_position == position
end
@tag :token_position
test "should give correct token position with a single interpolation" do
source = @single_interpolations_bin_string_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, nil}, :a},
{:match_op, {1, 3, nil}, :=},
{:bin_string, {1, 5, nil},
[
"MyModule.SubModule.",
{{1, 25, 1}, [{:identifier, {1, 27, nil}, :name}]}
]}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @single_interpolations_bin_string_position == position
end
@tag :token_position
test "should give correct token position with a single interpolation with list string" do
source = @single_interpolations_list_string_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, nil}, :a},
{:match_op, {1, 3, nil}, :=},
{:list_string, {1, 5, nil},
[
"MyModule.SubModule.",
{{1, 25, 1}, [{:identifier, {1, 27, nil}, :name}]}
]}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @single_interpolations_list_string_position == position
end
@tag :token_position
test "should give correct token position with multiple interpolations" do
source = @multiple_interpolations_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, nil}, :a},
{:match_op, {1, 3, nil}, :=},
{:bin_string, {1, 5, nil},
[
"MyModule.",
{{1, 15, 1},
[
{:paren_identifier, {1, 17, nil}, :fun},
{:"(", {1, 20, nil}},
{:alias, {1, 21, nil}, :Module},
{:., {1, 27, nil}},
{:paren_identifier, {1, 28, nil}, :value},
{:"(", {1, 33, nil}},
{:")", {1, 34, nil}},
{:dual_op, {1, 36, nil}, :+},
{:int, {1, 38, 1}, '1'},
{:")", {1, 39, nil}}
]},
".SubModule.",
{{1, 52, 1}, [{:identifier, {1, 54, nil}, :name}]}
]}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @multiple_interpolations_position == position
end
@tag :to_be_implemented
@tag :token_position
test "should give correct token position with multiple interpolations in heredoc" do
source = @heredoc_interpolations_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, nil}, :def},
{:paren_identifier, {1, 5, nil}, :fun},
{:"(", {1, 8, nil}},
{:")", {1, 9, nil}},
{:do, {1, 11, nil}},
{:eol, {1, 13, 1}},
{:identifier, {2, 3, nil}, :a},
{:match_op, {2, 5, nil}, :=},
{:bin_heredoc, {2, 7, nil},
[
"MyModule.",
{{3, 10, 3},
[
{:paren_identifier, {3, 12, nil}, :fun},
{:"(", {3, 15, nil}},
{:alias, {3, 16, nil}, :Module},
{:., {3, 22, nil}},
{:paren_identifier, {3, 23, nil}, :value},
{:"(", {3, 28, nil}},
{:")", {3, 29, nil}},
{:dual_op, {3, 31, nil}, :+},
{:int, {3, 33, 1}, '1'},
{:")", {3, 34, nil}}
]},
".SubModule.",
{{3, 47, 3}, [{:identifier, {3, 49, nil}, :name}]},
"\"\n"
]},
{:eol, {4, 1, 1}},
{:end, {5, 1, nil}},
{:eol, {5, 4, 1}}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @heredoc_interpolations_position == position
end
@tag needs_elixir: "1.7.0"
test "should give correct token position for map" do
source = ~S(%{"some-atom-with-quotes": "#{filename} world"})
tokens = Credo.Code.to_tokens(source)
expected = [
{:%{}, {1, 1, nil}},
{:"{", {1, 2, nil}},
{:kw_identifier_unsafe, {1, 3, nil}, ["some-atom-with-quotes"]},
{:bin_string, {1, 28, nil},
[{{1, 29, 1}, [{:identifier, {1, 31, nil}, :filename}]}, " world"]},
{:"}", {1, 47, nil}}
]
assert expected == tokens
position = expected |> Enum.take(4) |> List.last() |> Token.position()
assert {1, 28, 1, 47} == position
end
test "should give correct token position for map /2" do
source = ~S(%{some_atom_with_quotes: "#{filename} world"})
tokens = Credo.Code.to_tokens(source)
expected = [
{:%{}, {1, 1, nil}},
{:"{", {1, 2, nil}},
{:kw_identifier, {1, 3, nil}, :some_atom_with_quotes},
{:bin_string, {1, 26, nil},
[{{1, 27, 1}, [{:identifier, {1, 29, nil}, :filename}]}, " world"]},
{:"}", {1, 45, nil}}
]
assert expected == tokens
position = expected |> Enum.take(4) |> List.last() |> Token.position()
assert {1, 26, 1, 45} == position
end
end
# Elixir <= 1.5.x
if Version.match?(System.version(), "< 1.6.0-rc") do
@tag :token_position
test "token position" do
source = @no_interpolations_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:number, {1, 1, 4}, 134},
{:dual_op, {1, 5, 6}, :+},
{:number, {1, 7, 10}, 145}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @no_interpolations_position == position
end
@tag :token_position
test "should give correct token position with a single interpolation" do
source = @single_interpolations_bin_string_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, 2}, :a},
{:match_op, {1, 3, 4}, :=},
{:bin_string, {1, 5, 33},
[
"MyModule.SubModule.",
{{1, 25, 32}, [{:identifier, {1, 27, 31}, :name}]}
]}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @single_interpolations_bin_string_position == position
end
@tag :token_position
test "should give correct token position with multiple interpolations" do
source = @multiple_interpolations_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, 2}, :a},
{:match_op, {1, 3, 4}, :=},
{:bin_string, {1, 5, 60},
[
"MyModule.",
{{1, 15, 41},
[
{:paren_identifier, {1, 17, 20}, :fun},
{:"(", {1, 20, 21}},
{:aliases, {1, 21, 27}, [:Module]},
{:., {1, 27, 28}},
{:paren_identifier, {1, 28, 33}, :value},
{:"(", {1, 33, 34}},
{:")", {1, 34, 35}},
{:dual_op, {1, 36, 37}, :+},
{:number, {1, 38, 39}, 1},
{:")", {1, 39, 40}}
]},
".SubModule.",
{{1, 52, 59}, [{:identifier, {1, 54, 58}, :name}]}
]}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @multiple_interpolations_position == position
end
@tag :to_be_implemented
@tag :token_position
test "should give correct token position with multiple interpolations in heredoc" do
source = @heredoc_interpolations_source
tokens = Credo.Code.to_tokens(source)
expected = [
{:identifier, {1, 1, 4}, :def},
{:paren_identifier, {1, 5, 8}, :fun},
{:"(", {1, 8, 9}},
{:")", {1, 9, 10}},
{:do, {1, 11, 13}},
{:eol, {1, 13, 14}},
{:identifier, {2, 3, 4}, :a},
{:match_op, {2, 5, 6}, :=},
{:bin_string, {2, 7, 1},
[
"MyModule.",
{{3, 10, 36},
[
{:paren_identifier, {3, 12, 15}, :fun},
{:"(", {3, 15, 16}},
{:aliases, {3, 16, 22}, [:Module]},
{:., {3, 22, 23}},
{:paren_identifier, {3, 23, 28}, :value},
{:"(", {3, 28, 29}},
{:")", {3, 29, 30}},
{:dual_op, {3, 31, 32}, :+},
{:number, {3, 33, 34}, 1},
{:")", {3, 34, 35}}
]},
".SubModule.",
{{3, 47, 54}, [{:identifier, {3, 49, 53}, :name}]},
"\"\n"
]},
{:eol, {4, 1, 2}},
{:end, {5, 1, 4}},
{:eol, {5, 4, 5}}
]
assert expected == tokens
position = expected |> List.last() |> Token.position()
assert @heredoc_interpolations_position == position
end
end
end
| 29.687135 | 97 | 0.489707 |
7368b747160dc55a5ab520182bfff34dbe273017
| 505 |
exs
|
Elixir
|
apps/core/priv/repo/migrations/20191109171611_add_terraform_installations.exs
|
michaeljguarino/forge
|
50ee583ecb4aad5dee4ef08fce29a8eaed1a0824
|
[
"Apache-2.0"
] | 59 |
2021-09-16T19:29:39.000Z
|
2022-03-31T20:44:24.000Z
|
apps/core/priv/repo/migrations/20191109171611_add_terraform_installations.exs
|
svilenkov/plural
|
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
|
[
"Apache-2.0"
] | 111 |
2021-08-15T09:56:37.000Z
|
2022-03-31T23:59:32.000Z
|
apps/core/priv/repo/migrations/20191109171611_add_terraform_installations.exs
|
svilenkov/plural
|
ac6c6cc15ac4b66a3b5e32ed4a7bee4d46d1f026
|
[
"Apache-2.0"
] | 4 |
2021-12-13T09:43:01.000Z
|
2022-03-29T18:08:44.000Z
|
defmodule Core.Repo.Migrations.AddTerraformInstallations do
use Ecto.Migration
def change do
create table(:terraform_installations, primary_key: false) do
add :id, :uuid, primary_key: true
add :terraform_id, references(:terraform, type: :uuid, on_delete: :delete_all)
add :installation_id, references(:installations, type: :uuid, on_delete: :delete_all)
timestamps()
end
create unique_index(:terraform_installations, [:terraform_id, :installation_id])
end
end
| 31.5625 | 91 | 0.738614 |
7368bab68a6d48d96422e3155b40be70b8894673
| 9,955 |
exs
|
Elixir
|
lib/elixir/test/elixir/path_test.exs
|
elkinsd/elixir
|
810965e193cb57b82363e7c0c97b719743b7964f
|
[
"Apache-2.0"
] | null | null | null |
lib/elixir/test/elixir/path_test.exs
|
elkinsd/elixir
|
810965e193cb57b82363e7c0c97b719743b7964f
|
[
"Apache-2.0"
] | null | null | null |
lib/elixir/test/elixir/path_test.exs
|
elkinsd/elixir
|
810965e193cb57b82363e7c0c97b719743b7964f
|
[
"Apache-2.0"
] | null | null | null |
Code.require_file "test_helper.exs", __DIR__
defmodule PathTest do
use ExUnit.Case, async: true
doctest Path
import PathHelpers
if :file.native_name_encoding == :utf8 do
test "wildcard with utf8" do
File.mkdir_p(tmp_path("héllò"))
assert Path.wildcard(tmp_path("héllò")) == [tmp_path("héllò")]
after
File.rm_rf tmp_path("héllò")
end
end
test "wildcard" do
hello = tmp_path("wildcard/.hello")
world = tmp_path("wildcard/.hello/world")
File.mkdir_p(world)
assert Path.wildcard(tmp_path("wildcard/*/*")) == []
assert Path.wildcard(tmp_path("wildcard/**/*")) == []
assert Path.wildcard(tmp_path("wildcard/?hello/world")) == []
assert Path.wildcard(tmp_path("wildcard/*/*"), match_dot: true) == [world]
assert Path.wildcard(tmp_path("wildcard/**/*"), match_dot: true) == [hello, world]
assert Path.wildcard(tmp_path("wildcard/?hello/world"), match_dot: true) == [world]
after
File.rm_rf tmp_path("wildcard")
end
if windows?() do
test "relative win" do
assert Path.relative("C:/usr/local/bin") == "usr/local/bin"
assert Path.relative("C:\\usr\\local\\bin") == "usr\\local\\bin"
assert Path.relative("C:usr\\local\\bin") == "usr\\local\\bin"
assert Path.relative("/usr/local/bin") == "usr/local/bin"
assert Path.relative("usr/local/bin") == "usr/local/bin"
assert Path.relative("../usr/local/bin") == "../usr/local/bin"
assert Path.relative_to("D:/usr/local/foo", "D:/usr/") == "local/foo"
assert Path.relative_to("D:/usr/local/foo", "d:/usr/") == "local/foo"
assert Path.relative_to("d:/usr/local/foo", "D:/usr/") == "local/foo"
assert Path.relative_to("D:/usr/local/foo", "d:/") == "usr/local/foo"
assert Path.relative_to("D:/usr/local/foo", "D:/") == "usr/local/foo"
assert Path.relative_to("D:/usr/local/foo", "d:") == "D:/usr/local/foo"
assert Path.relative_to("D:/usr/local/foo", "D:") == "D:/usr/local/foo"
end
test "type win" do
assert Path.type("C:/usr/local/bin") == :absolute
assert Path.type('C:\\usr\\local\\bin') == :absolute
assert Path.type("C:usr\\local\\bin") == :volumerelative
assert Path.type("/usr/local/bin") == :volumerelative
assert Path.type('usr/local/bin') == :relative
assert Path.type("../usr/local/bin") == :relative
end
test "split win" do
assert Path.split("C:\\foo\\bar") == ["c:/", "foo", "bar"]
assert Path.split("C:/foo/bar") == ["c:/", "foo", "bar"]
end
else
test "relative Unix" do
assert Path.relative("/usr/local/bin") == "usr/local/bin"
assert Path.relative("usr/local/bin") == "usr/local/bin"
assert Path.relative("../usr/local/bin") == "../usr/local/bin"
assert Path.relative(['/usr', ?/, "local/bin"]) == "usr/local/bin"
end
test "type Unix" do
assert Path.type("/usr/local/bin") == :absolute
assert Path.type("usr/local/bin") == :relative
assert Path.type("../usr/local/bin") == :relative
assert Path.type('/usr/local/bin') == :absolute
assert Path.type('usr/local/bin') == :relative
assert Path.type('../usr/local/bin') == :relative
assert Path.type(['/usr/', 'local/bin']) == :absolute
assert Path.type(['usr/', 'local/bin']) == :relative
assert Path.type(['../usr', '/local/bin']) == :relative
end
end
test "relative to cwd" do
assert Path.relative_to_cwd(__ENV__.file) ==
Path.relative_to(__ENV__.file, System.cwd!)
assert Path.relative_to_cwd(to_charlist(__ENV__.file)) ==
Path.relative_to(to_charlist(__ENV__.file), to_charlist(System.cwd!))
end
test "absname" do
assert (Path.absname("/") |> strip_drive_letter_if_windows) == "/"
assert (Path.absname("/foo") |> strip_drive_letter_if_windows) == "/foo"
assert (Path.absname("/./foo") |> strip_drive_letter_if_windows) == "/foo"
assert (Path.absname("/foo/bar") |> strip_drive_letter_if_windows) == "/foo/bar"
assert (Path.absname("/foo/bar/") |> strip_drive_letter_if_windows) == "/foo/bar"
assert (Path.absname("/foo/bar/../bar") |> strip_drive_letter_if_windows) == "/foo/bar/../bar"
assert Path.absname("bar", "/foo") == "/foo/bar"
assert Path.absname("bar/", "/foo") == "/foo/bar"
assert Path.absname("bar/.", "/foo") == "/foo/bar/."
assert Path.absname("bar/../bar", "/foo") == "/foo/bar/../bar"
assert Path.absname("bar/../bar", "foo") == "foo/bar/../bar"
assert Path.absname(["bar/", ?., ?., ["/bar"]], "/foo") == "/foo/bar/../bar"
end
test "expand path with user home" do
home = System.user_home! |> Path.absname
assert home == Path.expand("~")
assert home == Path.expand('~')
assert is_binary Path.expand("~/foo")
assert is_binary Path.expand('~/foo')
assert Path.expand("~/file") == Path.join(home, "file")
assert Path.expand("~/file", "whatever") == Path.join(home, "file")
assert Path.expand("file", Path.expand("~")) == Path.expand("~/file")
assert Path.expand("file", "~") == Path.join(home, "file")
assert Path.expand("~file") == Path.join(System.cwd!, "file")
end
test "expand path" do
assert (Path.expand("/") |> strip_drive_letter_if_windows) == "/"
assert (Path.expand("/foo/../..") |> strip_drive_letter_if_windows) == "/"
assert (Path.expand("/foo") |> strip_drive_letter_if_windows) == "/foo"
assert (Path.expand("/./foo") |> strip_drive_letter_if_windows) == "/foo"
assert (Path.expand("/../foo") |> strip_drive_letter_if_windows) == "/foo"
assert (Path.expand("/foo/bar") |> strip_drive_letter_if_windows) == "/foo/bar"
assert (Path.expand("/foo/bar/") |> strip_drive_letter_if_windows) == "/foo/bar"
assert (Path.expand("/foo/bar/.") |> strip_drive_letter_if_windows)== "/foo/bar"
assert (Path.expand("/foo/bar/../bar") |> strip_drive_letter_if_windows) == "/foo/bar"
assert (Path.expand("bar", "/foo") |> strip_drive_letter_if_windows)== "/foo/bar"
assert (Path.expand("bar/", "/foo") |> strip_drive_letter_if_windows)== "/foo/bar"
assert (Path.expand("bar/.", "/foo") |> strip_drive_letter_if_windows)== "/foo/bar"
assert (Path.expand("bar/../bar", "/foo") |> strip_drive_letter_if_windows)== "/foo/bar"
assert (Path.expand("../bar/../bar", "/foo/../foo/../foo") |> strip_drive_letter_if_windows) == "/bar"
assert "/bar" ==
(Path.expand(['..', ?/, "bar/../bar"], '/foo/../foo/../foo') |> strip_drive_letter_if_windows)
assert (Path.expand("/..") |> strip_drive_letter_if_windows) == "/"
assert Path.expand("bar/../bar", "foo") == Path.expand("foo/bar")
end
test "relative to" do
assert Path.relative_to("/usr/local/foo", "/usr/local") == "foo"
assert Path.relative_to("/usr/local/foo", "/") == "usr/local/foo"
assert Path.relative_to("/usr/local/foo", "/etc") == "/usr/local/foo"
assert Path.relative_to("/usr/local/foo", "/usr/local/foo") == "/usr/local/foo"
assert Path.relative_to("usr/local/foo", "usr/local") == "foo"
assert Path.relative_to("usr/local/foo", "etc") == "usr/local/foo"
assert Path.relative_to('usr/local/foo', "etc") == "usr/local/foo"
assert Path.relative_to("usr/local/foo", "usr/local") == "foo"
assert Path.relative_to(["usr", ?/, 'local/foo'], 'usr/local') == "foo"
end
test "rootname" do
assert Path.rootname("~/foo/bar.ex", ".ex") == "~/foo/bar"
assert Path.rootname("~/foo/bar.exs", ".ex") == "~/foo/bar.exs"
assert Path.rootname("~/foo/bar.old.ex", ".ex") == "~/foo/bar.old"
assert Path.rootname([?~, '/foo/bar', ".old.ex"], '.ex') == "~/foo/bar.old"
end
test "extname" do
assert Path.extname("foo.erl") == ".erl"
assert Path.extname("~/foo/bar") == ""
assert Path.extname('foo.erl') == ".erl"
assert Path.extname('~/foo/bar') == ""
end
test "dirname" do
assert Path.dirname("/foo/bar.ex") == "/foo"
assert Path.dirname("foo/bar.ex") == "foo"
assert Path.dirname("~/foo/bar.ex") == "~/foo"
assert Path.dirname("/foo/bar/baz/") == "/foo/bar/baz"
assert Path.dirname([?~, "/foo", '/bar.ex']) == "~/foo"
end
test "basename" do
assert Path.basename("foo") == "foo"
assert Path.basename("/foo/bar") == "bar"
assert Path.basename("/") == ""
assert Path.basename("~/foo/bar.ex", ".ex") == "bar"
assert Path.basename("~/foo/bar.exs", ".ex") == "bar.exs"
assert Path.basename("~/for/bar.old.ex", ".ex") == "bar.old"
assert Path.basename([?~, "/for/bar", '.old.ex'], ".ex") == "bar.old"
end
test "join" do
assert Path.join([""]) == ""
assert Path.join(["foo"]) == "foo"
assert Path.join(["/", "foo", "bar"]) == "/foo/bar"
assert Path.join(["~", "foo", "bar"]) == "~/foo/bar"
assert Path.join(['/foo/', "/bar/"]) == "/foo/bar"
assert Path.join(["/", ""]) == "/"
assert Path.join(["/", "", "bar"]) == "/bar"
end
test "join two" do
assert Path.join("/foo", "bar") == "/foo/bar"
assert Path.join("~", "foo") == "~/foo"
assert Path.join("", "bar") == "bar"
assert Path.join("bar", "") == "bar"
assert Path.join("", "/bar") == "bar"
assert Path.join("/bar", "") == "/bar"
assert Path.join("foo", "/bar") == "foo/bar"
assert Path.join("/foo", "/bar") == "/foo/bar"
assert Path.join("/foo", "/bar") == "/foo/bar"
assert Path.join("/foo", "./bar") == "/foo/./bar"
assert Path.join([?/, "foo"], "./bar") == "/foo/./bar"
end
test "split" do
assert Path.split("") == []
assert Path.split("foo") == ["foo"]
assert Path.split("/foo/bar") == ["/", "foo", "bar"]
assert Path.split([?/, "foo/bar"]) == ["/", "foo", "bar"]
end
if windows?() do
defp strip_drive_letter_if_windows([_d, ?: | rest]), do: rest
defp strip_drive_letter_if_windows(<<_d, ?:, rest::binary>>), do: rest
else
defp strip_drive_letter_if_windows(path), do: path
end
end
| 40.303644 | 106 | 0.591261 |
73699d1dada663af0c7f446d1054ce31b5a65abe
| 351 |
exs
|
Elixir
|
priv/repo/seeds.exs
|
moroz/renraku
|
845e6a72573f138094ba8f868ac91b7f3440bdab
|
[
"BSD-3-Clause"
] | null | null | null |
priv/repo/seeds.exs
|
moroz/renraku
|
845e6a72573f138094ba8f868ac91b7f3440bdab
|
[
"BSD-3-Clause"
] | null | null | null |
priv/repo/seeds.exs
|
moroz/renraku
|
845e6a72573f138094ba8f868ac91b7f3440bdab
|
[
"BSD-3-Clause"
] | null | null | null |
# Script for populating the database. You can run it as:
#
# mix run priv/repo/seeds.exs
#
# Inside the script, you can read and write to any of your
# repositories directly:
#
# Renraku.Repo.insert!(%Renraku.SomeSchema{})
#
# We recommend using the bang functions (`insert!`, `update!`
# and so on) as they will fail if something goes wrong.
| 29.25 | 61 | 0.706553 |
7369bfc5605f2558d2e097cef56de3173214ca7b
| 1,018 |
ex
|
Elixir
|
lib/rocketpay/users/create.ex
|
willianns/rocketpay
|
34c882b47ab1cb2a83b51c6bb17eeceb7714ab92
|
[
"Unlicense"
] | 2 |
2021-03-01T09:15:57.000Z
|
2021-03-02T23:30:57.000Z
|
lib/rocketpay/users/create.ex
|
willianns/rocketpay
|
34c882b47ab1cb2a83b51c6bb17eeceb7714ab92
|
[
"Unlicense"
] | null | null | null |
lib/rocketpay/users/create.ex
|
willianns/rocketpay
|
34c882b47ab1cb2a83b51c6bb17eeceb7714ab92
|
[
"Unlicense"
] | null | null | null |
defmodule Rocketpay.Users.Create do
alias Ecto.Multi
alias Rocketpay.{Repo, User, Account}
def call(params) do
Multi.new()
|> Multi.insert(:create_user, User.changeset(params))
|> Multi.run(:create_account, fn repo, %{create_user: user} ->
insert_account(repo, user.id)
end)
|> Multi.run(:preload_data, fn repo, %{create_user: user} ->
preload_data(repo, user)
end)
|> run_transaction()
# params
# |> User.changeset()
# |> Repo.insert()
end
defp insert_account(repo, user_id) do
user_id
|> account_changeset()
|> repo.insert()
end
defp preload_data(repo, user) do
{:ok, repo.preload(user, :account)}
end
defp account_changeset(user_id) do
params = %{user_id: user_id, balance: "0.00"}
Account.changeset(params)
end
defp run_transaction(multi) do
case Repo.transaction(multi) do
{:error, _operation, reason, _changes} -> {:error, reason}
{:ok, %{preload_data: user}} -> {:ok, user}
end
end
end
| 24.238095 | 66 | 0.638507 |
7369dd7364301b99d1abd8b8f242532c1a7e94ea
| 590 |
exs
|
Elixir
|
priv/repo/migrations/20200527145236_create_test_tables.exs
|
jokawachi-hg/flop
|
0d8132e5da9f6b08913f16dba26a5c20a9b49db7
|
[
"MIT"
] | null | null | null |
priv/repo/migrations/20200527145236_create_test_tables.exs
|
jokawachi-hg/flop
|
0d8132e5da9f6b08913f16dba26a5c20a9b49db7
|
[
"MIT"
] | null | null | null |
priv/repo/migrations/20200527145236_create_test_tables.exs
|
jokawachi-hg/flop
|
0d8132e5da9f6b08913f16dba26a5c20a9b49db7
|
[
"MIT"
] | null | null | null |
defmodule Flop.Repo.Migrations.CreateTestTables do
use Ecto.Migration
def change do
create table(:owners) do
add :age, :integer
add :email, :string
add :name, :string
add :tags, {:array, :string}
end
create table(:pets) do
add :age, :integer
add :family_name, :string
add :given_name, :string
add :name, :string
add :owner_id, references(:owners)
add :species, :string
add :tags, {:array, :string}
end
create table(:fruits) do
add :family, :string
add :name, :string
end
end
end
| 21.071429 | 50 | 0.6 |
7369f776d332debbe5f37ff95de0cdba15b7d2f4
| 272 |
exs
|
Elixir
|
config/test.exs
|
feihong/elixir-quickstart
|
bbdb839c3db4f1470b4172b7036dc6d9ed9c6251
|
[
"Apache-2.0"
] | null | null | null |
config/test.exs
|
feihong/elixir-quickstart
|
bbdb839c3db4f1470b4172b7036dc6d9ed9c6251
|
[
"Apache-2.0"
] | null | null | null |
config/test.exs
|
feihong/elixir-quickstart
|
bbdb839c3db4f1470b4172b7036dc6d9ed9c6251
|
[
"Apache-2.0"
] | null | null | null |
use Mix.Config
# We don't run a server during test. If one is required,
# you can enable the server option below.
config :quickstart, QuickstartWeb.Endpoint,
http: [port: 4001],
server: false
# Print only warnings and errors during test
config :logger, level: :warn
| 24.727273 | 56 | 0.742647 |
736a3b77e40f578d8840f2150256d1fc5e0d8c20
| 1,588 |
ex
|
Elixir
|
clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/local_object_reference.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/local_object_reference.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1 |
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/cloud_run/lib/google_api/cloud_run/v1alpha1/model/local_object_reference.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1 |
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.CloudRun.V1alpha1.Model.LocalObjectReference do
@moduledoc """
LocalObjectReference contains enough information to let you locate the referenced object inside the same namespace.
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t()
}
field(:name)
end
defimpl Poison.Decoder, for: GoogleApi.CloudRun.V1alpha1.Model.LocalObjectReference do
def decode(value, options) do
GoogleApi.CloudRun.V1alpha1.Model.LocalObjectReference.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.CloudRun.V1alpha1.Model.LocalObjectReference do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.787234 | 165 | 0.751259 |
736a74f5dd4b8924a446bda4a16f39a0df0dc1f5
| 2,134 |
ex
|
Elixir
|
clients/display_video/lib/google_api/display_video/v1/model/exit_event.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1 |
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/display_video/lib/google_api/display_video/v1/model/exit_event.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1 |
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/display_video/lib/google_api/display_video/v1/model/exit_event.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DisplayVideo.V1.Model.ExitEvent do
@moduledoc """
Exit event of the creative.
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the click tag of the exit event. The name must be unique within one creative. Leave it empty or unset for creatives containing image assets only.
* `reportingName` (*type:* `String.t`, *default:* `nil`) - The name used to identify this event in reports. Leave it empty or unset for creatives containing image assets only.
* `type` (*type:* `String.t`, *default:* `nil`) - Required. The type of the exit event.
* `url` (*type:* `String.t`, *default:* `nil`) - Required. The click through URL of the exit event. This is required when type is: * `EXIT_EVENT_TYPE_DEFAULT` * `EXIT_EVENT_TYPE_BACKUP`
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t() | nil,
:reportingName => String.t() | nil,
:type => String.t() | nil,
:url => String.t() | nil
}
field(:name)
field(:reportingName)
field(:type)
field(:url)
end
defimpl Poison.Decoder, for: GoogleApi.DisplayVideo.V1.Model.ExitEvent do
def decode(value, options) do
GoogleApi.DisplayVideo.V1.Model.ExitEvent.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DisplayVideo.V1.Model.ExitEvent do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.107143 | 211 | 0.704311 |
736a820af27668fc64c5587f2a20001b6511b701
| 2,884 |
ex
|
Elixir
|
lib/chat_api/widget_settings.ex
|
webdeb/papercups
|
c9ccbf7365de0085232f5d3b1633f8aac698cf9c
|
[
"MIT"
] | 1 |
2020-08-13T15:11:12.000Z
|
2020-08-13T15:11:12.000Z
|
lib/chat_api/widget_settings.ex
|
webdeb/papercups
|
c9ccbf7365de0085232f5d3b1633f8aac698cf9c
|
[
"MIT"
] | null | null | null |
lib/chat_api/widget_settings.ex
|
webdeb/papercups
|
c9ccbf7365de0085232f5d3b1633f8aac698cf9c
|
[
"MIT"
] | null | null | null |
defmodule ChatApi.WidgetSettings do
@moduledoc """
The WidgetSettings context.
"""
import Ecto.Query, warn: false
alias ChatApi.Repo
alias ChatApi.WidgetSettings.WidgetSetting
@doc """
Returns the list of widget_settings.
## Examples
iex> list_widget_settings()
[%WidgetSetting{}, ...]
"""
def list_widget_settings do
Repo.all(WidgetSetting)
end
@doc """
Gets a single widget_setting.
Raises `Ecto.NoResultsError` if the Widget config does not exist.
## Examples
iex> get_widget_setting!(123)
%WidgetSetting{}
iex> get_widget_setting!(456)
** (Ecto.NoResultsError)
"""
def get_widget_setting!(id), do: Repo.get!(WidgetSetting, id)
def get_settings_by_account(account_id) do
WidgetSetting
|> where(account_id: ^account_id)
|> preload(:account)
|> Repo.one()
end
def create_or_update(nil, params) do
create_widget_setting(params)
end
def create_or_update(account_id, params) do
existing = get_settings_by_account(account_id)
if existing do
update_widget_setting(existing, params)
else
create_widget_setting(params)
end
end
@doc """
Creates a widget_setting.
## Examples
iex> create_widget_setting(%{field: value})
{:ok, %WidgetSetting{}}
iex> create_widget_setting(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_widget_setting(attrs \\ %{}) do
%WidgetSetting{}
|> WidgetSetting.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a widget_setting.
## Examples
iex> update_widget_setting(widget_setting, %{field: new_value})
{:ok, %WidgetSetting{}}
iex> update_widget_setting(widget_setting, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_widget_setting(%WidgetSetting{} = widget_setting, attrs) do
widget_setting
|> WidgetSetting.changeset(attrs)
|> Repo.update()
end
def update_widget_metadata(account_id, metadata) do
attrs = Map.take(metadata, ["host", "pathname", "last_seen_at"])
{:ok, settings} = create_or_update(account_id, %{account_id: account_id})
update_widget_setting(settings, attrs)
end
@doc """
Deletes a widget_setting.
## Examples
iex> delete_widget_setting(widget_setting)
{:ok, %WidgetSetting{}}
iex> delete_widget_setting(widget_setting)
{:error, %Ecto.Changeset{}}
"""
def delete_widget_setting(%WidgetSetting{} = widget_setting) do
Repo.delete(widget_setting)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking widget_setting changes.
## Examples
iex> change_widget_setting(widget_setting)
%Ecto.Changeset{data: %WidgetSetting{}}
"""
def change_widget_setting(%WidgetSetting{} = widget_setting, attrs \\ %{}) do
WidgetSetting.changeset(widget_setting, attrs)
end
end
| 21.684211 | 79 | 0.677184 |
736a9c7960463a51baa230321cbd6fd7a1a5ee17
| 3,655 |
ex
|
Elixir
|
lib/fire_act/changeset_params.ex
|
arathunku/fire-act
|
2577361f66463ab0741ba9db6f35850f64a0c992
|
[
"MIT"
] | 2 |
2019-06-03T18:24:10.000Z
|
2019-08-23T08:29:43.000Z
|
lib/fire_act/changeset_params.ex
|
arathunku/fire-act
|
2577361f66463ab0741ba9db6f35850f64a0c992
|
[
"MIT"
] | null | null | null |
lib/fire_act/changeset_params.ex
|
arathunku/fire-act
|
2577361f66463ab0741ba9db6f35850f64a0c992
|
[
"MIT"
] | null | null | null |
defmodule FireAct.ChangesetParams do
@callback cast(any, Map.t()) :: Ecto.Changeset.t()
@callback validate_params(FireAct.Action.t(), Map.t()) :: Ecto.Changeset.t()
@moduledoc """
Params validation based on Ecto.Changeset.
## Examples
iex> {:ok, %FireAct.Action{} = action} = FireAct.run(RegisterUser, %{"age" => 18})
iex> action.assigns[:permitted_params]
%{age: 18}
iex> {:error, %FireAct.Action{} = action} = FireAct.run(RegisterUser, %{"age" => "n"})
iex> action.assigns[:permitted_params] == nil
true
iex> action.assigns[:error].errors
[age: {"is invalid", [type: :integer, validation: :cast]}]
"""
defmacro __using__(opts) when is_list(opts) do
define_changeset_helpers(opts)
end
defmacro __using__([]) do
define_changeset_helpers([])
end
defmacro __using__(schema) do
define_changeset_helpers(schema: schema)
end
def define_changeset_helpers(opts) do
quote do
@behaviour FireAct.ChangesetParams
opts = unquote(opts)
if opts[:schema] do
@schema opts[:schema]
def schema(), do: @schema
end
@changeset_action opts[:changeset_action] || :insert
@error_key opts[:error_key] || :error
def error_key(), do: @error_key
plug(:validate_passed_params)
if opts[:halt_on_error] != false do
plug(:halt_on_params_error)
end
import Ecto.Changeset
if opts[:schema] do
def new(params), do: cast(params)
def new(data, params), do: cast(data, params)
def validate_params(_action, changeset), do: changeset
def data(_action), do: %{}
def process_params(%FireAct.Action{} = action, params) do
validate_params(action, cast(data(action), params))
|> apply_action(@changeset_action)
end
def cast(params) do
FireAct.ChangesetParams.cast(schema(), %{}, params)
end
def cast(data, params) do
FireAct.ChangesetParams.cast(schema(), data, params)
end
defoverridable new: 1, new: 2, validate_params: 2, data: 1
else
def process_params(%FireAct.Action{} = action, params) do
validate_params(action, params)
|> apply_action(@changeset_action)
end
end
def validate_passed_params(%FireAct.Action{} = action, _) do
FireAct.ChangesetParams.validate_passed_params(__MODULE__, action)
end
def halt_on_params_error(%FireAct.Action{} = action, _) do
if !!Map.get(action.assigns, error_key()) do
action
|> FireAct.Action.fail()
else
action
end
end
def action(%FireAct.Action{} = action, _opts \\ []) do
apply(__MODULE__, :handle, [action, action.assigns[:permitted_params]])
end
defoverridable action: 2
end
end
def validate_passed_params(module, action) do
module.process_params(action, action.params)
|> case do
{:ok, permitted_params} ->
action
|> FireAct.Action.assign(:permitted_params, permitted_params)
{:error, error} ->
action
|> FireAct.Action.assign(module.error_key(), error)
end
end
def cast(schema, data, params) do
types = Enum.into(schema, %{})
changeset =
{data, types}
|> Ecto.Changeset.cast(params, Map.keys(types))
|> Map.put(:action, :insert)
initial_map =
Map.keys(types)
|> Enum.reduce(%{}, fn key, acc ->
Map.put(acc, key, Ecto.Changeset.get_field(changeset, key))
end)
put_in(changeset.changes, Map.merge(initial_map, changeset.changes))
end
end
| 26.875 | 90 | 0.622709 |
736aa22bab4fe25598fe6e37bfadf4c1cd0b68f9
| 72 |
exs
|
Elixir
|
test/views/page_view_test.exs
|
NorifumiKawamoto/ginjyo
|
8e28438db4675bb55ba090614c6834190adb61b1
|
[
"MIT"
] | null | null | null |
test/views/page_view_test.exs
|
NorifumiKawamoto/ginjyo
|
8e28438db4675bb55ba090614c6834190adb61b1
|
[
"MIT"
] | null | null | null |
test/views/page_view_test.exs
|
NorifumiKawamoto/ginjyo
|
8e28438db4675bb55ba090614c6834190adb61b1
|
[
"MIT"
] | null | null | null |
defmodule Ginjyo.PageViewTest do
use Ginjyo.ConnCase, async: true
end
| 18 | 34 | 0.805556 |
736aad140247790c1bb15c9e63f9b0b95466bc5c
| 47 |
exs
|
Elixir
|
test/tipalti_test.exs
|
gadabout/tipalti-elixir
|
4cff4108b343b8d7c30d117494838ad00a46128a
|
[
"MIT"
] | 8 |
2018-04-26T21:40:07.000Z
|
2019-08-14T10:55:53.000Z
|
test/tipalti_test.exs
|
gadabout/tipalti-elixir
|
4cff4108b343b8d7c30d117494838ad00a46128a
|
[
"MIT"
] | 198 |
2018-04-26T21:53:20.000Z
|
2022-03-23T15:20:11.000Z
|
test/tipalti_test.exs
|
gadabout/tipalti-elixir
|
4cff4108b343b8d7c30d117494838ad00a46128a
|
[
"MIT"
] | 1 |
2018-11-09T03:10:36.000Z
|
2018-11-09T03:10:36.000Z
|
defmodule TipaltiTest do
use ExUnit.Case
end
| 11.75 | 24 | 0.808511 |
736ab26ed3915a044bc10caaaa4f73caa2acf72a
| 3,537 |
ex
|
Elixir
|
lib/ueberauth/strategy/disqus.ex
|
cgorshing/ueberauth_disqus
|
6530fd0ce9b575ee3350544bf172aa0be5316dff
|
[
"MIT"
] | null | null | null |
lib/ueberauth/strategy/disqus.ex
|
cgorshing/ueberauth_disqus
|
6530fd0ce9b575ee3350544bf172aa0be5316dff
|
[
"MIT"
] | null | null | null |
lib/ueberauth/strategy/disqus.ex
|
cgorshing/ueberauth_disqus
|
6530fd0ce9b575ee3350544bf172aa0be5316dff
|
[
"MIT"
] | null | null | null |
defmodule Ueberauth.Strategy.Disqus do
require Logger
@moduledoc """
Disqus Strategy for Überauth.
"""
use Ueberauth.Strategy,
default_scope: "read",
oauth2_module: Ueberauth.Strategy.Disqus.OAuth
alias Ueberauth.Auth.Info
alias Ueberauth.Auth.Credentials
alias Ueberauth.Auth.Extra
alias Ueberauth.Strategy.Disqus.OAuth
@doc """
Handles initial request for Disqus authentication
The initial entry point from ueberauth
"""
def handle_request!(conn) do
Logger.warn "handle_request!"
scopes = conn.params["scope"] || option(conn, :default_scope) || "read"
send_redirect_uri = Keyword.get(options(conn), :send_redirect_uri, true)
opts = if send_redirect_uri do
[redirect_uri: callback_url(conn), scope: scopes]
else
[scope: scopes]
end
opts =
if conn.params["state"], do: Keyword.put(opts, :state, conn.params["state"]), else: opts
module = option(conn, :oauth2_module)
redirect!(conn, apply(module, :authorize_url!, [opts]))
end
@doc """
Handles the callback from Disqus
"""
def handle_callback!(%Plug.Conn{params: %{"oauth_token" => oauth_token, "oauth_token_secret" => oauth_token_secret, "oauth_verifier" => oauth_verifier}} = conn) do
IO.puts "+++ handle_callback! with params"
case OAuth.access_token(oauth_token, oauth_token_secret, oauth_verifier) do
{:ok, access_token} -> fetch_user(conn, access_token)
{:error, reason} -> set_errors!(conn, [error("access_error", reason)])
end
end
@doc false
def handle_callback!(conn) do
IO.puts "+++ handle_callback! with just conn"
set_errors!(conn, [error("missing_code", "No code received")])
end
@doc false
def handle_cleanup!(conn) do
IO.puts "+++ handle_cleanup!"
conn
|> put_private(:disqus_user_map, nil)
|> put_private(:disqus_tokens, nil)
|> put_session(:disqus_request_token, nil)
|> put_session(:disqus_request_token_secret, nil)
end
@doc """
Fetches the uid/kaid field from the response
"""
def uid(conn) do
IO.puts "+++ uid"
conn.private.disqus_user_map["kaid"]
end
@doc """
Includes the credentials from the Disqus response
"""
def credentials(conn) do
IO.puts "+++ credentials"
%Credentials{
token: conn.private.disqus_tokens["oauth_token"],
}
end
@doc """
Fetches the fields to populate the info section of the `Ueberauth.Auth` struct.
"""
def info(conn) do
IO.puts "+++ info(conn)"
m = conn.private.disqus_user_map
#TODO We really need the kaid
%Ueberauth.Auth.Info{
name: m["nickname"],
nickname: m["username"],
#email: m["email"] || Enum.find(user["emails"] || [], &(&1["primary"]))["email"],
email: m["email"],
#kaid: m["kaid"],
image: m["avatar_url"]
}
end
@doc """
Stores the raw information (including the token) obtained from the callback
"""
def extra(conn) do
IO.puts "+++ extra(conn)"
%Extra{
raw_info: %{
token: conn.private.disqus_tokens["oauth_token"],
user: conn.private.disqus_user_map
}
}
end
defp fetch_user(conn, tokens) do
case OAuth.get_info(tokens) do
{:ok, person} ->
conn
|> put_private(:disqus_user_map, person)
|> put_private(:disqus_tokens, tokens)
{:error, reason} ->
set_errors!(conn, [error("get_info", reason)])
end
end
defp option(conn, key) do
Keyword.get(options(conn), key, Keyword.get(default_options(), key))
end
end
| 26.395522 | 165 | 0.651117 |
736ae9ce046a9161fbec677b992f06be4d1619ef
| 2,256 |
ex
|
Elixir
|
lib/elixir_sense/providers/suggestion/reducers/overridable.ex
|
J3RN/elixir_sense
|
0e978dcfbf0a0602743917e3e71dfa40bf7467cf
|
[
"MIT",
"Unlicense"
] | null | null | null |
lib/elixir_sense/providers/suggestion/reducers/overridable.ex
|
J3RN/elixir_sense
|
0e978dcfbf0a0602743917e3e71dfa40bf7467cf
|
[
"MIT",
"Unlicense"
] | null | null | null |
lib/elixir_sense/providers/suggestion/reducers/overridable.ex
|
J3RN/elixir_sense
|
0e978dcfbf0a0602743917e3e71dfa40bf7467cf
|
[
"MIT",
"Unlicense"
] | null | null | null |
defmodule ElixirSense.Providers.Suggestion.Reducers.Overridable do
@moduledoc false
alias ElixirSense.Core.Introspection
alias ElixirSense.Core.State
@doc """
A reducer that adds suggestions of overridable functions.
"""
def add_overridable(_hint, %State.Env{scope: {_f, _a}}, _metadata, _cursor_context, acc),
do: {:cont, acc}
def add_overridable(hint, env, metadata, _cursor_context, acc) do
%State.Env{protocol: protocol, behaviours: behaviours, module: module} = env
# overridable behaviour callbacks are returned by Reducers.Callbacks
behaviour_callbacks =
Enum.flat_map(behaviours, fn
mod when is_atom(mod) and (protocol == nil or mod != elem(protocol, 0)) ->
for %{
name: name,
arity: arity
} <-
Introspection.get_callbacks_with_docs(mod) do
{name, arity}
end
_ ->
[]
end)
list =
for {{^module, name, arity}, %State.ModFunInfo{overridable: {true, origin}} = info}
when is_integer(arity) <- metadata.mods_funs_to_positions,
def_prefix?(hint, info.type) or String.starts_with?("#{name}", hint),
{name, arity} not in behaviour_callbacks do
spec =
case metadata.specs[{module, name, arity}] do
%State.SpecInfo{specs: specs} -> specs |> Enum.join("\n")
nil -> ""
end
args = info.params |> hd |> Enum.map_join(", ", &(&1 |> elem(0) |> Atom.to_string()))
subtype =
case State.ModFunInfo.get_category(info) do
:function -> :callback
:macro -> :macrocallback
end
%{
type: :callback,
subtype: subtype,
name: Atom.to_string(name),
arity: arity,
args: args,
origin: inspect(origin),
summary: "",
metadata: %{},
spec: spec
}
end
{:cont, %{acc | result: acc.result ++ Enum.sort(list)}}
end
defp def_prefix?(hint, type) when type in [:defmacro, :defmacrop] do
String.starts_with?("defmacro", hint)
end
defp def_prefix?(hint, type) when type in [:def, :defp] do
String.starts_with?("def", hint)
end
end
| 30.08 | 93 | 0.578901 |
736b028a9a5bbe51dc7a567217bf8534e850f3ed
| 142 |
ex
|
Elixir
|
lib/empex_cookbook_web/views/tag_view.ex
|
ludwikbukowski/recipes
|
cac5711d32874c3011da8da3329b70d0e28e725e
|
[
"MIT"
] | 4 |
2019-02-11T12:15:36.000Z
|
2021-03-22T16:23:47.000Z
|
lib/empex_cookbook_web/views/tag_view.ex
|
ludwikbukowski/recipes
|
cac5711d32874c3011da8da3329b70d0e28e725e
|
[
"MIT"
] | null | null | null |
lib/empex_cookbook_web/views/tag_view.ex
|
ludwikbukowski/recipes
|
cac5711d32874c3011da8da3329b70d0e28e725e
|
[
"MIT"
] | null | null | null |
defmodule EmpexCookbookWeb.TagView do
use EmpexCookbookWeb, :view
def render("index.json", %{tags: tags}) do
%{tags: tags}
end
end
| 17.75 | 44 | 0.697183 |
736b0715253071d72da79d015ed954017cfeef5e
| 3,879 |
ex
|
Elixir
|
lib/mappers/ingest/validate.ex
|
evandiewald/mappers
|
7359cfb39a4d9d26c42f5917ee04a7e41d3291bc
|
[
"Apache-2.0"
] | null | null | null |
lib/mappers/ingest/validate.ex
|
evandiewald/mappers
|
7359cfb39a4d9d26c42f5917ee04a7e41d3291bc
|
[
"Apache-2.0"
] | null | null | null |
lib/mappers/ingest/validate.ex
|
evandiewald/mappers
|
7359cfb39a4d9d26c42f5917ee04a7e41d3291bc
|
[
"Apache-2.0"
] | null | null | null |
defmodule Mappers.Ingest.Validate do
def validate_message(message) do
if match?(%{"decoded" => %{"payload" => %{"latitude" => _}}}, message) == false do
{:error, "Missing Field: latitude"}
else
if match?(%{"decoded" => %{"payload" => %{"longitude" => _}}}, message) == false do
{:error, "Missing Field: longitude"}
else
if match?(%{"decoded" => %{"payload" => %{"altitude" => _}}}, message) == false do
{:error, "Missing Field: altitude"}
else
if match?(%{"decoded" => %{"payload" => %{"accuracy" => _}}}, message) == false do
{:error, "Missing Field: accuracy"}
else
device_lat = message["decoded"]["payload"]["latitude"]
device_lng = message["decoded"]["payload"]["longitude"]
device_alt = message["decoded"]["payload"]["altitude"]
device_acu = message["decoded"]["payload"]["accuracy"]
if device_lat == 0.0 or device_lat < -90 or device_lat > 90 or device_lng == 0.0 or
device_lng < -180 or device_lng > 180 do
{:error,
"Invalid Device Latitude or Longitude Values for Lat: #{device_lat} Lng: #{device_lng}"}
else
if device_alt < -500 do
{:error, "Invalid Device Altitude Value for Alt: #{device_alt}"}
else
if device_acu < 0 do
{:error, "Invalid Device Accuracy Value for Accuracy: #{device_acu}"}
else
Enum.map(message["hotspots"], fn hotspot ->
hotspot_name = hotspot["name"]
hotspot_lat = hotspot["lat"]
hotspot_lng = hotspot["long"]
hotspot_rssi = hotspot["rssi"]
hotspot_snr = hotspot["snr"]
if hotspot_lat == 0.0 or hotspot_lat < -90 or
hotspot_lat > 90 or hotspot_lng == 0.0 or
hotspot_lng < -180 or hotspot_lng > 180 do
{:error,
"Invalid Latitude or Longitude Values for Hotspot: #{hotspot_name}"}
else
if Geocalc.distance_between([device_lat, device_lng], [
hotspot_lat,
hotspot_lng
]) >
500_000 do
{:error, "Invalid Distance Between Device and Hotspot: #{hotspot_name}"}
else
if hotspot_rssi < -141 or hotspot_rssi > 0 do
{:error, "Invalid Uplink RSSI for Hotspot: #{hotspot_name}"}
else
if hotspot_snr < -40 or hotspot_snr > 40 do
{:error, "Invalid Uplink SNR for Hotspot: #{hotspot_name}"}
else
{:ok, hotspot}
end
end
end
end
end)
|> Enum.split_with(fn
{:error, _} -> true
{:ok, _} -> false
end)
|> case do
# if there are any hotspot errors but no oks
{errors, []} ->
errors_s =
errors
|> Enum.map(&elem(&1, 1))
{:error, errors_s}
# if there are any hotspot oks
{_, hotspots} ->
hotspots_s =
hotspots
|> Enum.map(&elem(&1, 1))
{:ok, hotspots_s}
end
end
end
end
end
end
end
end
end
end
| 41.709677 | 103 | 0.427945 |
736b0f4836d87bade2c68089584e675a6162f0a8
| 291 |
ex
|
Elixir
|
mr_v0.ex
|
sharma7n/MrElixir
|
703899e9e90e47ca14695a772abc870a35b9539d
|
[
"MIT"
] | null | null | null |
mr_v0.ex
|
sharma7n/MrElixir
|
703899e9e90e47ca14695a772abc870a35b9539d
|
[
"MIT"
] | null | null | null |
mr_v0.ex
|
sharma7n/MrElixir
|
703899e9e90e47ca14695a772abc870a35b9539d
|
[
"MIT"
] | null | null | null |
# v0: No distributed processing.
defmodule MapReduce do
defp map(data), do: Enum.map(data, fn x -> x*2 end)
defp reduce(data), do: Enum.reduce(data, 0, fn x, acc -> x + acc end)
def run(data), do: data |> mapper |> reducer
end
result = MapReduce.run [1, 2, 3]
IO.inspect result
| 29.1 | 73 | 0.649485 |
736b2fe6588e642040b9a28c4371289f2f57aee8
| 642 |
exs
|
Elixir
|
apps/rig_api/test/rig_api/controllers/health_controller_test.exs
|
arana3/reactive-interaction-gateway
|
793648bcc5b8b05fc53df1f5f97818fb40ca84be
|
[
"Apache-2.0"
] | 518 |
2017-11-09T13:10:49.000Z
|
2022-03-28T14:29:50.000Z
|
apps/rig_api/test/rig_api/controllers/health_controller_test.exs
|
arana3/reactive-interaction-gateway
|
793648bcc5b8b05fc53df1f5f97818fb40ca84be
|
[
"Apache-2.0"
] | 270 |
2017-11-10T00:11:34.000Z
|
2022-02-27T13:08:16.000Z
|
apps/rig_api/test/rig_api/controllers/health_controller_test.exs
|
arana3/reactive-interaction-gateway
|
793648bcc5b8b05fc53df1f5f97818fb40ca84be
|
[
"Apache-2.0"
] | 67 |
2017-12-19T20:16:37.000Z
|
2022-03-31T10:43:04.000Z
|
defmodule RigApi.HealthControllerTest do
@moduledoc false
require Logger
use ExUnit.Case, async: true
use RigApi.ConnCase
describe "GET /health" do
test "should return OK as text response" do
conn = build_conn() |> get("/health")
assert conn.resp_body == "OK"
assert "text/plain" == resp_content_type(conn)
end
end
# The response content-type with parameters stripped (e.g. "text/plain").
defp resp_content_type(conn) do
[{:ok, type, subtype, _params}] =
conn
|> get_resp_header("content-type")
|> Enum.map(&Plug.Conn.Utils.content_type/1)
"#{type}/#{subtype}"
end
end
| 25.68 | 75 | 0.660436 |
736b339254d2046c3b093b58efa777121aba4dd7
| 392 |
ex
|
Elixir
|
lib/source_academy_admin/views/error_view.ex
|
trewdys/source-academy2-debug
|
6146e1fac81472184877f47aa32dee7fdceb4fb6
|
[
"Unlicense"
] | null | null | null |
lib/source_academy_admin/views/error_view.ex
|
trewdys/source-academy2-debug
|
6146e1fac81472184877f47aa32dee7fdceb4fb6
|
[
"Unlicense"
] | null | null | null |
lib/source_academy_admin/views/error_view.ex
|
trewdys/source-academy2-debug
|
6146e1fac81472184877f47aa32dee7fdceb4fb6
|
[
"Unlicense"
] | null | null | null |
defmodule SourceAcademyAdmin.ErrorView do
use SourceAcademyAdmin, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 21.777778 | 47 | 0.714286 |
736b3787bec8a601b7ebf230d8b23b8be0532bb4
| 855 |
ex
|
Elixir
|
lib/ark_elixir_example.ex
|
Highjhacker/Ark-Elixir-Example
|
7daec76e839cb291ebc191b840845f17342be617
|
[
"MIT"
] | 1 |
2018-04-22T05:15:59.000Z
|
2018-04-22T05:15:59.000Z
|
lib/ark_elixir_example.ex
|
Highjhacker/Ark-Elixir-Example
|
7daec76e839cb291ebc191b840845f17342be617
|
[
"MIT"
] | null | null | null |
lib/ark_elixir_example.ex
|
Highjhacker/Ark-Elixir-Example
|
7daec76e839cb291ebc191b840845f17342be617
|
[
"MIT"
] | null | null | null |
defmodule ArkElixirExample do
def main(argv) do
argv
|> parse_args
end
def parse_args(args) do
parsed_args = OptionParser.parse(args, switches: [help: :boolean, address: :string, search: :string],
aliases: [h: :help, a: :address, s: :search])
case parsed_args do
{[help: true], _, _} -> help()
{[address: address], _, _} -> IO.inspect Ark_Elixir.Account.get_balance(address)
{[search: query], _, _} -> IO.inspect Ark_Elixir.Delegate.search_delegates([q: query])
_ -> :help
end
end
def help do
IO.puts "Help of ArkElixirExample !\n-h --help for help\n-a --address validArkAddress for watching the balance of an account\n-s --search 'delegate' for searching a delegate."
end
end
| 35.625 | 183 | 0.575439 |
736b48637fb686f8af12f8b2334b485b8ba05b3e
| 1,026 |
ex
|
Elixir
|
community/samples/serving/helloworld-elixir/lib/hello/application.ex
|
brunoborges/docs
|
a4d3e3af4e3b6510f9812082e9f92e5853067eea
|
[
"Apache-2.0"
] | 3,383 |
2018-07-23T21:00:17.000Z
|
2022-03-30T17:13:52.000Z
|
community/samples/serving/helloworld-elixir/lib/hello/application.ex
|
brunoborges/docs
|
a4d3e3af4e3b6510f9812082e9f92e5853067eea
|
[
"Apache-2.0"
] | 4,617 |
2018-07-23T21:55:06.000Z
|
2022-03-31T21:52:36.000Z
|
community/samples/serving/helloworld-elixir/lib/hello/application.ex
|
brunoborges/docs
|
a4d3e3af4e3b6510f9812082e9f92e5853067eea
|
[
"Apache-2.0"
] | 1,240 |
2018-07-23T20:36:04.000Z
|
2022-03-30T20:03:07.000Z
|
defmodule Hello.Application do
use Application
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
def start(_type, _args) do
IO.puts :stderr, "Application starting up"
import Supervisor.Spec
# Define workers and child supervisors to be supervised
children = [
# Start the endpoint when the application starts
supervisor(HelloWeb.Endpoint, []),
# Start your own worker by calling: Hello.Worker.start_link(arg1, arg2, arg3)
# worker(Hello.Worker, [arg1, arg2, arg3]),
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Hello.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
IO.puts :stderr, "Config changed"
HelloWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 32.0625 | 83 | 0.714425 |
736b7bb986d5f7cbfe51f90ac20ff6da370d949f
| 2,799 |
exs
|
Elixir
|
apps/blunt_absinthe_relay/test/blunt/absinthe/relay/connection_test.exs
|
blunt-elixir/blunt
|
a88b88984022db7ba2110204248fdb541121e3a0
|
[
"MIT"
] | 1 |
2022-03-07T11:54:47.000Z
|
2022-03-07T11:54:47.000Z
|
apps/blunt_absinthe_relay/test/blunt/absinthe/relay/connection_test.exs
|
elixir-cqrs/cqrs_tools
|
afbf82da522a10d2413547a46f316ed3aadebba5
|
[
"MIT"
] | null | null | null |
apps/blunt_absinthe_relay/test/blunt/absinthe/relay/connection_test.exs
|
elixir-cqrs/cqrs_tools
|
afbf82da522a10d2413547a46f316ed3aadebba5
|
[
"MIT"
] | null | null | null |
defmodule Blunt.Absinthe.Relay.ConnectionTest do
use ExUnit.Case, async: false
alias Blunt.DispatchContext
alias Blunt.Absinthe.Relay.Test.{CreatePeople, Schema}
setup_all do
peeps = [
%{id: UUID.uuid4(), name: "chris"},
%{id: UUID.uuid4(), name: "chris", gender: :male},
%{id: UUID.uuid4(), name: "chris", gender: :male},
%{id: UUID.uuid4(), name: "sarah", gender: :female},
%{id: UUID.uuid4(), name: "sarah", gender: :female},
%{id: UUID.uuid4(), name: "luke", gender: :not_sure},
%{id: UUID.uuid4(), name: "michael", gender: :not_sure}
]
assert {:ok, _people} =
%{peeps: peeps}
|> CreatePeople.new()
|> CreatePeople.dispatch()
%{
query: """
query list($name: String, $gender: Gender, $after: String){
listPeople(first: 2, after: $after, name: $name, gender: $gender){
pageInfo {
hasNextPage
}
edges {
node {
id
name
gender
}
}
}
}
"""
}
end
@doc """
The Ecto Etso adapter does not support windowing functions or counting via repo.aggregate.
This stops me from testing totalCount on the connection and fetching next pages.
This is livable, but I should really just configure postgres. I just don't want to now.
"""
test "totalCount is present on the connection" do
# Etso won't do the count aggregate function. Maybe I'll switch to postgres. This is a downer.
assert %{fields: %{total_count: _}} = Absinthe.Schema.lookup_type(Schema, "PersonConnection")
end
test "searching for chris should return two pages", %{query: query} do
assert {:ok, %{data: %{"listPeople" => %{"pageInfo" => page_info, "edges" => edges}}}} =
Absinthe.run(query, Schema, variables: %{"name" => "chris"})
assert length(edges) == 2
assert %{"hasNextPage" => true} = page_info
end
test "searching for gender NOT_SURE should return two pages", %{query: query} do
assert {:ok, %{data: %{"listPeople" => %{"pageInfo" => page_info, "edges" => edges}}}} =
Absinthe.run(query, Schema, variables: %{"gender" => "NOT_SURE"})
assert length(edges) == 2
assert %{"hasNextPage" => true} = page_info
assert edges
|> Enum.map(&get_in(&1, ["node", "name"]))
|> Enum.all?(fn name -> name in ["chris", "luke", "michael"] end)
end
test "user is put in the context from absinthe resolution context", %{query: query} do
context = %{user: %{name: "chris"}, reply_to: self()}
_ = Absinthe.run(query, Schema, context: context, variables: %{"gender" => "NOT_SURE"})
assert_receive {:context, %DispatchContext{user: %{name: "chris"}}}
end
end
| 33.321429 | 98 | 0.58771 |
736b7e802bd47f7f56f65ce9dbdf5cade4808b50
| 1,393 |
exs
|
Elixir
|
mix.exs
|
salemove/elixir-http_client
|
c3419d63363eb38e744c3c136353ff8260cdd123
|
[
"MIT"
] | null | null | null |
mix.exs
|
salemove/elixir-http_client
|
c3419d63363eb38e744c3c136353ff8260cdd123
|
[
"MIT"
] | 9 |
2018-01-15T15:32:06.000Z
|
2021-10-07T09:06:20.000Z
|
mix.exs
|
salemove/elixir-http_client
|
c3419d63363eb38e744c3c136353ff8260cdd123
|
[
"MIT"
] | null | null | null |
defmodule Salemove.HttpClient.Mixfile do
use Mix.Project
def project do
[
app: :salemove_http_client,
version: "2.1.0-rc.2",
elixir: "~> 1.9",
start_permanent: Mix.env() == :prod,
build_embedded: Mix.env() == :prod,
deps: deps(),
package: package(),
description: description(),
docs: [
main: "Salemove.HttpClient"
],
dialyzer: [
plt_add_apps: [:ex_unit],
flags: [:error_handling, :race_conditions, :underspecs]
]
]
end
def description do
~S"""
Elixir HTTP client for JSON services
"""
end
def package do
[
maintainers: ["SaleMove TechMovers"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/salemove/elixir-http_client"}
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:tesla, "~> 1.4"},
{:tesla_statsd, "~> 0.3.0"},
{:confex, "~> 3.0"},
{:telemetry, "~> 0.4 or ~> 1.0"},
{:opentelemetry_tesla, "~> 1.3.2-rc.4", optional: true},
{:ex_statsd, ">= 0.0.0", only: [:dev, :test]},
{:ex_doc, ">= 0.0.0", only: :dev},
{:dialyxir, "~> 0.5", only: :dev, runtime: false},
{:jason, "~> 1.1"}
]
end
end
| 23.216667 | 76 | 0.539842 |
736b887a20aa9aa72b8f1d28b8a8a13dfdf1b201
| 730 |
ex
|
Elixir
|
test/support/mock_verne.ex
|
rbino/astarte_vmq_plugin
|
e5cfcb717d8ac2b2bcfc3430a48b4c4c7b767140
|
[
"Apache-2.0"
] | null | null | null |
test/support/mock_verne.ex
|
rbino/astarte_vmq_plugin
|
e5cfcb717d8ac2b2bcfc3430a48b4c4c7b767140
|
[
"Apache-2.0"
] | null | null | null |
test/support/mock_verne.ex
|
rbino/astarte_vmq_plugin
|
e5cfcb717d8ac2b2bcfc3430a48b4c4c7b767140
|
[
"Apache-2.0"
] | null | null | null |
defmodule Astarte.VMQ.Plugin.MockVerne do
def start_link do
Agent.start_link(fn -> :queue.new() end, name: __MODULE__)
end
# Return mock functions for tests instead of the
# ones returned from :vmq_reg.direct_plugin_exports
def get_functions do
empty_fun = fn -> :ok end
publish_fun = fn topic, payload, opts ->
Agent.update(__MODULE__, &:queue.in({topic, payload, opts}, &1))
end
{empty_fun, publish_fun, {empty_fun, empty_fun}}
end
def consume_message do
Agent.get_and_update(__MODULE__, fn queue ->
case :queue.out(queue) do
{{:value, item}, new_queue} ->
{item, new_queue}
{:empty, ^queue} ->
{nil, queue}
end
end)
end
end
| 24.333333 | 70 | 0.639726 |
736b90e1cd90c8935bb42928e6652b7b55936c22
| 1,352 |
ex
|
Elixir
|
lib/requestbox_web/controllers/session_controller.ex
|
kevinastone/phoenixbin
|
8b7326b5de1fe9961c1a2d7971a3d4abe7178829
|
[
"MIT"
] | 18 |
2015-11-18T09:52:34.000Z
|
2021-04-27T19:38:08.000Z
|
lib/requestbox_web/controllers/session_controller.ex
|
kevinastone/phoenixbin
|
8b7326b5de1fe9961c1a2d7971a3d4abe7178829
|
[
"MIT"
] | 3 |
2017-01-11T18:55:39.000Z
|
2021-06-15T05:46:34.000Z
|
lib/requestbox_web/controllers/session_controller.ex
|
kevinastone/phoenixbin
|
8b7326b5de1fe9961c1a2d7971a3d4abe7178829
|
[
"MIT"
] | 7 |
2016-08-17T10:24:20.000Z
|
2020-07-10T13:00:36.000Z
|
defmodule RequestboxWeb.SessionController do
use Requestbox.Web, :controller
alias Requestbox.Request
alias Requestbox.Session
plug(:scrub_params, "session" when action in [:create, :update])
def index(conn, _params) do
changeset = Session.changeset(%Session{})
render(conn, :index, changeset: changeset)
end
def create(conn, %{"session" => session_params}) do
changeset = Session.changeset(%Session{}, session_params)
case Repo.insert(changeset) do
{:ok, session} ->
conn
|> redirect(to: Routes.session_path(conn, :show, session))
{:error, _changeset} ->
conn
|> put_flash(:error, "Failed to create a session.")
|> redirect(to: Routes.session_path(conn, :index))
end
end
def show(conn, %{"id" => id}) do
conn = conn |> fetch_query_params
session = Session.find_session(id)
render_session(conn, session)
end
defp render_session(conn, %Session{} = session) do
{requests, pagination} =
Request.sorted()
|> where([r], r.session_id == ^session.id)
|> Repo.paginate(conn.query_params)
render(conn, "show.html", session: session, requests: requests, pagination: pagination)
end
defp render_session(conn, nil) do
conn
|> put_status(:not_found)
|> render(RequestboxWeb.ErrorView, "404.html")
end
end
| 27.04 | 91 | 0.659763 |
736b976bb6241b6206b35e0b653f0bb3b27c868f
| 983 |
exs
|
Elixir
|
apps/extract_http/mix.exs
|
jdenen/hindsight
|
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
|
[
"Apache-2.0"
] | 12 |
2020-01-27T19:43:02.000Z
|
2021-07-28T19:46:29.000Z
|
apps/extract_http/mix.exs
|
jdenen/hindsight
|
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
|
[
"Apache-2.0"
] | 81 |
2020-01-28T18:07:23.000Z
|
2021-11-22T02:12:13.000Z
|
apps/extract_http/mix.exs
|
jdenen/hindsight
|
ef69b4c1a74c94729dd838a9a0849a48c9b6e04c
|
[
"Apache-2.0"
] | 10 |
2020-02-13T21:24:09.000Z
|
2020-05-21T18:39:35.000Z
|
defmodule ExtractHttp.MixProject do
use Mix.Project
def project do
[
app: :extract_http,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.9",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
def application do
[
extra_applications: [:logger]
]
end
defp deps do
[
{:protocol_extract_step, in_umbrella: true},
{:definition, in_umbrella: true},
{:mint, "~> 1.0", override: true},
{:tesla, "~> 1.3"},
{:castore, "~> 0.1.4"},
{:temp, "~> 0.4.7"},
{:json_serde, "~> 1.0"},
{:bypass, "~> 1.0", only: [:test]},
{:checkov, "~> 1.0", only: [:dev, :test]},
{:credo, "~> 1.3", only: [:dev]},
{:dialyxir, "~> 1.0.0-rc.7", only: [:dev], runtime: false},
{:placebo, "~> 2.0.0-rc.2", only: [:dev, :test]}
]
end
end
| 23.97561 | 65 | 0.485249 |
736b9a1f1568d8765d3af9079d1eb1b9e97e356a
| 1,141 |
exs
|
Elixir
|
mix.exs
|
baldmountain/avia
|
c60a748e8124bc602d485cd017f9f4f0953db54c
|
[
"MIT"
] | null | null | null |
mix.exs
|
baldmountain/avia
|
c60a748e8124bc602d485cd017f9f4f0953db54c
|
[
"MIT"
] | null | null | null |
mix.exs
|
baldmountain/avia
|
c60a748e8124bc602d485cd017f9f4f0953db54c
|
[
"MIT"
] | null | null | null |
defmodule Snitch.Mixfile do
use Mix.Project
def project do
[
apps_path: "apps",
elixir: "~> 1.12.2",
start_permanent: Mix.env() == :prod,
deps: deps(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [coveralls: :test, "coveralls.json": :test, "coveralls.html": :test],
docs: docs()
]
end
# Dependencies listed here are available only for this
# project and cannot be accessed from applications inside
# the apps folder.
#
# Run "mix help deps" for examples and options.
defp deps do
[
{:jason, "~> 1.2"},
{:ex_doc, "~> 0.25", only: :dev, runtime: false},
{:excoveralls, "~> 0.14", only: :test},
{:inch_ex, "~> 2.0", only: [:docs, :dev]},
{:distillery, "~> 2.1", runtime: false}
]
end
defp docs do
[
extras: ~w(README.md),
main: "readme",
source_url: "https://github.com/aviabird/snitch",
groups_for_modules: groups_for_modules()
]
end
defp groups_for_modules do
[
Snitch: ~r/^Snitch.?/,
SnitchApi: ~r/^SnitchApi.?/,
SnitchAdmin: ~r/^AdminApp.?/
]
end
end
| 23.770833 | 94 | 0.575811 |
736bd0675c6cfa6a88606013972870dac585d345
| 24,627 |
ex
|
Elixir
|
lib/mix/lib/mix.ex
|
ericklima-ca/elixir
|
9512bcce90a85fe3cc6d503e92a2b522d6b9825e
|
[
"Apache-2.0"
] | 2 |
2020-08-11T16:19:53.000Z
|
2020-08-11T18:07:11.000Z
|
lib/mix/lib/mix.ex
|
ericklima-ca/elixir
|
9512bcce90a85fe3cc6d503e92a2b522d6b9825e
|
[
"Apache-2.0"
] | null | null | null |
lib/mix/lib/mix.ex
|
ericklima-ca/elixir
|
9512bcce90a85fe3cc6d503e92a2b522d6b9825e
|
[
"Apache-2.0"
] | null | null | null |
defmodule Mix do
@moduledoc ~S"""
Mix is a build tool that provides tasks for creating, compiling,
and testing Elixir projects, managing its dependencies, and more.
## Mix.Project
The foundation of Mix is a project. A project can be defined by using
`Mix.Project` in a module, usually placed in a file named `mix.exs`:
defmodule MyApp.MixProject do
use Mix.Project
def project do
[
app: :my_app,
version: "1.0.0"
]
end
end
See the `Mix.Project` module for detailed documentation on Mix projects.
Once the project is defined, a number of default Mix tasks can be run
directly from the command line:
* `mix compile` - compiles the current project
* `mix test` - runs tests for the given project
* `mix run` - runs a particular command inside the project
Each task has its own options and sometimes specific configuration
to be defined in the `project/0` function. You can use `mix help`
to list all available tasks and `mix help NAME` to show help for
a particular task.
The best way to get started with your first project is by calling
`mix new my_project` from the command line.
## Mix.Task
Tasks are what make Mix extensible.
Projects can extend Mix behaviour by adding their own tasks. For
example, adding the task below inside your project will
make it available to everyone that uses your project:
defmodule Mix.Tasks.Hello do
use Mix.Task
def run(_) do
Mix.shell().info("Hello world")
end
end
The task can now be invoked with `mix hello`.
See the `Mix.Task` behaviour for detailed documentation on Mix tasks.
## Dependencies
Mix also manages your dependencies and integrates nicely with the [Hex package
manager](https://hex.pm).
In order to use dependencies, you need to add a `:deps` key
to your project configuration. We often extract the list of dependencies
into its own function:
defmodule MyApp.MixProject do
use Mix.Project
def project do
[
app: :my_app,
version: "1.0.0",
deps: deps()
]
end
defp deps do
[
{:ecto, "~> 2.0"},
{:plug, github: "elixir-lang/plug"}
]
end
end
You can run `mix help deps` to learn more about dependencies in Mix.
## Environments
Mix supports different environments. Environments allow developers
to prepare and organize their project specifically for different
scenarios. By default, Mix provides three environments:
* `:dev` - the default environment
* `:test` - the environment `mix test` runs on
* `:prod` - the environment your dependencies run on
The environment can be changed via the command line by setting
the `MIX_ENV` environment variable, for example:
```bash
$ MIX_ENV=prod mix run server.exs
```
You can also specify that certain dependencies are available only for
certain environments:
{:some_test_dependency, "~> 1.0", only: :test}
The environment can be read via `Mix.env/0`.
## Targets
Besides environments, Mix supports targets. Targets are useful when a
project needs to compile to different architectures and some of the
dependencies are only available to some of them. By default, the target
is `:host` but it can be set via the `MIX_TARGET` environment variable.
The target can be read via `Mix.target/0`.
## Configuration
Mix allows you configure the application environment of your application
and of your dependencies. See the `Application` module to learn more about
the application environment. On this section, we will focus on how to configure
it at two distinct moments: build-time and runtime.
> Note: The application environment is discouraged for libraries. See Elixir's
> [Library Guidelines](https://hexdocs.pm/elixir/library-guidelines.html) for
> more information.
### Build-time configuration
Whenever you invoke a `mix` command, Mix loads the configuration
in `config/config.exs`, if said file exists. It is common for the
`config/config.exs` file itself to import other configuration based
on the current `MIX_ENV`, such as `config/dev.exs`, `config/test.exs`,
and `config/prod.exs`, by calling `Config.import_config/1`:
import Config
import_config "#{config_env()}.exs"
We say `config/config.exs` and all imported files are build-time
configuration as they are evaluated whenever you compile your code.
In other words, if your configuration does something like:
import Config
config :my_app, :secret_key, System.fetch_env!("MY_APP_SECRET_KEY")
The `:secret_key` key under `:my_app` will be computed on the host
machine before your code compiles. This can be an issue if the machine
compiling your code does not have access to all environment variables
used to run your code, as loading the config above will fail due to the
missing environment variable. Luckily, Mix also provides runtime
configuration, which should be preferred and we will see next.
### Runtime configuration
To enable runtime configuration in your release, all you need to do is
to create a file named `config/runtime.exs`:
import Config
config :my_app, :secret_key, System.fetch_env!("MY_APP_SECRET_KEY")
This file will be executed whenever your Mix project. If you assemble
a release with `mix release`, it is also booted every time your release
starts.
## Aliases
Aliases are shortcuts or tasks specific to the current project.
In the [Mix.Task section](#module-mix-task), we have defined a task that would be
available to everyone using our project as a dependency. What if
we wanted the task to only be available for our project? Just
define an alias:
defmodule MyApp.MixProject do
use Mix.Project
def project do
[
app: :my_app,
version: "1.0.0",
aliases: aliases()
]
end
defp aliases do
[
c: "compile",
hello: &hello/1
]
end
defp hello(_) do
Mix.shell().info("Hello world")
end
end
In the example above, we have defined two aliases. One is `mix c`
which is a shortcut for `mix compile`. The other is named
`mix hello`, which is the equivalent to the `Mix.Tasks.Hello`
we have defined in the [Mix.Task section](#module-mix-task).
Aliases may also be lists, specifying multiple tasks to be run
consecutively:
[all: [&hello/1, "deps.get --only #{Mix.env()}", "compile"]]
In the example above, we have defined an alias named `mix all`,
that prints "Hello world", then fetches dependencies specific
to the current environment, and compiles the project.
Aliases can also be used to augment existing tasks. Let's suppose
you want to augment `mix clean` to clean another directory Mix does
not know about:
[clean: ["clean", &clean_extra/1]]
Where `&clean_extra/1` would be a function in your `mix.exs`
with extra cleanup logic.
Arguments given to the alias will be appended to the arguments of
the last task in the list. Except when overriding an existing task.
In this case, the arguments will be given to the original task,
in order to preserve semantics. For example, in the `:clean` alias
above, the arguments given to the alias will be passed to "clean"
and not to `clean_extra/1`.
Aliases defined in the current project do not affect its dependencies
and aliases defined in dependencies are not accessible from the
current project.
Aliases can be used very powerfully to also run Elixir scripts and
shell commands, for example:
# priv/hello1.exs
IO.puts("Hello One")
# priv/hello2.exs
IO.puts("Hello Two")
# priv/world.sh
#!/bin/sh
echo "world!"
# mix.exs
defp aliases do
[
some_alias: ["hex.info", "run priv/hello1.exs", "cmd priv/world.sh"]
]
end
In the example above we have created the alias `some_alias` that will
run the task `mix hex.info`, then `mix run` to run an Elixir script,
then `mix cmd` to execute a command line shell script. This shows how
powerful aliases mixed with Mix tasks can be.
Mix tasks are designed to run only once. This prevents the same task
from being executed multiple times. For example, if there are several tasks
depending on `mix compile`, the code will be compiled once. Tasks can
be executed again if they are explicitly reenabled using `Mix.Task.reenable/1`:
another_alias: [
"format --check-formatted priv/hello1.exs",
"cmd priv/world.sh",
fn _ -> Mix.Task.reenable("format") end,
"format --check-formatted priv/hello2.exs"
]
Some tasks are automatically reenabled though, as they are expected to
be invoked multiple times. They are: `mix cmd`, `mix do`, `mix loadconfig`,
`mix profile.cprof`, `mix profile.eprof`, `mix profile.fprof`, `mix run`,
and `mix xref`.
It is worth mentioning that some tasks, such as in the case of the
`mix format` command in the example above, can accept multiple files so it
could be rewritten as:
another_alias: ["format --check-formatted priv/hello1.exs priv/hello2.exs"]
## Environment variables
Several environment variables can be used to modify Mix's behaviour.
Mix responds to the following variables:
* `MIX_ARCHIVES` - specifies the directory into which the archives should be installed
(default: `~/.mix/archives`)
* `MIX_BUILD_ROOT` - sets the root directory where build artifacts
should be written to. For example, "_build". If `MIX_BUILD_PATH` is set, this
option is ignored.
* `MIX_BUILD_PATH` - sets the project `Mix.Project.build_path/0` config. This option
must always point to a subdirectory inside a temporary directory. For instance,
never "/tmp" or "_build" but "_build/PROD" or "/tmp/PROD", as required by Mix
* `MIX_DEPS_PATH` - sets the project `Mix.Project.deps_path/0` config for the current project (default: `deps`)
* `MIX_DEBUG` - outputs debug information about each task before running it
* `MIX_ENV` - specifies which environment should be used. See [Environments](#module-environments)
* `MIX_TARGET` - specifies which target should be used. See [Targets](#module-targets)
* `MIX_EXS` - changes the full path to the `mix.exs` file
* `MIX_HOME` - path to Mix's home directory, stores configuration files and scripts used by Mix
(default: `~/.mix`)
* `MIX_INSTALL_DIR` - (since v1.12.0) specifies directory where `Mix.install/2` keeps
install cache
* `MIX_INSTALL_FORCE` - (since v1.13.0) runs `Mix.install/2` with empty install cache
* `MIX_PATH` - appends extra code paths
* `MIX_QUIET` - does not print information messages to the terminal
* `MIX_REBAR` - path to rebar command that overrides the one Mix installs
(default: `~/.mix/rebar`)
* `MIX_REBAR3` - path to rebar3 command that overrides the one Mix installs
(default: `~/.mix/rebar3`)
* `MIX_XDG` - asks Mix to follow the [XDG Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)
for its home directory and configuration files. This behaviour needs to
be opt-in due to backwards compatibility. `MIX_HOME` has higher preference
than `MIX_XDG`. If none of the variables are set, the default directory
`~/.mix` will be used
Environment variables that are not meant to hold a value (and act basically as
flags) should be set to either `1` or `true`, for example:
$ MIX_DEBUG=1 mix compile
"""
@mix_install_project __MODULE__.InstallProject
use Application
import Kernel, except: [raise: 2]
@doc false
def start do
{:ok, _} = Application.ensure_all_started(:mix)
:ok
end
@doc false
def start(_type, []) do
children = [Mix.State, Mix.TasksServer, Mix.ProjectStack]
opts = [strategy: :one_for_one, name: Mix.Supervisor, max_restarts: 0]
Supervisor.start_link(children, opts)
end
@doc """
Returns the current Mix environment.
This function should not be used at runtime in application code (as opposed
to infrastructure and build code like Mix tasks). Mix is a build tool and may
not be available after the code is compiled (for example in a release).
To differentiate the program behavior depending on the environment, it is
recommended to use application environment through `Application.get_env/3`.
Proper configuration can be set in config files, often per-environment
(see the `Config` module for more information).
"""
@spec env() :: atom()
def env do
# env is not available on bootstrapping, so set a :dev default
Mix.State.get(:env, :dev)
end
@doc """
Changes the current Mix environment to `env`.
Be careful when invoking this function as any project
configuration won't be reloaded.
This function should not be used at runtime in application code
(see `env/0` for more information).
"""
@spec env(atom()) :: :ok
def env(env) when is_atom(env) do
Mix.State.put(:env, env)
end
@doc """
Returns the Mix target.
"""
@spec target() :: atom()
def target do
# target is not available on bootstrapping, so set a :host default
Mix.State.get(:target, :host)
end
@doc """
Changes the current Mix target to `target`.
Be careful when invoking this function as any project
configuration won't be reloaded.
"""
@spec target(atom()) :: :ok
def target(target) when is_atom(target) do
Mix.State.put(:target, target)
end
@doc """
Returns the default compilers used by Mix.
It can be used in your `mix.exs` to prepend or
append new compilers to Mix:
def project do
[compilers: Mix.compilers() ++ [:foo, :bar]]
end
"""
@spec compilers() :: [atom()]
def compilers do
[:yecc, :leex, :erlang, :elixir, :app]
end
@doc """
Returns the current shell.
`shell/0` can be used as a wrapper for the current shell. It contains
conveniences for requesting information from the user, printing to the
shell and so forth. The Mix shell is swappable (see `shell/1`), allowing
developers to use a test shell that simply sends messages to the current
process instead of performing IO (see `Mix.Shell.Process`).
By default, this returns `Mix.Shell.IO`.
## Examples
Mix.shell().info("Preparing to do something dangerous...")
if Mix.shell().yes?("Are you sure?") do
# do something dangerous
end
"""
@spec shell() :: module
def shell do
Mix.State.get(:shell, Mix.Shell.IO)
end
@doc """
Sets the current shell.
As an argument you may pass `Mix.Shell.IO`, `Mix.Shell.Process`,
`Mix.Shell.Quiet`, or any module that implements the `Mix.Shell`
behaviour.
After calling this function, `shell` becomes the shell that is
returned by `shell/0`.
## Examples
iex> Mix.shell(Mix.Shell.IO)
:ok
You can use `shell/0` and `shell/1` to temporarily switch shells,
for example, if you want to run a Mix Task that normally produces
a lot of output:
shell = Mix.shell()
Mix.shell(Mix.Shell.Quiet)
try do
Mix.Task.run("noisy.task")
after
Mix.shell(shell)
end
"""
@spec shell(module) :: :ok
def shell(shell) do
Mix.State.put(:shell, shell)
end
@doc """
Returns `true` if Mix is in debug mode, `false` otherwise.
"""
@spec debug?() :: boolean()
def debug? do
Mix.State.get(:debug, false)
end
@doc """
Sets Mix debug mode.
"""
@spec debug(boolean()) :: :ok
def debug(debug) when is_boolean(debug) do
Mix.State.put(:debug, debug)
end
@doc """
Raises a Mix error that is nicely formatted, defaulting to exit status `1`.
"""
@spec raise(binary) :: no_return
def raise(message) do
__MODULE__.raise(message, exit_status: 1)
end
@doc """
Raises a Mix error that is nicely formatted.
## Options
* `:exit_status` - defines exit status, defaults to `1`
"""
@doc since: "1.12.3"
@spec raise(binary, exit_status: non_neg_integer()) :: no_return
def raise(message, opts) when is_binary(message) and is_list(opts) do
status =
opts[:exit_status] ||
if exit_code = opts[:exit_code] do
IO.warn(":exit_code is deprecated, use :exit_status instead")
exit_code
else
1
end
Kernel.raise(Mix.Error, mix: status, message: message)
end
@doc """
The path for local archives or escripts.
"""
@doc since: "1.10.0"
@spec path_for(:archives | :escripts) :: String.t()
def path_for(:archives) do
System.get_env("MIX_ARCHIVES") || Path.join(Mix.Utils.mix_home(), "archives")
end
def path_for(:escripts) do
Path.join(Mix.Utils.mix_home(), "escripts")
end
@doc """
Installs and starts dependencies.
The given `deps` should be in the same format as defined in a regular Mix
project. See `mix help deps` for more information. As a shortcut, an atom
can be given as dependency to mean the latest version. In other words,
specifying `:decimal` is the same as `{:decimal, ">= 0.0.0"}`.
After each successful installation, a given set of dependencies is cached
so starting another VM and calling `Mix.install/2` with the same dependencies
will avoid unnecessary downloads and compilations. The location of the cache
directory can be controlled using the `MIX_INSTALL_DIR` environment variable.
This function can only be called outside of a Mix project and only with the
same dependencies in the given VM.
**Note:** this feature is currently experimental and it may change
in future releases.
## Options
* `:force` - if `true`, runs with empty install cache. This is useful when you want
to update your dependencies or your install got into an inconsistent state.
To use this option, you can also set the `MIX_INSTALL_FORCE` environment variable.
(Default: `false`)
* `:verbose` - if `true`, prints additional debugging information
(Default: `false`)
* `:consolidate_protocols` - if `true`, runs protocol
consolidation via the `mix compile.protocols` task (Default: `true`)
* `:elixir` - if set, ensures the current Elixir version matches the given
version requirement (Default: `nil`)
* `:config` (since v1.13.0) - a keyword list of keyword lists with application
configuration to be set before the apps loaded. The configuration is part of
the `Mix.install/2` cache, so different configurations will lead to different
apps
* `:system_env` (since v1.13.0) - a list or a map of system environment variable
names as binary keys and their respective values as binaries. The system environment
is made part of the `Mix.install/2` cache, so different configurations will lead
to different apps
## Examples
To install `:decimal` and `:jason`:
Mix.install([
:decimal,
{:jason, "~> 1.0"}
])
Using `:nx`, `:exla`, and configure the underlying applications
and environment variables:
Mix.install(
[:nx, :exla],
config: [
nx: [default_backend: EXLA]
],
system_env: [
{"XLA_TARGET", "cuda111"}
]
)
## Limitations
There is one limitation to `Mix.install/2`, which is actually an Elixir
behaviour. If you are installing a dependency that defines a struct or
macro, you cannot use the struct or macro immediately after the install
call. For example, this won't work:
Mix.install([:decimal])
%Decimal{} = Decimal.new(42)
That's because Elixir first expands all structs and all macros, and then
it executes the code. This means that, by the time Elixir tries to expand
the `%Decimal{}` struct, the dependency has not been installed yet.
Luckily this has a straightforward solution, which is move the code to
inside a module:
Mix.install([:decimal])
defmodule Script do
def run do
%Decimal{} = Decimal.new(42)
end
end
Script.run()
The contents inside `defmodule` will only be expanded and executed
after `Mix.install/2` runs, which means that any struct, macros,
and imports will be correctly handled.
"""
@doc since: "1.12.0"
def install(deps, opts \\ [])
def install(deps, opts) when is_list(deps) and is_list(opts) do
Mix.start()
if Mix.Project.get() do
Mix.raise("Mix.install/2 cannot be used inside a Mix project")
end
elixir_requirement = opts[:elixir]
elixir_version = System.version()
if !!elixir_requirement and not Version.match?(elixir_version, elixir_requirement) do
Mix.raise(
"Mix.install/2 declared it supports only Elixir #{elixir_requirement} " <>
"but you're running on Elixir #{elixir_version}"
)
end
deps =
Enum.map(deps, fn
dep when is_atom(dep) ->
{dep, ">= 0.0.0"}
{app, opts} when is_atom(app) and is_list(opts) ->
{app, maybe_expand_path_dep(opts)}
{app, requirement, opts} when is_atom(app) and is_binary(requirement) and is_list(opts) ->
{app, requirement, maybe_expand_path_dep(opts)}
other ->
other
end)
config = Keyword.get(opts, :config, [])
system_env = Keyword.get(opts, :system_env, [])
id =
{deps, config, system_env}
|> :erlang.term_to_binary()
|> :erlang.md5()
|> Base.encode16(case: :lower)
force? = System.get_env("MIX_INSTALL_FORCE") in ["1", "true"] or !!opts[:force]
case Mix.State.get(:installed) do
nil ->
:ok
^id when not force? ->
:ok
_ ->
Mix.raise("Mix.install/2 can only be called with the same dependencies in the given VM")
end
Application.put_all_env(config, persistent: true)
System.put_env(system_env)
installs_root =
System.get_env("MIX_INSTALL_DIR") || Path.join(Mix.Utils.mix_cache(), "installs")
version = "elixir-#{System.version()}-erts-#{:erlang.system_info(:version)}"
dir = Path.join([installs_root, version, id])
if opts[:verbose] do
Mix.shell().info("Mix.install/2 using #{dir}")
end
if force? do
File.rm_rf!(dir)
end
config = [
version: "0.1.0",
build_embedded: false,
build_per_environment: true,
build_path: "_build",
lockfile: "mix.lock",
deps_path: "deps",
deps: deps,
app: :mix_install,
erlc_paths: ["src"],
elixirc_paths: ["lib"],
compilers: [],
consolidate_protocols: Keyword.get(opts, :consolidate_protocols, true)
]
started_apps = Application.started_applications()
:ok = Mix.Local.append_archives()
:ok = Mix.ProjectStack.push(@mix_install_project, config, "nofile")
build_dir = Path.join(dir, "_build")
try do
run_deps? = not File.dir?(build_dir)
File.mkdir_p!(dir)
File.cd!(dir, fn ->
if run_deps? do
Mix.Task.rerun("deps.get")
end
Mix.Task.rerun("deps.loadpaths")
# Hex and SSL can use a good amount of memory after the registry fetching,
# so we stop any app started during deps resolution.
stop_apps(Application.started_applications() -- started_apps)
Mix.Task.rerun("compile")
end)
for app <- Mix.Project.deps_apps() do
Application.ensure_all_started(app)
end
Mix.State.put(:installed, id)
:ok
after
Mix.ProjectStack.pop()
end
end
defp stop_apps([]), do: :ok
defp stop_apps(apps) do
:logger.add_primary_filter(:silence_app_exit, {&silence_app_exit/2, []})
Enum.each(apps, fn {app, _, _} -> Application.stop(app) end)
:logger.remove_primary_filter(:silence_app_exit)
:ok
end
defp silence_app_exit(
%{
msg:
{:report,
%{
label: {:application_controller, :exit},
report: [application: _, exited: :stopped] ++ _
}}
},
_extra
) do
:stop
end
defp silence_app_exit(_message, _extra) do
:ignore
end
defp maybe_expand_path_dep(opts) do
if Keyword.has_key?(opts, :path) do
Keyword.update!(opts, :path, &Path.expand/1)
else
opts
end
end
@doc false
def install?, do: Mix.Project.get() == @mix_install_project
end
| 31.173418 | 148 | 0.669509 |
736be24a6dc55fa081eb622997f19868728a9a24
| 2,353 |
exs
|
Elixir
|
apps/local_ledger_db/priv/repo/migrations/20180514095907_rename_balance_to_wallet.exs
|
jimpeebles/ewallet
|
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
|
[
"Apache-2.0"
] | null | null | null |
apps/local_ledger_db/priv/repo/migrations/20180514095907_rename_balance_to_wallet.exs
|
jimpeebles/ewallet
|
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
|
[
"Apache-2.0"
] | null | null | null |
apps/local_ledger_db/priv/repo/migrations/20180514095907_rename_balance_to_wallet.exs
|
jimpeebles/ewallet
|
ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2018 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule LocalLedgerDB.Repo.Migrations.RenameBalanceToWallet do
use Ecto.Migration
def up do
tables = %{
cached_balance: %{balance_address: :wallet_address},
transaction: %{balance_address: :wallet_address}
}
rename table(:balance), to: table(:wallet)
Enum.each(tables, fn {table, columns} ->
Enum.each(columns, fn {old_name, new_name} ->
rename table(table), old_name, to: new_name
drop constraint(table, "#{Atom.to_string(table)}_#{Atom.to_string(old_name)}_fkey")
end)
end)
drop index(:balance, [:address])
create unique_index(:wallet, [:address])
Enum.each(tables, fn {table, columns} ->
Enum.each(columns, fn {_old_name, new_name} ->
alter table(table) do
modify new_name, references(:wallet, type: :string,
column: :address), null: false
end
end)
end)
end
def down do
tables = %{
cached_balance: %{balance_address: :wallet_address},
transaction: %{balance_address: :wallet_address}
}
rename table(:wallet), to: table(:balance)
Enum.each(tables, fn {table, columns} ->
Enum.each(columns, fn {old_name, new_name} ->
drop constraint(table, "#{Atom.to_string(table)}_#{Atom.to_string(new_name)}_fkey")
rename table(table), new_name, to: old_name
end)
end)
drop index(:wallet, [:address])
create unique_index(:balance, [:address])
Enum.each(tables, fn {table, columns} ->
Enum.each(columns, fn {old_name, _new_name} ->
alter table(table) do
modify old_name, references(:balance, type: :string,
column: :address), null: false
end
end)
end)
end
end
| 31.797297 | 91 | 0.646409 |
736bed359b14982a8253b6c87db23abc249160c7
| 26,957 |
ex
|
Elixir
|
lib/rpi/compile.ex
|
ericmj/scenic_driver_nerves_rpi
|
91dc3bfe6fc5344cf31887e54ca7f3e5d9fc8deb
|
[
"Apache-2.0"
] | null | null | null |
lib/rpi/compile.ex
|
ericmj/scenic_driver_nerves_rpi
|
91dc3bfe6fc5344cf31887e54ca7f3e5d9fc8deb
|
[
"Apache-2.0"
] | null | null | null |
lib/rpi/compile.ex
|
ericmj/scenic_driver_nerves_rpi
|
91dc3bfe6fc5344cf31887e54ca7f3e5d9fc8deb
|
[
"Apache-2.0"
] | null | null | null |
#
# Created by Boyd Multerer on 06/01/18.
# Copyright © 2018 Kry10 Industries. All rights reserved.
#
# compile a graph out to a series of commands that can be drawn
# by the C render code
#
#
defmodule Scenic.Driver.Nerves.Rpi.Compile do
@moduledoc false
alias Scenic.Primitive
require Logger
# import IEx
# ============================================================================
# state handling
@op_push_state 0x01
@op_pop_state 0x02
# @op_reset_state 0x03
@op_run_script 0x04
# render styles
@op_paint_linear 0x06
@op_paint_box 0x07
@op_paint_radial 0x08
@op_paint_image 0x09
# @op_anti_alias 0x0A
@op_stroke_width 0x0C
@op_stroke_color 0x0D
@op_stroke_paint 0x0E
@op_fill_color 0x10
@op_fill_paint 0x11
@op_miter_limit 0x14
@op_line_cap 0x15
@op_line_join 0x16
# @op_global_alpha 0x17
# scissoring
# @op_scissor 0x1B
@op_intersect_scissor 0x1C
# @op_reset_scissor 0x1D
# path operations
@op_path_begin 0x20
@op_path_move_to 0x21
@op_path_line_to 0x22
@op_path_bezier_to 0x23
@op_path_quadratic_to 0x24
@op_path_arc_to 0x25
@op_path_close 0x26
@op_path_winding 0x27
@op_fill 0x29
@op_stroke 0x2A
@op_triangle 0x2C
@op_arc 0x2D
@op_rect 0x2E
@op_round_rect 0x2F
# @op_round_rect_var 0x30
@op_ellipse 0x31
@op_circle 0x32
@op_sector 0x33
@op_text 0x34
# transform operations
# @op_tx_reset 0x36
# @op_tx_identity 0x37
@op_tx_matrix 0x38
@op_tx_translate 0x39
@op_tx_scale 0x3A
@op_tx_rotate 0x3B
@op_tx_skew_x 0x3C
@op_tx_skew_y 0x3D
# text/font styles
@op_font 0x40
@op_font_blur 0x41
@op_font_size 0x42
@op_text_align 0x43
@op_text_height 0x44
@op_terminate 0xFF
# ============================================================================
# --------------------------------------------------------
def graph(nil, _, _) do
[]
end
def graph(_, nil, _) do
[]
end
def graph(graph, _graph_id, state) do
[]
|> compile_primitive(graph[0], graph, state)
|> op_terminate()
|> Enum.reverse()
end
# ============================================================================
# skip hidden primitives early
defp compile_primitive(ops, %{styles: %{hidden: true}}, _, _) do
ops
end
defp compile_primitive(ops, p, graph, state) do
ops
|> op_push_state()
|> compile_transforms(p)
|> compile_styles(p)
|> op_path_begin()
|> do_compile_primitive(p, graph, state)
|> do_fill(p)
|> do_stroke(p)
|> op_pop_state()
end
# --------------------------------------------------------
defp do_fill(ops, %{styles: %{fill: paint}}) do
case paint do
{:image, {image, ox, oy, ex, ey, angle, alpha}} ->
ops
|> op_paint_image(image, ox, oy, ex, ey, angle, alpha)
|> op_fill_paint()
_ ->
ops
end
|> op_fill()
end
defp do_fill(ops, _), do: ops
# --------------------------------------------------------
defp do_stroke(ops, %{styles: %{stroke: paint}}) do
case paint do
{:image, {image, ox, oy, ex, ey, angle, alpha}} ->
ops
|> op_paint_image(image, ox, oy, ex, ey, angle, alpha)
|> op_stroke_paint()
_ ->
ops
end
|> op_stroke()
end
defp do_stroke(ops, _), do: ops
# --------------------------------------------------------
defp do_compile_primitive(ops, %{data: {Primitive.Group, ids}}, graph, state) do
Enum.reduce(ids, ops, fn id, ops ->
compile_primitive(ops, graph[id], graph, state)
end)
end
defp do_compile_primitive(ops, %{data: {Primitive.Line, {{x0, y0}, {x1, y1}}}}, _, _) do
ops
|> op_path_move_to(x0, y0)
|> op_path_line_to(x1, y1)
end
defp do_compile_primitive(
ops,
%{data: {Primitive.Quad, {{x0, y0}, {x1, y1}, {x2, y2}, {x3, y3}}}},
_,
_
) do
ops
|> op_path_move_to(x0, y0)
|> op_path_line_to(x1, y1)
|> op_path_line_to(x2, y2)
|> op_path_line_to(x3, y3)
|> op_path_close()
end
defp do_compile_primitive(
ops,
%{data: {Primitive.Triangle, {{x0, y0}, {x1, y1}, {x2, y2}}}},
_,
_
) do
ops
|> op_triangle(x0, y0, x1, y1, x2, y2)
end
defp do_compile_primitive(ops, %{data: {Primitive.Rectangle, {width, height}}}, _, _) do
op_rect(ops, width, height)
end
defp do_compile_primitive(
ops,
%{data: {Primitive.RoundedRectangle, {width, height, radius}}},
_,
_
) do
op_round_rect(ops, width, height, radius)
end
defp do_compile_primitive(ops, %{data: {Primitive.Circle, radius}}, _, _) do
op_circle(ops, radius)
end
defp do_compile_primitive(ops, %{data: {Primitive.Ellipse, {r1, r2}}}, _, _) do
op_ellipse(ops, r1, r2)
end
defp do_compile_primitive(ops, %{data: {Primitive.Arc, {radius, start, finish}}}, _, _) do
op_arc(ops, radius, start, finish)
end
defp do_compile_primitive(ops, %{data: {Primitive.Sector, {radius, start, finish}}}, _, _) do
op_sector(ops, radius, start, finish)
end
defp do_compile_primitive(ops, %{data: {Primitive.Path, actions}}, _, _) do
Enum.reduce(actions, ops, fn
:begin, ops ->
op_path_begin(ops)
{:move_to, x, y}, ops ->
op_path_move_to(ops, x, y)
{:line_to, x, y}, ops ->
op_path_line_to(ops, x, y)
{:bezier_to, c1x, c1y, c2x, c2y, x, y}, ops ->
op_path_bezier_to(ops, c1x, c1y, c2x, c2y, x, y)
{:quadratic_to, cx, cy, x, y}, ops ->
op_path_quadratic_to(ops, cx, cy, x, y)
{:arc_to, x1, y1, x2, y2, radius}, ops ->
op_path_arc_to(ops, x1, y1, x2, y2, radius)
:close_path, ops ->
op_path_close(ops)
:solid, ops ->
op_path_winding(ops, :solid)
:hole, ops ->
op_path_winding(ops, :hole)
# {:arc, cx, cy, r, a0, a1}, ops ->
# op_arc(ops, cx, cy, r, a0, a1, :solid)
# {:rect, x, y, w, h}, ops -> op_rect(ops, x, y, w, h)
# {:round_rect, x, y, w, h, r}, ops -> op_round_rect(ops, x, y, w, h, r)
# {:ellipse, cx, cy, rx, ry}, ops -> op_ellipse(ops, cx, cy, rx, ry)
# {:circle, cx, cy, r}, ops -> op_circle(ops, cx, cy, r)
end)
end
defp do_compile_primitive(ops, %{data: {Primitive.Text, text}}, _, _) do
ops
|> op_text(text)
end
defp do_compile_primitive(ops, %{data: {Primitive.SceneRef, {:graph, _, _} = graph_key}}, _, %{
dl_map: dl_map
}) do
case dl_map[graph_key] do
nil ->
ops
id ->
[
<<
@op_run_script::unsigned-integer-size(32)-native,
id::unsigned-integer-size(32)-native
>>
| ops
]
end
end
# defp do_primitive_four( %{data: {Scenic.Primitive.SceneRef, {:graph,_,_} = graph_key}},
# _, _, %{dl_map: dl_map} ) do
# case dl_map[graph_key] do
# nil ->
# # Logger.error "GLFW nil SceneRef #{inspect(graph_key)}"
# []
# dl_id ->
# # prepare the draw command
# <<
# @id_sub_graph :: size(8),
# dl_id :: unsigned-integer-size(32)-native
# >>
# end
# end
# ignore unrecognized primitives
defp do_compile_primitive(ops, _p, _graph, _state) do
ops
end
# ============================================================================
defp compile_styles(ops, %{styles: styles}) do
Enum.reduce(styles, ops, fn {key, value}, ops -> do_compile_style(ops, key, value) end)
end
defp compile_styles(ops, _), do: ops
defp do_compile_style(ops, :join, type), do: op_line_join(ops, type)
defp do_compile_style(ops, :cap, type), do: op_line_cap(ops, type)
defp do_compile_style(ops, :miter_limit, limit), do: op_miter_limit(ops, limit)
defp do_compile_style(ops, :font, font), do: op_font(ops, font)
defp do_compile_style(ops, :font_blur, blur), do: op_font_blur(ops, blur)
defp do_compile_style(ops, :font_size, size), do: op_font_size(ops, size)
defp do_compile_style(ops, :text_align, align), do: op_text_align(ops, align)
defp do_compile_style(ops, :text_height, height), do: op_text_height(ops, height)
defp do_compile_style(ops, :scissor, {w, h}) do
[
<<
@op_intersect_scissor::unsigned-integer-size(32)-native,
w::float-size(32)-native,
h::float-size(32)-native
>>
| ops
]
end
defp do_compile_style(ops, :fill, paint) do
case paint do
{:color, color} ->
op_fill_color(ops, color)
{:linear, {sx, sy, ex, ey, color_start, color_end}} ->
ops
|> op_paint_linear(sx, sy, ex, ey, color_start, color_end)
|> op_fill_paint()
{:box, {x, y, w, h, feather, radius, color_start, color_end}} ->
ops
|> op_paint_box(x, y, w, h, feather, radius, color_start, color_end)
|> op_fill_paint()
{:radial, {cx, cy, r_in, r_out, color_start, color_end}} ->
ops
|> op_paint_radial(cx, cy, r_in, r_out, color_start, color_end)
|> op_fill_paint()
# don't handle image pattern here. Should be set after the path is drawn
_ ->
ops
end
end
defp do_compile_style(ops, :stroke, {width, paint}) do
case paint do
{:color, color} ->
op_stroke_color(ops, color)
{:linear, {sx, sy, ex, ey, color_start, color_end}} ->
ops
|> op_paint_linear(sx, sy, ex, ey, color_start, color_end)
|> op_stroke_paint()
{:box, {x, y, w, h, feather, radius, color_start, color_end}} ->
ops
|> op_paint_box(x, y, w, h, feather, radius, color_start, color_end)
|> op_stroke_paint()
{:radial, {cx, cy, r_in, r_out, color_start, color_end}} ->
ops
|> op_paint_radial(cx, cy, r_in, r_out, color_start, color_end)
|> op_stroke_paint()
# don't handle image pattern here. Should be set after the path is drawn
_ ->
ops
end
|> op_stroke_width(width)
end
defp do_compile_style(ops, _op, _value), do: ops
# ============================================================================
defp compile_transforms(ops, %{transforms: txs}) do
ops
|> do_compile_tx(:matrix, txs[:matrix])
|> do_compile_tx(:translate, txs[:translate])
|> do_compile_tx(:skew_x, txs[:skew_x])
|> do_compile_tx(:skew_y, txs[:skew_y])
|> do_compile_tx(:pin, txs[:pin])
|> do_compile_tx(:rotate, txs[:rotate])
|> do_compile_tx(:scale, txs[:scale])
|> do_compile_tx(:inv_pin, txs[:pin])
end
defp compile_transforms(ops, _), do: ops
defp do_compile_tx(ops, :translate, {dx, dy}) do
[
<<
@op_tx_translate::unsigned-integer-size(32)-native,
dx::float-size(32)-native,
dy::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :pin, {dx, dy}) do
[
<<
@op_tx_translate::unsigned-integer-size(32)-native,
dx::float-size(32)-native,
dy::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :inv_pin, {dx, dy}) do
{dx, dy} = Scenic.Math.Vector2.invert({dx, dy})
[
<<
@op_tx_translate::unsigned-integer-size(32)-native,
dx::float-size(32)-native,
dy::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :scale, {sx, sy}) do
[
<<
@op_tx_scale::unsigned-integer-size(32)-native,
sx::float-size(32)-native,
sy::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :rotate, value) when is_number(value) do
[
<<
@op_tx_rotate::unsigned-integer-size(32)-native,
value::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :skew_x, value) when is_number(value) do
[
<<
@op_tx_skew_x::unsigned-integer-size(32)-native,
value::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :skew_y, value) when is_number(value) do
[
<<
@op_tx_skew_y::unsigned-integer-size(32)-native,
value::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, :matrix, <<
a::float-size(32)-native,
c::float-size(32)-native,
e::float-size(32)-native,
b::float-size(32)-native,
d::float-size(32)-native,
f::float-size(32)-native,
_::binary
>>) do
[
<<
@op_tx_matrix::unsigned-integer-size(32)-native,
a::float-size(32)-native,
b::float-size(32)-native,
c::float-size(32)-native,
d::float-size(32)-native,
e::float-size(32)-native,
f::float-size(32)-native
>>
| ops
]
end
defp do_compile_tx(ops, _op, _v), do: ops
# ============================================================================
# low-level commands that get compiled into the ops list
# each new command is added to the front of the list, which will be reversed at the end.
# --------------------------------------------------------
defp op_push_state(ops), do: [<<@op_push_state::unsigned-integer-size(32)-native>> | ops]
defp op_pop_state(ops), do: [<<@op_pop_state::unsigned-integer-size(32)-native>> | ops]
# defp op_reset_state(ops), do: [ <<@op_reset_state :: size(8) >> | ops ]
# #--------------------------------------------------------
# defp op_run_script(ops, script_id) do
# [
# <<
# @op_run_script :: size(8),
# script_id :: size(32)
# >>
# | ops]
# end
# --------------------------------------------------------
defp op_paint_linear(ops, sx, sy, ex, ey, {sr, sg, sb, sa}, {er, eg, eb, ea}) do
[
<<
@op_paint_linear::unsigned-integer-size(32)-native,
sx::float-size(32)-native,
sy::float-size(32)-native,
ex::float-size(32)-native,
ey::float-size(32)-native,
sr::unsigned-integer-size(32)-native,
sg::unsigned-integer-size(32)-native,
sb::unsigned-integer-size(32)-native,
sa::unsigned-integer-size(32)-native,
er::unsigned-integer-size(32)-native,
eg::unsigned-integer-size(32)-native,
eb::unsigned-integer-size(32)-native,
ea::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_paint_box(ops, x, y, w, h, radius, feather, {sr, sg, sb, sa}, {er, eg, eb, ea}) do
[
<<
@op_paint_box::unsigned-integer-size(32)-native,
x::float-size(32)-native,
y::float-size(32)-native,
w::float-size(32)-native,
h::float-size(32)-native,
radius::float-size(32)-native,
feather::float-size(32)-native,
sr::unsigned-integer-size(32)-native,
sg::unsigned-integer-size(32)-native,
sb::unsigned-integer-size(32)-native,
sa::unsigned-integer-size(32)-native,
er::unsigned-integer-size(32)-native,
eg::unsigned-integer-size(32)-native,
eb::unsigned-integer-size(32)-native,
ea::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_paint_radial(ops, cx, cy, r_in, r_out, {sr, sg, sb, sa}, {er, eg, eb, ea}) do
[
<<
@op_paint_radial::unsigned-integer-size(32)-native,
cx::float-size(32)-native,
cy::float-size(32)-native,
r_in::float-size(32)-native,
r_out::float-size(32)-native,
sr::unsigned-integer-size(32)-native,
sg::unsigned-integer-size(32)-native,
sb::unsigned-integer-size(32)-native,
sa::unsigned-integer-size(32)-native,
er::unsigned-integer-size(32)-native,
eg::unsigned-integer-size(32)-native,
eb::unsigned-integer-size(32)-native,
ea::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_paint_image(ops, image, ox, oy, ex, ey, angle, alpha) do
name_size = byte_size(image) + 1
# keep everything aligned on 4 byte boundaries
{name_size, extra_buffer} =
case 4 - rem(name_size, 4) do
1 -> {name_size + 1, <<0::size(8)>>}
2 -> {name_size + 2, <<0::size(16)>>}
3 -> {name_size + 3, <<0::size(24)>>}
_ -> {name_size, <<>>}
end
[
<<
@op_paint_image::unsigned-integer-size(32)-native,
ox::float-size(32)-native,
oy::float-size(32)-native,
ex::float-size(32)-native,
ey::float-size(32)-native,
angle::float-size(32)-native,
alpha::unsigned-integer-size(32)-native,
name_size::unsigned-integer-size(32)-native,
image::binary,
# null terminate to it can be used directly
0::size(8),
extra_buffer::binary
>>
| ops
]
end
# --------------------------------------------------------
# defp op_anti_alias(ops, true) do
# [ << @op_anti_alias :: size(8), 1 :: size(8) >> | ops]
# end
# defp op_anti_alias(ops, false) do
# [ << @op_anti_alias :: size(8), 0 :: size(8) >> | ops]
# end
defp op_stroke_width(ops, w) do
[
<<
@op_stroke_width::unsigned-integer-size(32)-native,
w::float-size(32)-native
>>
| ops
]
end
defp op_stroke_color(ops, {r, g, b, a}) do
[
<<
@op_stroke_color::unsigned-integer-size(32)-native,
r::unsigned-integer-size(32)-native,
g::unsigned-integer-size(32)-native,
b::unsigned-integer-size(32)-native,
a::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_stroke_paint(ops) do
[<<@op_stroke_paint::unsigned-integer-size(32)-native>> | ops]
end
defp op_fill_color(ops, {r, g, b, a}) do
[
<<
@op_fill_color::unsigned-integer-size(32)-native,
r::unsigned-integer-size(32)-native,
g::unsigned-integer-size(32)-native,
b::unsigned-integer-size(32)-native,
a::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_fill_paint(ops) do
[<<@op_fill_paint::unsigned-integer-size(32)-native>> | ops]
end
defp op_miter_limit(ops, limit) do
[
<<
@op_miter_limit::unsigned-integer-size(32)-native,
limit::float-size(32)-native
>>
| ops
]
end
defp op_line_cap(ops, :butt) do
[
<<
@op_line_cap::unsigned-integer-size(32)-native,
0::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_line_cap(ops, :round) do
[
<<
@op_line_cap::unsigned-integer-size(32)-native,
1::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_line_cap(ops, :square) do
[
<<
@op_line_cap::unsigned-integer-size(32)-native,
2::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_line_join(ops, :miter) do
[
<<
@op_line_join::unsigned-integer-size(32)-native,
0::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_line_join(ops, :round) do
[
<<
@op_line_join::unsigned-integer-size(32)-native,
1::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_line_join(ops, :bevel) do
[
<<
@op_line_join::unsigned-integer-size(32)-native,
2::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_font(ops, font) do
font_name = to_string(font)
name_size = byte_size(font_name) + 1
# keep everything aligned on 4 byte boundaries
{name_size, extra_buffer} =
case 4 - rem(name_size, 4) do
1 -> {name_size + 1, <<0::size(8)>>}
2 -> {name_size + 2, <<0::size(16)>>}
3 -> {name_size + 3, <<0::size(24)>>}
_ -> {name_size, <<>>}
end
[
<<
@op_font::unsigned-integer-size(32)-native,
name_size::unsigned-integer-size(32)-native,
font_name::binary,
# null terminate the name here. This allows us to use the
# string in the script directly without copying it to a new buffer
0::size(8),
extra_buffer::binary
>>
| ops
]
end
defp op_font_blur(ops, blur) do
[
<<
@op_font_blur::unsigned-integer-size(32)-native,
blur::float-size(32)-native
>>
| ops
]
end
defp op_font_size(ops, point_size) do
[
<<
@op_font_size::unsigned-integer-size(32)-native,
point_size::float-size(32)-native
>>
| ops
]
end
defp op_text_align(ops, :left), do: op_text_align(ops, 0b1000001)
defp op_text_align(ops, :center), do: op_text_align(ops, 0b1000010)
defp op_text_align(ops, :right), do: op_text_align(ops, 0b1000100)
defp op_text_align(ops, :left_top), do: op_text_align(ops, 0b0001001)
defp op_text_align(ops, :center_top), do: op_text_align(ops, 0b0001010)
defp op_text_align(ops, :right_top), do: op_text_align(ops, 0b0001100)
defp op_text_align(ops, :left_middle), do: op_text_align(ops, 0b0010001)
defp op_text_align(ops, :center_middle), do: op_text_align(ops, 0b0010010)
defp op_text_align(ops, :right_middle), do: op_text_align(ops, 0b0010100)
defp op_text_align(ops, :left_bottom), do: op_text_align(ops, 0b0100001)
defp op_text_align(ops, :center_bottom), do: op_text_align(ops, 0b0100010)
defp op_text_align(ops, :right_bottom), do: op_text_align(ops, 0b0100100)
defp op_text_align(ops, flags) when is_integer(flags) do
[
<<
@op_text_align::unsigned-integer-size(32)-native,
flags::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_text_height(ops, height) do
[
<<
@op_text_height::unsigned-integer-size(32)-native,
height::float-size(32)-native
>>
| ops
]
end
# --------------------------------------------------------
defp op_path_begin(ops), do: [<<@op_path_begin::unsigned-integer-size(32)-native>> | ops]
defp op_path_move_to(ops, x, y) do
[
<<
@op_path_move_to::unsigned-integer-size(32)-native,
x::float-size(32)-native,
y::float-size(32)-native
>>
| ops
]
end
defp op_path_line_to(ops, x, y) do
[
<<
@op_path_line_to::unsigned-integer-size(32)-native,
x::float-size(32)-native,
y::float-size(32)-native
>>
| ops
]
end
defp op_path_bezier_to(ops, c1x, c1y, c2x, c2y, x, y) do
[
<<
@op_path_bezier_to::unsigned-integer-size(32)-native,
c1x::float-size(32)-native,
c1y::float-size(32)-native,
c2x::float-size(32)-native,
c2y::float-size(32)-native,
x::float-size(32)-native,
y::float-size(32)-native
>>
| ops
]
end
defp op_path_quadratic_to(ops, cx, cy, x, y) do
[
<<
@op_path_quadratic_to::unsigned-integer-size(32)-native,
cx::float-size(32)-native,
cy::float-size(32)-native,
x::float-size(32)-native,
y::float-size(32)-native
>>
| ops
]
end
defp op_path_arc_to(ops, x1, y1, x2, y2, radius) do
[
<<
@op_path_arc_to::unsigned-integer-size(32)-native,
x1::float-size(32)-native,
y1::float-size(32)-native,
x2::float-size(32)-native,
y2::float-size(32)-native,
radius::float-size(32)-native
>>
| ops
]
end
defp op_path_close(ops) do
[<<@op_path_close::unsigned-integer-size(32)-native>> | ops]
end
defp op_path_winding(ops, :solid) do
[
<<
@op_path_winding::unsigned-integer-size(32)-native,
1::unsigned-integer-size(32)-native
>>
| ops
]
end
defp op_path_winding(ops, :hole) do
[
<<
@op_path_winding::unsigned-integer-size(32)-native,
0::unsigned-integer-size(32)-native
>>
| ops
]
end
# --------------------------------------------------------
defp op_triangle(ops, x0, y0, x1, y1, x2, y2) do
[
<<
@op_triangle::unsigned-integer-size(32)-native,
x0::float-size(32)-native,
y0::float-size(32)-native,
x1::float-size(32)-native,
y1::float-size(32)-native,
x2::float-size(32)-native,
y2::float-size(32)-native
>>
| ops
]
end
defp op_rect(ops, w, h) do
[
<<
@op_rect::unsigned-integer-size(32)-native,
w::float-size(32)-native,
h::float-size(32)-native
>>
| ops
]
end
defp op_round_rect(ops, w, h, r) do
[
<<
@op_round_rect::unsigned-integer-size(32)-native,
w::float-size(32)-native,
h::float-size(32)-native,
r::float-size(32)-native
>>
| ops
]
end
defp op_circle(ops, r) do
[
<<
@op_circle::unsigned-integer-size(32)-native,
r::float-size(32)-native
>>
| ops
]
end
# defp op_arc(ops,_,_,_, start, finish, _,_) when start == finish, do: ops
defp op_arc(ops, r, start, finish) do
[
<<
@op_arc::unsigned-integer-size(32)-native,
r::float-size(32)-native,
start::float-size(32)-native,
finish::float-size(32)-native
>>
| ops
]
end
# defp op_sector(ops,_,_,_, start, finish, _,_) when start == finish, do: ops
defp op_sector(ops, r, start, finish) do
[
<<
@op_sector::unsigned-integer-size(32)-native,
r::float-size(32)-native,
start::float-size(32)-native,
finish::float-size(32)-native
>>
| ops
]
end
defp op_ellipse(ops, rx, ry) do
[
<<
@op_ellipse::unsigned-integer-size(32)-native,
rx::float-size(32)-native,
ry::float-size(32)-native
>>
| ops
]
end
defp op_text(ops, text) do
text_size = byte_size(text) + 1
# keep everything aligned on 4 byte boundaries
{text_size, extra_buffer} =
case 4 - rem(text_size, 4) do
1 -> {text_size + 1, <<0::size(8)>>}
2 -> {text_size + 2, <<0::size(16)>>}
3 -> {text_size + 3, <<0::size(24)>>}
_ -> {text_size, <<>>}
end
[
<<
@op_text::unsigned-integer-size(32)-native,
text_size::unsigned-integer-size(32)-native,
text::binary,
# null terminate the string so it can be used directly
0::size(8),
extra_buffer::binary
>>
| ops
]
end
# --------------------------------------------------------
defp op_fill(ops), do: [<<@op_fill::unsigned-integer-size(32)-native>> | ops]
defp op_stroke(ops), do: [<<@op_stroke::unsigned-integer-size(32)-native>> | ops]
# --------------------------------------------------------
defp op_terminate(ops), do: [<<@op_terminate::unsigned-integer-size(32)-native>> | ops]
end
| 25.94514 | 97 | 0.551063 |
736c29c6f95c90d37c87146996060ac563a4455d
| 1,386 |
ex
|
Elixir
|
lib/timber/eventable.ex
|
axelson/timber-elixir
|
def9de8ebbb64a6f6d5dd85f8958d8b24f8d6c31
|
[
"0BSD"
] | 244 |
2016-10-10T15:30:32.000Z
|
2021-08-11T08:45:53.000Z
|
lib/timber/eventable.ex
|
axelson/timber-elixir
|
def9de8ebbb64a6f6d5dd85f8958d8b24f8d6c31
|
[
"0BSD"
] | 242 |
2016-10-10T19:34:44.000Z
|
2020-11-20T18:56:43.000Z
|
lib/timber/eventable.ex
|
axelson/timber-elixir
|
def9de8ebbb64a6f6d5dd85f8958d8b24f8d6c31
|
[
"0BSD"
] | 35 |
2016-12-04T07:33:04.000Z
|
2020-06-17T20:22:11.000Z
|
defprotocol Timber.Eventable do
@moduledoc ~S"""
Protocol that converts a data structure into a `Timber.Event.t`.
This is called on any data structure used in the `:event` metadata key passed to `Logger` calls.
## Example
For example, you can use this protocol to pass format event structs:
defmodule OrderPlacedEvent do
defstruct [:order_id, :total]
defimpl Timber.Eventable do
def to_event(event) do
map = Map.from_struct(event)
%{order_placed: map}
end
end
end
Then you can use it like so:
Logger.info(fn ->
event = %OrderPlacedEvent{order_id: "abcd", total: 100.23}
message = "Order #{event.id} placed"
{message, event: event}
end)
"""
@fallback_to_any true
@doc """
Converts the data structure into a `Timber.Event.t`.
"""
@spec to_event(any) :: Timber.Event.t()
def to_event(data)
end
defimpl Timber.Eventable, for: Map do
def to_event(%{type: type, data: data}) do
%{type => data}
end
def to_event(map) do
map
end
end
defimpl Timber.Eventable, for: Any do
def to_event(%{__exception__: true} = error) do
message = Exception.message(error)
module_name = Timber.Utils.Module.name(error.__struct__)
%{
error: %{
name: module_name,
message: message
}
}
end
end
| 21.65625 | 98 | 0.62482 |
736c5930f16a21b616ec73383ad0d65ba52ae067
| 532 |
ex
|
Elixir
|
lib/honeydew/dispatcher/mru.ex
|
evadne/honeydew
|
c3c2f6095a28393cae13c0e686bdb6257d532ca1
|
[
"MIT"
] | null | null | null |
lib/honeydew/dispatcher/mru.ex
|
evadne/honeydew
|
c3c2f6095a28393cae13c0e686bdb6257d532ca1
|
[
"MIT"
] | null | null | null |
lib/honeydew/dispatcher/mru.ex
|
evadne/honeydew
|
c3c2f6095a28393cae13c0e686bdb6257d532ca1
|
[
"MIT"
] | null | null | null |
defmodule Honeydew.Dispatcher.MRU do
# TODO: docs
# TODO: abstract common LRU/MRU functionality?
def init do
{:ok, :queue.new}
end
def available?(free) do
!:queue.is_empty(free)
end
def check_in(worker, free) do
:queue.in_r(worker, free)
end
def check_out(_job, free) do
case :queue.out(free) do
{{:value, worker}, free} ->
{worker, free}
{:empty, _free} ->
{nil, free}
end
end
def remove(worker, free) do
:queue.filter(&(&1 != worker), free)
end
end
| 17.733333 | 48 | 0.599624 |
736c8723b748029bda4ac3654ef002fc2d2c45de
| 403 |
ex
|
Elixir
|
lib/source_academy_admin/plugs/assign_current_student.ex
|
trewdys/source-academy2-debug
|
6146e1fac81472184877f47aa32dee7fdceb4fb6
|
[
"Unlicense"
] | null | null | null |
lib/source_academy_admin/plugs/assign_current_student.ex
|
trewdys/source-academy2-debug
|
6146e1fac81472184877f47aa32dee7fdceb4fb6
|
[
"Unlicense"
] | null | null | null |
lib/source_academy_admin/plugs/assign_current_student.ex
|
trewdys/source-academy2-debug
|
6146e1fac81472184877f47aa32dee7fdceb4fb6
|
[
"Unlicense"
] | null | null | null |
defmodule SourceAcademy.Plug.AssignCurrentStudent do
@moduledoc false
import Plug.Conn
alias SourceAcademy.Course
def init(opts), do: opts
def call(conn, _opts) do
current_user = conn.assigns[:current_user]
if current_user != nil do
current_student = Course.get_student(current_user)
assign(conn, :current_student, current_student)
else
conn
end
end
end
| 21.210526 | 56 | 0.719603 |
736caab523c18375af4536af856244029cc488fd
| 3,075 |
ex
|
Elixir
|
lib/github/http.ex
|
Gimi/coders
|
28e20558ac26709c62b8463dae963e4e41a759b2
|
[
"MIT"
] | null | null | null |
lib/github/http.ex
|
Gimi/coders
|
28e20558ac26709c62b8463dae963e4e41a759b2
|
[
"MIT"
] | null | null | null |
lib/github/http.ex
|
Gimi/coders
|
28e20558ac26709c62b8463dae963e4e41a759b2
|
[
"MIT"
] | null | null | null |
defmodule Github.HTTP do
@moduledoc """
This module implements functions to handle github HTTP API calls,
esp. makes it easier to handle github API responses.
"""
require Logger
use HTTPoison.Base
@doc """
Just like HTTPoison.Base.get/1, but ignores error cases (error or non 200 responses).
For error cases, it will return the default value, which by default is nil.
"""
@spec get_or(String.t, any) :: HTTPoison.Response.t | any
def get_or(url, default \\ nil) do
case get(url) do
{:ok, resp = %HTTPoison.Response{status_code: 200}} -> resp
{:ok, %HTTPoison.Response{status_code: code}} ->
Logger.error("GET #{url} returned #{code}.")
default
{:error, %HTTPoison.Error{reason: reason}} ->
Logger.error("GET #{url} failed with #{reason}.")
default
end
end
# we just want the body!
def get_or!(url, default \\ nil) do
case get_or(url, default) do
%HTTPoison.Response{body: body} -> Poison.decode!(body)
resp -> resp
end
end
@doc """
Get a collection reponse as a stream. If nothing returned,
return an empty list.
"""
@spec get_stream(String.t) :: Enumerable.t
def get_stream(url) do
case resp = get_or(url, []) do
%HTTPoison.Response{} -> pagination_stream(resp)
_ -> resp
end
end
@doc "Make a paginated resource, e.g. event, as a stream."
@spec pagination_stream(HTTPoison.Response.t) :: Stream.t
def pagination_stream(%HTTPoison.Response{body: body} = resp) do
start_fn = fn -> {Poison.decode!(body), next_page_link(resp)} end
next_fn =
fn {items, next_link} ->
case items do
[head|tail] -> {[head], {tail, next_link}}
_ ->
case next_link do
nil -> {:halt, {items, next_link}}
_ ->
resp = get!(next_link)
case Poison.decode!(resp.body) do
[head|tail] -> {[head], {tail, next_page_link(resp)}}
_ -> {:halt, {[], nil}}
end
end
end
end
end_fn = fn _ -> end
Stream.resource(start_fn, next_fn, end_fn)
end
@doc false
# Get the next page link from a pagenated response.
defp next_page_link(%HTTPoison.Response{headers: headers}) do
if links = List.keyfind(headers, "Link", 0) do
link = elem(links, 1)
|> String.split(", ")
|> Stream.filter(&(String.ends_with?(&1, "rel=\"next\"")))
|> Stream.map(&(hd(String.split(&1, ";", parts: 2))))
|> Stream.map(&(&1 |> String.lstrip(?<) |> String.rstrip(?>)))
|> Enum.take(1)
case link do
[url] -> url
_ -> nil
end
end
end
@doc false
defp process_url(url) do
# url's may be returned by Github, those url's are absolute paths.
case url do
<<"https://", _::binary>> -> url
_ -> "https://api.github.com" <> url
end
end
end
| 30.445545 | 87 | 0.554472 |
736d0e9f04f1f974c8b1267f95858e64ce159a01
| 374 |
ex
|
Elixir
|
examples/example-phx-1_2/web/views/error_view.ex
|
devshane/thesis-phoenix
|
afe22a25542f91e15cfffb1e93ff8d833a64c25b
|
[
"MIT"
] | 681 |
2016-06-21T20:49:21.000Z
|
2022-02-19T04:08:38.000Z
|
examples/example-phx-1_2/web/views/error_view.ex
|
devshane/thesis-phoenix
|
afe22a25542f91e15cfffb1e93ff8d833a64c25b
|
[
"MIT"
] | 125 |
2016-06-21T21:14:49.000Z
|
2020-12-12T20:15:48.000Z
|
examples/example-phx-1_2/web/views/error_view.ex
|
devshane/thesis-phoenix
|
afe22a25542f91e15cfffb1e93ff8d833a64c25b
|
[
"MIT"
] | 76 |
2016-09-06T03:40:55.000Z
|
2022-01-20T21:29:22.000Z
|
defmodule Example.ErrorView do
use Example.Web, :view
def render("404.html", _assigns) do
"Page not found"
end
def render("500.html", _assigns) do
"Internal server error"
end
# In case no render clause matches or no
# template is found, let's render it as 500
def template_not_found(_template, assigns) do
render "500.html", assigns
end
end
| 20.777778 | 47 | 0.697861 |
736d2c219ba38d10b71dc0977ed3ea4d4c6b1ce5
| 7,510 |
exs
|
Elixir
|
test/ex_rabbit_m_q_test.exs
|
sger/exrabbitmq
|
3eae1c557a69b8ffb92ee8d4c828af613ba52f58
|
[
"MIT"
] | null | null | null |
test/ex_rabbit_m_q_test.exs
|
sger/exrabbitmq
|
3eae1c557a69b8ffb92ee8d4c828af613ba52f58
|
[
"MIT"
] | null | null | null |
test/ex_rabbit_m_q_test.exs
|
sger/exrabbitmq
|
3eae1c557a69b8ffb92ee8d4c828af613ba52f58
|
[
"MIT"
] | null | null | null |
defmodule ExRabbitMQTest do
use ExUnit.Case
alias ExRabbitMQ.Connection
alias ExRabbitMQ.Connection.Config, as: ConnectionConfig
alias ExRabbitMQ.Consumer.QueueConfig
test "publishing a message and then consuming it" do
# first we start the connection supervisor
# it holds the template for the GenServer wrapping connections to RabbitMQ
ExRabbitMQ.Connection.Supervisor.start_link()
# configuration for a default local RabbitMQ installation
connection_config = %ConnectionConfig{
username: "guest",
password: "guest",
host: "127.0.0.1",
reconnect_after: 500
}
test_queue = "xrmq_test"
test_exchange = "xrmq_test_exchange"
# configuration for a test queue where we will publish to/consumer from
queue_config = %QueueConfig{
queue: test_queue,
queue_opts: [durable: false, auto_delete: true],
exchange: test_exchange,
exchange_opts: [type: :direct, durable: false, auto_delete: true],
bind_opts: [],
qos_opts: [prefetch_count: 1],
consume_opts: [no_ack: true]
}
# the test message to be published and then consumed
test_message = "ExRabbitMQ test"
# we start the consumer so that the queue will be declared
{:ok, consumer} = ExRabbitMQConsumerTest.start_link(self(), connection_config, queue_config)
# we monitor the consumer so that we can wait for it to exit
consumer_monitor = Process.monitor(consumer)
# the consumer tells us that the connection has been opened
assert_receive(
{:consumer_connection_open, consumer_connection_pid},
500,
"failed to open a connection for the consumer"
)
# we monitor the consumer's connection GenServer wrapper so that we can wait for it to exit
consumer_connection_monitor = Process.monitor(consumer_connection_pid)
# is the consumer's connection truly ready?
assert({:ok, _consumer_connection} = Connection.get(consumer_connection_pid))
# are the consumer's channel and queue properly set up?
assert_receive(
{:consumer_state,
%{consumer_channel_setup_ok: true, consumer_queue_setup_ok: {:ok, ^test_queue}}},
500,
"failed to properly setup the consumer's channel and/or queue"
)
# we start the producer to publish our test message
{:ok, producer} =
ExRabbitMQProducerTest.start_link(self(), connection_config, test_queue, test_message)
# we monitor the producer so that we can wait for it to exit
producer_monitor = Process.monitor(producer)
# the producer tells us that the connection has been opened
assert_receive(
{:producer_connection_open, producer_connection_pid},
500,
"failed to open a connection for the producer"
)
# we monitor the producer's connection GenServer wrapper so that we can wait for it to exit
producer_connection_monitor = Process.monitor(producer_connection_pid)
# is the producer's connection truly ready?
assert({:ok, _producer_connection} = Connection.get(consumer_connection_pid))
# is the producers's channel properly set up?
assert_receive(
{:producer_state, %{producer_channel_setup_ok: true}},
500,
"failed to properly setup the producer's channel"
)
# the producer must have reused the same connection as the consumer
# when this connection is used for the maximum of 65535 channels,
# a new connection will be used for the next consumer/producer that needs one
assert consumer_connection_pid === producer_connection_pid
# the producer tells us that the message has been published
assert_receive({:publish, :ok}, 500, "failed to publish test message #{test_message}")
# the consumer tells us that the message that we published is the same we have consumed
assert_receive(
{:consume, ^test_message},
500,
"failed to receive test message #{test_message}"
)
# we stop everything
ExRabbitMQConsumerTest.stop(consumer)
ExRabbitMQProducerTest.stop(producer)
Connection.close(consumer_connection_pid)
Connection.close(producer_connection_pid)
# we make sure that everything has stopped as required before we exit
assert_receive({:DOWN, ^consumer_monitor, :process, _pid, _reason}, 500)
assert_receive({:DOWN, ^producer_monitor, :process, _pid, _reason}, 500)
assert_receive({:DOWN, ^consumer_connection_monitor, :process, _pid, _reason}, 500)
assert_receive({:DOWN, ^producer_connection_monitor, :process, _pid, _reason}, 500)
end
end
defmodule ExRabbitMQProducerTest do
@moduledoc false
use GenServer
use ExRabbitMQ.Producer
def start_link(tester_pid, connection_config, test_queue, test_message) do
GenServer.start_link(__MODULE__, %{
tester_pid: tester_pid,
connection_config: connection_config,
test_queue: test_queue,
test_message: test_message
})
end
def init(state) do
GenServer.cast(self(), :init)
{:ok, state}
end
def stop(producer_pid) do
GenServer.cast(producer_pid, :stop)
end
def handle_cast(
:init,
%{
tester_pid: tester_pid,
connection_config: connection_config,
test_queue: test_queue,
test_message: test_message
} = state
) do
new_state =
xrmq_init(connection_config, state)
|> xrmq_extract_state()
send(tester_pid, {:producer_connection_open, xrmq_get_connection_pid()})
send(tester_pid, {:producer_state, new_state})
publish_result = xrmq_basic_publish(test_message, "", test_queue)
send(tester_pid, {:publish, publish_result})
{:noreply, new_state}
end
def handle_cast(:stop, state) do
{:stop, :normal, state}
end
def handle_info(_, state) do
{:noreply, state}
end
def xrmq_channel_setup(channel, state) do
{:ok, state} = super(channel, state)
{:ok, Map.put(state, :producer_channel_setup_ok, true)}
end
end
defmodule ExRabbitMQConsumerTest do
@moduledoc false
use GenServer
use ExRabbitMQ.Consumer, GenServer
def start_link(tester_pid, connection_config, queue_config) do
GenServer.start_link(__MODULE__, %{
tester_pid: tester_pid,
connection_config: connection_config,
queue_config: queue_config
})
end
def init(state) do
GenServer.cast(self(), :init)
{:ok, state}
end
def stop(consumer_pid) do
GenServer.cast(consumer_pid, :stop)
end
def handle_cast(
:init,
%{
tester_pid: tester_pid,
connection_config: connection_config,
queue_config: queue_config
} = state
) do
new_state =
xrmq_init(connection_config, queue_config, state)
|> xrmq_extract_state()
send(tester_pid, {:consumer_connection_open, xrmq_get_connection_pid()})
send(tester_pid, {:consumer_state, new_state})
{:noreply, new_state}
end
def handle_cast(:stop, state) do
{:stop, :normal, state}
end
def handle_info(_, state) do
{:noreply, state}
end
def xrmq_basic_deliver(payload, _meta, %{tester_pid: tester_pid} = state) do
send(tester_pid, {:consume, payload})
{:noreply, state}
end
def xrmq_channel_setup(channel, state) do
{:ok, state} = super(channel, state)
{:ok, Map.put(state, :consumer_channel_setup_ok, true)}
end
def xrmq_queue_setup(channel, queue, state) do
{:ok, state} = super(channel, queue, state)
{:ok, Map.put(state, :consumer_queue_setup_ok, {:ok, queue})}
end
end
| 29.801587 | 96 | 0.702264 |
736d4532136c398a36d664c1256a633c7adc64f2
| 702 |
ex
|
Elixir
|
web/gettext.ex
|
mindsigns/soroban
|
c56962e1164a51cb5e383bbbfda880f098f181f1
|
[
"MIT"
] | 1 |
2020-02-09T03:03:04.000Z
|
2020-02-09T03:03:04.000Z
|
web/gettext.ex
|
mindsigns/soroban
|
c56962e1164a51cb5e383bbbfda880f098f181f1
|
[
"MIT"
] | null | null | null |
web/gettext.ex
|
mindsigns/soroban
|
c56962e1164a51cb5e383bbbfda880f098f181f1
|
[
"MIT"
] | null | null | null |
defmodule Soroban.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 Soroban.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: :soroban
end
| 28.08 | 72 | 0.678063 |
736d83d24a404776c318afbfb90384f0bac6d414
| 443 |
ex
|
Elixir
|
clients/elixir/generated/lib/swaggy_jenkins/model/pipeline_runs.ex
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 23 |
2017-08-01T12:25:26.000Z
|
2022-01-25T03:44:11.000Z
|
clients/elixir/generated/lib/swaggy_jenkins/model/pipeline_runs.ex
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 35 |
2017-06-14T03:28:15.000Z
|
2022-02-14T10:25:54.000Z
|
clients/elixir/generated/lib/swaggy_jenkins/model/pipeline_runs.ex
|
PankTrue/swaggy-jenkins
|
aca35a7cca6e1fcc08bd399e05148942ac2f514b
|
[
"MIT"
] | 11 |
2017-08-31T19:00:20.000Z
|
2021-12-19T12:04:12.000Z
|
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule SwaggyJenkins.Model.PipelineRuns do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
]
@type t :: %__MODULE__{
}
end
defimpl Poison.Decoder, for: SwaggyJenkins.Model.PipelineRuns do
def decode(value, _options) do
value
end
end
| 17.038462 | 91 | 0.693002 |
736d94bbc52a392baa4fe90a6adf199a5c7ae488
| 176 |
exs
|
Elixir
|
server/priv/repo/migrations/20160331235426_add_end_date_to_sprints.exs
|
MikaAK/trello-burndown
|
b78d97fa03fcdd60c1c9652b65d272936f648c6f
|
[
"MIT"
] | null | null | null |
server/priv/repo/migrations/20160331235426_add_end_date_to_sprints.exs
|
MikaAK/trello-burndown
|
b78d97fa03fcdd60c1c9652b65d272936f648c6f
|
[
"MIT"
] | 3 |
2016-04-18T18:09:21.000Z
|
2016-04-25T07:29:59.000Z
|
server/priv/repo/migrations/20160331235426_add_end_date_to_sprints.exs
|
MikaAK/trello-burndown
|
b78d97fa03fcdd60c1c9652b65d272936f648c6f
|
[
"MIT"
] | null | null | null |
defmodule TrelloBurndown.Repo.Migrations.AddEndDateToSprints do
use Ecto.Migration
def change do
alter table(:sprints) do
add :end_date, :date
end
end
end
| 17.6 | 63 | 0.727273 |
736dc85c0c658f176994daf0ada0eb79bee3b7d1
| 12,404 |
ex
|
Elixir
|
clients/tasks/lib/google_api/tasks/v1/api/tasklists.ex
|
mocknen/elixir-google-api
|
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
|
[
"Apache-2.0"
] | null | null | null |
clients/tasks/lib/google_api/tasks/v1/api/tasklists.ex
|
mocknen/elixir-google-api
|
dac4877b5da2694eca6a0b07b3bd0e179e5f3b70
|
[
"Apache-2.0"
] | null | null | null |
clients/tasks/lib/google_api/tasks/v1/api/tasklists.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.Tasks.V1.Api.Tasklists do
@moduledoc """
API calls for all endpoints tagged `Tasklists`.
"""
alias GoogleApi.Tasks.V1.Connection
alias GoogleApi.Gax.{Request, Response}
@doc """
Deletes the authenticated user's specified task list.
## Parameters
- connection (GoogleApi.Tasks.V1.Connection): Connection to server
- tasklist (String.t): Task list identifier.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %{}} on success
{:error, info} on failure
"""
@spec tasks_tasklists_delete(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, nil} | {:error, Tesla.Env.t()}
def tasks_tasklists_delete(connection, tasklist, 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("/users/@me/lists/{tasklist}", %{
"tasklist" => URI.encode_www_form(tasklist)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [decode: false])
end
@doc """
Returns the authenticated user's specified task list.
## Parameters
- connection (GoogleApi.Tasks.V1.Connection): Connection to server
- tasklist (String.t): Task list identifier.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
## Returns
{:ok, %GoogleApi.Tasks.V1.Model.TaskList{}} on success
{:error, info} on failure
"""
@spec tasks_tasklists_get(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Tasks.V1.Model.TaskList.t()} | {:error, Tesla.Env.t()}
def tasks_tasklists_get(connection, tasklist, 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("/users/@me/lists/{tasklist}", %{
"tasklist" => URI.encode_www_form(tasklist)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Tasks.V1.Model.TaskList{}])
end
@doc """
Creates a new task list and adds it to the authenticated user's task lists.
## Parameters
- connection (GoogleApi.Tasks.V1.Connection): Connection to server
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (TaskList):
## Returns
{:ok, %GoogleApi.Tasks.V1.Model.TaskList{}} on success
{:error, info} on failure
"""
@spec tasks_tasklists_insert(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.Tasks.V1.Model.TaskList.t()} | {:error, Tesla.Env.t()}
def tasks_tasklists_insert(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:post)
|> Request.url("/users/@me/lists")
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Tasks.V1.Model.TaskList{}])
end
@doc """
Returns all the authenticated user's task lists.
## Parameters
- connection (GoogleApi.Tasks.V1.Connection): Connection to server
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :maxResults (String.t): Maximum number of task lists returned on one page. Optional. The default is 100.
- :pageToken (String.t): Token specifying the result page to return. Optional.
## Returns
{:ok, %GoogleApi.Tasks.V1.Model.TaskLists{}} on success
{:error, info} on failure
"""
@spec tasks_tasklists_list(Tesla.Env.client(), keyword()) ::
{:ok, GoogleApi.Tasks.V1.Model.TaskLists.t()} | {:error, Tesla.Env.t()}
def tasks_tasklists_list(connection, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:maxResults => :query,
:pageToken => :query
}
request =
Request.new()
|> Request.method(:get)
|> Request.url("/users/@me/lists")
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Tasks.V1.Model.TaskLists{}])
end
@doc """
Updates the authenticated user's specified task list. This method supports patch semantics.
## Parameters
- connection (GoogleApi.Tasks.V1.Connection): Connection to server
- tasklist (String.t): Task list identifier.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (TaskList):
## Returns
{:ok, %GoogleApi.Tasks.V1.Model.TaskList{}} on success
{:error, info} on failure
"""
@spec tasks_tasklists_patch(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Tasks.V1.Model.TaskList.t()} | {:error, Tesla.Env.t()}
def tasks_tasklists_patch(connection, tasklist, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:patch)
|> Request.url("/users/@me/lists/{tasklist}", %{
"tasklist" => URI.encode_www_form(tasklist)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Tasks.V1.Model.TaskList{}])
end
@doc """
Updates the authenticated user's specified task list.
## Parameters
- connection (GoogleApi.Tasks.V1.Connection): Connection to server
- tasklist (String.t): Task list identifier.
- optional_params (KeywordList): [optional] Optional parameters
- :alt (String.t): Data format for the response.
- :fields (String.t): Selector specifying which fields to include in a partial response.
- :key (String.t): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
- :oauth_token (String.t): OAuth 2.0 token for the current user.
- :prettyPrint (boolean()): Returns response with indentations and line breaks.
- :quotaUser (String.t): An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
- :userIp (String.t): Deprecated. Please use quotaUser instead.
- :body (TaskList):
## Returns
{:ok, %GoogleApi.Tasks.V1.Model.TaskList{}} on success
{:error, info} on failure
"""
@spec tasks_tasklists_update(Tesla.Env.client(), String.t(), keyword()) ::
{:ok, GoogleApi.Tasks.V1.Model.TaskList.t()} | {:error, Tesla.Env.t()}
def tasks_tasklists_update(connection, tasklist, optional_params \\ [], opts \\ []) do
optional_params_config = %{
:alt => :query,
:fields => :query,
:key => :query,
:oauth_token => :query,
:prettyPrint => :query,
:quotaUser => :query,
:userIp => :query,
:body => :body
}
request =
Request.new()
|> Request.method(:put)
|> Request.url("/users/@me/lists/{tasklist}", %{
"tasklist" => URI.encode_www_form(tasklist)
})
|> Request.add_optional_params(optional_params_config, optional_params)
connection
|> Connection.execute(request)
|> Response.decode(opts ++ [struct: %GoogleApi.Tasks.V1.Model.TaskList{}])
end
end
| 39.629393 | 170 | 0.669703 |
736df02d5ad2957b4d0332b6c20b97019408d536
| 6,665 |
ex
|
Elixir
|
apps/abi/lib/abi.ex
|
atoulme/ethereum
|
cebb0756c7292ac266236636d2ab5705cb40a52e
|
[
"MIT"
] | 1 |
2018-09-21T02:58:03.000Z
|
2018-09-21T02:58:03.000Z
|
apps/abi/lib/abi.ex
|
atoulme/ethereum
|
cebb0756c7292ac266236636d2ab5705cb40a52e
|
[
"MIT"
] | null | null | null |
apps/abi/lib/abi.ex
|
atoulme/ethereum
|
cebb0756c7292ac266236636d2ab5705cb40a52e
|
[
"MIT"
] | null | null | null |
defmodule ABI do
@moduledoc """
Documentation for ABI, the function interface language for Solidity.
Generally, the ABI describes how to take binary Ethereum and transform
it to or from types that Solidity understands.
"""
@doc """
Encodes the given data into the function signature or tuple signature.
In place of a signature, you can also pass one of the `ABI.FunctionSelector` structs returned from `parse_specification/1`.
## Examples
iex> ABI.encode("baz(uint,address)", [50, <<1::160>> |> :binary.decode_unsigned])
...> |> Base.encode16(case: :lower)
"a291add600000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000001"
iex> ABI.encode("baz(uint8)", [9999])
** (RuntimeError) Data overflow encoding uint, data `9999` cannot fit in 8 bits
iex> ABI.encode("(uint,address)", [{50, <<1::160>> |> :binary.decode_unsigned}])
...> |> Base.encode16(case: :lower)
"00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000001"
iex> ABI.encode("(string)", [{"Ether Token"}])
...> |> Base.encode16(case: :lower)
"0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b457468657220546f6b656e000000000000000000000000000000000000000000"
iex> ABI.encode("(string)", [{String.duplicate("1234567890", 10)}])
...> |> Base.encode16(case: :lower)
"000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000643132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393000000000000000000000000000000000000000000000000000000000"
iex> File.read!("priv/dog.abi.json")
...> |> Poison.decode!
...> |> ABI.parse_specification
...> |> Enum.find(&(&1.function == "bark")) # bark(address,bool)
...> |> ABI.encode([<<1::160>> |> :binary.decode_unsigned, true])
...> |> Base.encode16(case: :lower)
"b85d0bd200000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001"
"""
def encode(function_signature, data) when is_binary(function_signature) do
encode(ABI.Parser.parse!(function_signature), data)
end
def encode(%ABI.FunctionSelector{} = function_selector, data) do
ABI.TypeEncoder.encode(data, function_selector)
end
@doc """
Decodes the given data based on the function or tuple
signature.
In place of a signature, you can also pass one of the `ABI.FunctionSelector` structs returned from `parse_specification/1`.
## Examples
iex> ABI.decode("baz(uint,address)", "00000000000000000000000000000000000000000000000000000000000000320000000000000000000000000000000000000000000000000000000000000001" |> Base.decode16!(case: :lower))
[50, <<1::160>>]
iex> ABI.decode("(address[])", "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000" |> Base.decode16!(case: :lower))
[{[]}]
iex> ABI.decode("(string)", "0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000b457468657220546f6b656e000000000000000000000000000000000000000000" |> Base.decode16!(case: :lower))
[{"Ether Token"}]
iex> File.read!("priv/dog.abi.json")
...> |> Poison.decode!
...> |> ABI.parse_specification
...> |> Enum.find(&(&1.function == "bark")) # bark(address,bool)
...> |> ABI.decode("00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000001" |> Base.decode16!(case: :lower))
[<<1::160>>, true]
"""
def decode(function_signature, data) when is_binary(function_signature) do
decode(ABI.Parser.parse!(function_signature), data)
end
def decode(%ABI.FunctionSelector{} = function_selector, data) do
ABI.TypeDecoder.decode(data, function_selector)
end
@doc """
Parses the given ABI specification document into an array of `ABI.FunctionSelector`s.
Non-function entries (e.g. constructors) in the ABI specification are skipped. Fallback function entries are accepted.
This function can be used in combination with a JSON parser, e.g. [`Poison`](https://hex.pm/packages/poison), to parse ABI specification JSON files.
## Examples
iex> File.read!("priv/dog.abi.json")
...> |> Poison.decode!
...> |> ABI.parse_specification
[%ABI.FunctionSelector{function: "bark", returns: nil, types: [:address, :bool]},
%ABI.FunctionSelector{function: "rollover", returns: :bool, types: []}]
iex> [%{
...> "constant" => true,
...> "inputs" => [
...> %{"name" => "at", "type" => "address"},
...> %{"name" => "loudly", "type" => "bool"}
...> ],
...> "name" => "bark",
...> "outputs" => [],
...> "payable" => false,
...> "stateMutability" => "nonpayable",
...> "type" => "function"
...> }]
...> |> ABI.parse_specification
[%ABI.FunctionSelector{function: "bark", returns: nil, types: [:address, :bool]}]
iex> [%{
...> "inputs" => [
...> %{"name" => "_numProposals", "type" => "uint8"}
...> ],
...> "payable" => false,
...> "stateMutability" => "nonpayable",
...> "type" => "constructor"
...> }]
...> |> ABI.parse_specification
[]
iex> ABI.decode("(string)", "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000643132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393031323334353637383930313233343536373839303132333435363738393000000000000000000000000000000000000000000000000000000000" |> Base.decode16!(case: :lower))
[{String.duplicate("1234567890", 10)}]
iex> [%{
...> "payable" => false,
...> "stateMutability" => "nonpayable",
...> "type" => "fallback"
...> }]
...> |> ABI.parse_specification
[%ABI.FunctionSelector{function: nil, returns: nil, types: []}]
"""
def parse_specification(doc) do
doc
|> Enum.map(&ABI.FunctionSelector.parse_specification_item/1)
|> Enum.filter(& &1)
end
end
| 47.607143 | 453 | 0.701725 |
736e058a8c5035ff7dc9cc75ffac75b28a443dd0
| 119 |
ex
|
Elixir
|
lib/pow_assent.ex
|
mitcheaton1/pow_assent
|
f3e9e6cc7dd16a3f2d9add885bd160d227abb713
|
[
"MIT"
] | 193 |
2019-10-30T00:58:21.000Z
|
2022-03-09T20:26:37.000Z
|
lib/pow_assent.ex
|
mitcheaton1/pow_assent
|
f3e9e6cc7dd16a3f2d9add885bd160d227abb713
|
[
"MIT"
] | 82 |
2019-10-29T20:19:38.000Z
|
2022-03-22T04:09:27.000Z
|
lib/pow_assent.ex
|
mitcheaton1/pow_assent
|
f3e9e6cc7dd16a3f2d9add885bd160d227abb713
|
[
"MIT"
] | 28 |
2019-10-31T12:38:10.000Z
|
2021-11-01T18:05:23.000Z
|
defmodule PowAssent do
@moduledoc false
use Pow.Extension.Base
@impl true
def phoenix_messages?, do: true
end
| 14.875 | 33 | 0.747899 |
736e857ea3d29f3d2fa5894e037ced82ed1d7fb6
| 1,111 |
exs
|
Elixir
|
apps/amf0/config/config.exs
|
Kabie/elixir-media-libs
|
9750c6dcdffdf8014183a6a4f303c5d0d658f062
|
[
"MIT"
] | 75 |
2016-12-23T14:37:18.000Z
|
2021-04-26T14:07:20.000Z
|
apps/amf0/config/config.exs
|
Kabie/elixir-media-libs
|
9750c6dcdffdf8014183a6a4f303c5d0d658f062
|
[
"MIT"
] | 19 |
2016-12-22T03:20:43.000Z
|
2020-06-11T12:10:37.000Z
|
apps/amf0/config/config.exs
|
Kabie/elixir-media-libs
|
9750c6dcdffdf8014183a6a4f303c5d0d658f062
|
[
"MIT"
] | 3 |
2018-03-29T06:40:40.000Z
|
2019-02-13T09:37:19.000Z
|
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :amf0, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:amf0, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.83871 | 73 | 0.749775 |
736e8c3ea9084a70b76fa2cf60cdced60bafea5e
| 458 |
exs
|
Elixir
|
01/npkstuff/test/npkstuff_web/views/error_view_test.exs
|
victordomingos/Learning_Elixir
|
414f4f647c9eba494b65575e725a58021fde2313
|
[
"MIT"
] | 1 |
2021-06-23T21:48:32.000Z
|
2021-06-23T21:48:32.000Z
|
01/npkstuff/test/npkstuff_web/views/error_view_test.exs
|
victordomingos/Learning_Elixir
|
414f4f647c9eba494b65575e725a58021fde2313
|
[
"MIT"
] | null | null | null |
01/npkstuff/test/npkstuff_web/views/error_view_test.exs
|
victordomingos/Learning_Elixir
|
414f4f647c9eba494b65575e725a58021fde2313
|
[
"MIT"
] | null | null | null |
defmodule NpkstuffWeb.ErrorViewTest do
use NpkstuffWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.json" do
assert render(NpkstuffWeb.ErrorView, "404.json", []) == %{errors: %{detail: "Not Found"}}
end
test "renders 500.json" do
assert render(NpkstuffWeb.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| 28.625 | 93 | 0.68559 |
736eaf771c8d1b87d61378088bd4f468338ea0ba
| 2,041 |
ex
|
Elixir
|
clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_batch_update_user_links_request.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_batch_update_user_links_request.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/analytics_admin/lib/google_api/analytics_admin/v1alpha/model/google_analytics_admin_v1alpha_batch_update_user_links_request.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1 |
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchUpdateUserLinksRequest do
@moduledoc """
Request message for BatchUpdateUserLinks RPC.
## Attributes
* `requests` (*type:* `list(GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaUpdateUserLinkRequest.t)`, *default:* `nil`) - The requests specifying the user links to update. A maximum of 1000 user links can be updated in a batch.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:requests =>
list(
GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaUpdateUserLinkRequest.t()
)
}
field(:requests,
as: GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaUpdateUserLinkRequest,
type: :list
)
end
defimpl Poison.Decoder,
for:
GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchUpdateUserLinksRequest do
def decode(value, options) do
GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchUpdateUserLinksRequest.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.AnalyticsAdmin.V1alpha.Model.GoogleAnalyticsAdminV1alphaBatchUpdateUserLinksRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.016667 | 250 | 0.759432 |
736ec898297f7fce25e3dd55dd3f322bb41cf0fd
| 396 |
ex
|
Elixir
|
lib/attentive/http.ex
|
malomohq/attentive-elixir
|
0bb550b482a1da6e344779aa0d077eacc790f021
|
[
"MIT"
] | null | null | null |
lib/attentive/http.ex
|
malomohq/attentive-elixir
|
0bb550b482a1da6e344779aa0d077eacc790f021
|
[
"MIT"
] | 3 |
2021-08-06T16:50:58.000Z
|
2022-02-21T17:18:12.000Z
|
lib/attentive/http.ex
|
malomohq/attentive-elixir
|
0bb550b482a1da6e344779aa0d077eacc790f021
|
[
"MIT"
] | null | null | null |
defmodule Attentive.Http do
alias Attentive.{ Request }
@type response_t ::
%{
body: String.t(),
headers: Attentive.http_headers_t(),
status_code: Attentive.http_status_code_t()
}
@callback send(
request :: Request.t(),
opts :: any
) :: { :ok, response_t } | { :error, response_t | any }
end
| 24.75 | 67 | 0.517677 |
736ecb067e9bf38956dc7f4a59c4a8f78fd3987e
| 786 |
ex
|
Elixir
|
lib/optimus/arg.ex
|
corka149/optimus
|
12c0dc597691d04481513f4e2345812e38e63f73
|
[
"MIT"
] | 82 |
2016-12-14T22:21:45.000Z
|
2019-11-19T13:47:25.000Z
|
lib/optimus/arg.ex
|
corka149/optimus
|
12c0dc597691d04481513f4e2345812e38e63f73
|
[
"MIT"
] | 15 |
2017-01-08T06:54:02.000Z
|
2019-11-12T10:30:49.000Z
|
lib/optimus/arg.ex
|
corka149/optimus
|
12c0dc597691d04481513f4e2345812e38e63f73
|
[
"MIT"
] | 7 |
2017-01-08T06:42:41.000Z
|
2019-11-12T09:32:50.000Z
|
defmodule Optimus.Arg do
defstruct [
:name,
:value_name,
:help,
:required,
:parser
]
def new(spec) do
Optimus.Arg.Builder.build(spec)
end
def parse(arg, parsed, [item | command_line]) do
case arg.parser.(item) do
{:ok, value} ->
{:ok, Map.put(parsed, {:arg, arg.name}, value), command_line}
{:error, reason} ->
{:error, "invalid value #{inspect(item)} for #{arg.value_name}: #{reason}", command_line}
end
end
end
defimpl Optimus.Format, for: Optimus.Arg do
def format(arg), do: arg.value_name
def format_in_error(arg), do: arg.value_name
def format_in_usage(arg) do
if arg.required do
arg.value_name
else
"[#{arg.value_name}]"
end
end
def help(arg), do: arg.help || ""
end
| 19.65 | 97 | 0.611959 |
736ee170ff467d5cce8bf1446b6264169fed67cd
| 365 |
ex
|
Elixir
|
lib/four_lucha/person.ex
|
Thomas-Jean/four_lucha
|
591627059c02edc3315b5cac2c35eacb821108ff
|
[
"Apache-2.0"
] | 1 |
2021-02-21T19:15:27.000Z
|
2021-02-21T19:15:27.000Z
|
lib/four_lucha/person.ex
|
Thomas-Jean/four_lucha
|
591627059c02edc3315b5cac2c35eacb821108ff
|
[
"Apache-2.0"
] | null | null | null |
lib/four_lucha/person.ex
|
Thomas-Jean/four_lucha
|
591627059c02edc3315b5cac2c35eacb821108ff
|
[
"Apache-2.0"
] | null | null | null |
defmodule FourLucha.Person do
@moduledoc false
@item "person"
@items "people"
use FourLucha.BaseHelpers
use FourLucha.BaseSingular
use FourLucha.BasePlural
alias FourLucha.Resource.Person, as: Person
require FourLucha.Client
defp get_resource do
Person
end
defp get_known_query_params do
[:filter, :sort, :limit, :offset]
end
end
| 18.25 | 45 | 0.739726 |
736f3566b5c679f175e06c2c4ce86ce981f7280d
| 1,736 |
ex
|
Elixir
|
clients/content/lib/google_api/content/v2/model/orderinvoices_create_charge_invoice_response.ex
|
kaaboaye/elixir-google-api
|
1896784c4342151fd25becd089a5beb323eff567
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v2/model/orderinvoices_create_charge_invoice_response.ex
|
kaaboaye/elixir-google-api
|
1896784c4342151fd25becd089a5beb323eff567
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v2/model/orderinvoices_create_charge_invoice_response.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.OrderinvoicesCreateChargeInvoiceResponse do
@moduledoc """
## Attributes
* `executionStatus` (*type:* `String.t`, *default:* `nil`) - The status of the execution.
* `kind` (*type:* `String.t`, *default:* `content#orderinvoicesCreateChargeInvoiceResponse`) - Identifies what kind of resource this is. Value: the fixed string "content#orderinvoicesCreateChargeInvoiceResponse".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:executionStatus => String.t(),
:kind => String.t()
}
field(:executionStatus)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse do
def decode(value, options) do
GoogleApi.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrderinvoicesCreateChargeInvoiceResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.72 | 216 | 0.748848 |
736f3acc8141066c9a3c3955a233d94493395e2d
| 606 |
ex
|
Elixir
|
apps/bankingAPI_web/lib/bankingAPI_web/input_validation.ex
|
danielkv7/bankingAPI
|
d84b9a12c72d6bbd7d3077346501fde6db25ef19
|
[
"Apache-2.0"
] | null | null | null |
apps/bankingAPI_web/lib/bankingAPI_web/input_validation.ex
|
danielkv7/bankingAPI
|
d84b9a12c72d6bbd7d3077346501fde6db25ef19
|
[
"Apache-2.0"
] | null | null | null |
apps/bankingAPI_web/lib/bankingAPI_web/input_validation.ex
|
danielkv7/bankingAPI
|
d84b9a12c72d6bbd7d3077346501fde6db25ef19
|
[
"Apache-2.0"
] | null | null | null |
defmodule BankingAPIWeb.InputValidation do
@moduledoc """
Validates a given map of params with the given schema.
"""
@doc """
Apply the changeset function of the given module passing params.
When successful, it returns {:ok, schema} and an instance of the the given
schema.
When validation fails, it returns {:error, changeset}.
"""
def cast_and_apply(params, module) do
case module.changeset(params) do
%{valid?: true} = changeset ->
{:ok, Ecto.Changeset.apply_changes(changeset)}
%{valid?: false} = changeset ->
{:error, changeset}
end
end
end
| 27.545455 | 76 | 0.674917 |
736f4d3c5320eac233d77c8b3f200f90e745d979
| 936 |
ex
|
Elixir
|
lib/pow_sessions_toolkit/session.ex
|
weareyipyip/Pow-Session-Toolkit
|
fb0c061a70824d2664816b71f22e11bd7fa71dd5
|
[
"Apache-2.0"
] | 1 |
2020-02-21T15:28:11.000Z
|
2020-02-21T15:28:11.000Z
|
lib/pow_sessions_toolkit/session.ex
|
weareyipyip/Pow-Session-Toolkit
|
fb0c061a70824d2664816b71f22e11bd7fa71dd5
|
[
"Apache-2.0"
] | null | null | null |
lib/pow_sessions_toolkit/session.ex
|
weareyipyip/Pow-Session-Toolkit
|
fb0c061a70824d2664816b71f22e11bd7fa71dd5
|
[
"Apache-2.0"
] | null | null | null |
defmodule PowSessionToolkit.Session do
@moduledoc """
A session as stored in Mnesia by `PowSessionToolkit.MnesiaSessionStore`.
"""
defstruct id: nil,
user_id: nil,
refresh_token_id: nil,
created_at: nil,
refreshed_at: nil,
last_known_ip: nil,
token_signature_transport: nil,
expires_at: nil
use PowSessionToolkit.Constants
@type t :: %__MODULE__{
id: String.t(),
user_id: pos_integer,
refresh_token_id: String.t(),
created_at: integer,
refreshed_at: integer,
last_known_ip: String.t(),
token_signature_transport: atom,
expires_at: integer | nil
}
@doc """
Gets a `%#{__MODULE__}{}` from a conn's `private` map.
"""
@spec get_from_conn(Plug.Conn.t()) :: t() | nil
def get_from_conn(conn) do
conn.private[@private_session_key]
end
end
| 26.742857 | 74 | 0.596154 |
736f6f9cbc0c5fbd47a0caee3e8978004888e0b1
| 2,681 |
ex
|
Elixir
|
lib/fastglobal.ex
|
LaudateCorpus1/fastglobal
|
275569454462312fc3f5214275fe7e739b5b2d25
|
[
"MIT"
] | 494 |
2017-09-21T20:26:48.000Z
|
2020-03-20T21:18:35.000Z
|
lib/fastglobal.ex
|
Seanpm2001-Discord/fastglobal
|
275569454462312fc3f5214275fe7e739b5b2d25
|
[
"MIT"
] | 9 |
2021-02-24T13:33:40.000Z
|
2022-01-31T04:05:55.000Z
|
lib/fastglobal.ex
|
Seanpm2001-Discord/fastglobal
|
275569454462312fc3f5214275fe7e739b5b2d25
|
[
"MIT"
] | 29 |
2020-07-28T08:31:28.000Z
|
2022-03-25T12:46:39.000Z
|
defmodule FastGlobal do
@moduledoc """
Abuse module constant pools as a "read-only shared heap" (since erts 5.6)
http://www.erlang.org/pipermail/erlang-questions/2009-March/042503.html
"""
@type t :: {__MODULE__, atom}
@doc """
Create a module for the FastGlobal instance.
"""
@spec new(atom) :: {__MODULE__, atom}
def new(key) do
{__MODULE__, key_to_module(key)}
end
@doc """
Get the value for `key` or return nil.
"""
@spec get(atom) :: any | nil
def get(key), do: get(key, nil)
@doc """
Get the value for `key` or return `default`.
"""
@spec get(atom | {__MODULE__, module}, any) :: any
def get({__MODULE__, module}, default), do: do_get(module, default)
def get(key, default), do: key |> key_to_module |> do_get(default)
@doc """
Store `value` at `key`, replaces an existing value if present.
"""
@spec put(atom | {__MODULE__, module}, any) :: :ok
def put({__MODULE__, module}, value), do: do_put(module, value)
def put(key, value), do: key |> key_to_module |> do_put(value)
@doc """
Delete value stored at `key`, no-op if non-existent.
"""
@spec delete(atom | {__MODULE__, module}) :: :ok
def delete({__MODULE__, module}), do: do_delete(module)
def delete(key), do: key |> key_to_module |> do_delete
## Private
@spec do_get(atom, any) :: any
defp do_get(module, default) do
try do
module.value
catch
:error, :undef ->
default
end
end
@spec do_put(atom, any) :: :ok
defp do_put(module, value) do
binary = compile(module, value)
:code.purge(module)
{:module, ^module} = :code.load_binary(module, '#{module}.erl', binary)
:ok
end
@spec do_delete(atom) :: :ok
defp do_delete(module) do
:code.purge(module)
:code.delete(module)
end
@spec key_to_module(atom) :: atom
defp key_to_module(key) do
# Don't use __MODULE__ because it is slower.
:"Elixir.FastGlobal.#{key}"
end
@spec compile(atom, any) :: binary
defp compile(module, value) do
{:ok, ^module, binary} = module
|> value_to_abstract(value)
|> Enum.map(&:erl_syntax.revert/1)
|> :compile.forms([:verbose, :report_errors])
binary
end
@spec value_to_abstract(atom, any) :: [:erl_syntax.syntaxTree]
defp value_to_abstract(module, value) do
import :erl_syntax
[
# -module(module).
attribute(
atom(:module),
[atom(module)]),
# -export([value/0]).
attribute(
atom(:export),
[list([arity_qualifier(atom(:value), integer(0))])]),
# value() -> value.
function(
atom(:value),
[clause([], :none, [abstract(value)])]),
]
end
end
| 25.778846 | 75 | 0.616188 |
736f807bff981acce7dc38e396b168f23b95652f
| 3,787 |
exs
|
Elixir
|
lib/elixir/test/elixir/process_test.exs
|
Joe-noh/elixir
|
34bf464bc1a035b6015366463e04f1bf9d2065f3
|
[
"Apache-2.0"
] | null | null | null |
lib/elixir/test/elixir/process_test.exs
|
Joe-noh/elixir
|
34bf464bc1a035b6015366463e04f1bf9d2065f3
|
[
"Apache-2.0"
] | null | null | null |
lib/elixir/test/elixir/process_test.exs
|
Joe-noh/elixir
|
34bf464bc1a035b6015366463e04f1bf9d2065f3
|
[
"Apache-2.0"
] | null | null | null |
Code.require_file "test_helper.exs", __DIR__
defmodule ProcessTest do
use ExUnit.Case, async: true
doctest Process
test "dictionary" do
assert Process.put(:foo, :bar) == nil
assert Process.put(:foo, :baz) == :bar
assert Process.get_keys() == [:foo]
assert Process.get_keys(:bar) == []
assert Process.get_keys(:baz) == [:foo]
assert Process.get(:foo) == :baz
assert Process.delete(:foo) == :baz
assert Process.get(:foo) == nil
end
test "group_leader/2 and group_leader/0" do
another = spawn_link(fn -> :timer.sleep(1000) end)
assert Process.group_leader(self(), another)
assert Process.group_leader == another
end
test "monitoring functions are inlined by the compiler" do
assert expand(quote(do: Process.monitor(pid())), __ENV__) ==
quote(do: :erlang.monitor(:process, pid()))
end
test "sleep/1" do
assert Process.sleep(0) == :ok
end
test "info/2" do
pid = spawn fn -> :timer.sleep(1000) end
assert Process.info(pid, :priority) == {:priority, :normal}
assert Process.info(pid, [:priority]) == [priority: :normal]
Process.exit(pid, :kill)
assert Process.info(pid, :backtrace) == nil
assert Process.info(pid, [:backtrace, :status]) == nil
end
test "info/2 with registered name" do
pid = spawn fn -> nil end
Process.exit(pid, :kill)
assert Process.info(pid, :registered_name) ==
nil
assert Process.info(pid, [:registered_name]) ==
nil
assert Process.info(self(), :registered_name) ==
{:registered_name, []}
assert Process.info(self(), [:registered_name]) ==
[registered_name: []]
Process.register(self(), __MODULE__)
assert Process.info(self(), :registered_name) ==
{:registered_name, __MODULE__}
assert Process.info(self(), [:registered_name]) ==
[registered_name: __MODULE__]
end
test "send_after/3 sends messages once expired" do
Process.send_after(self(), :hello, 10)
assert_receive :hello
end
test "send_after/3 returns a timer reference that can be read or cancelled" do
timer = Process.send_after(self(), :hello, 100_000)
refute_received :hello
assert is_integer Process.read_timer(timer)
assert is_integer Process.cancel_timer(timer)
timer = Process.send_after(self(), :hello, 0)
assert_receive :hello
assert Process.read_timer(timer) == false
assert Process.cancel_timer(timer) == false
end
test "exit(pid, :normal) does not cause the target process to exit" do
pid = spawn_link fn ->
receive do
:done -> nil
end
end
trap = Process.flag(:trap_exit, true)
true = Process.exit(pid, :normal)
refute_receive {:EXIT, ^pid, :normal}
assert Process.alive?(pid)
# now exit the process for real so it doesn't hang around
true = Process.exit(pid, :abnormal)
assert_receive {:EXIT, ^pid, :abnormal}
refute Process.alive?(pid)
Process.flag(:trap_exit, trap)
end
test "exit(pid, :normal) makes the process receive a message if it traps exits" do
parent = self()
pid = spawn_link fn ->
Process.flag(:trap_exit, true)
receive do
{:EXIT, ^parent, :normal} -> send(parent, {:ok, self()})
end
end
refute_receive _
Process.exit(pid, :normal)
assert_receive {:ok, ^pid}
refute Process.alive?(pid)
end
test "exit(self(), :normal) causes the calling process to exit" do
trap = Process.flag(:trap_exit, true)
pid = spawn_link fn -> Process.exit(self(), :normal) end
assert_receive {:EXIT, ^pid, :normal}
refute Process.alive?(pid)
Process.flag(:trap_exit, trap)
end
defp expand(expr, env) do
{expr, _env} = :elixir_exp.expand(expr, env)
expr
end
end
| 28.261194 | 84 | 0.64827 |
736f96b40bf744e40e882b92e523de6a38b3a2e4
| 1,913 |
exs
|
Elixir
|
config/prod.exs
|
hamiltop/ashes
|
74882221af8d4fd96cd5d88e32fa6a6b3df44c77
|
[
"MIT"
] | 1 |
2019-09-04T10:06:04.000Z
|
2019-09-04T10:06:04.000Z
|
config/prod.exs
|
hamiltop/ashes
|
74882221af8d4fd96cd5d88e32fa6a6b3df44c77
|
[
"MIT"
] | null | null | null |
config/prod.exs
|
hamiltop/ashes
|
74882221af8d4fd96cd5d88e32fa6a6b3df44c77
|
[
"MIT"
] | null | null | null |
use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :ashes, Ashes.Endpoint,
http: [port: 54321],
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/manifest.json",
server: true,
secret_key_base: System.get_env("SECRET_KEY_BASE")
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :ashes, Ashes.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :ashes, Ashes.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :ashes, Ashes.Endpoint, server: true
#
| 31.883333 | 67 | 0.709357 |
736faab63f79c5d445ade20e40b2412494c4aa4e
| 937 |
ex
|
Elixir
|
lib/together/application.ex
|
BryanJBryce/Get-Together
|
7c6a5456e849a48d3575bf2caa957974228f1126
|
[
"MIT"
] | 1 |
2019-10-23T16:02:08.000Z
|
2019-10-23T16:02:08.000Z
|
lib/together/application.ex
|
BryanJBryce/Get-Together
|
7c6a5456e849a48d3575bf2caa957974228f1126
|
[
"MIT"
] | 1 |
2021-03-09T20:59:56.000Z
|
2021-03-09T20:59:56.000Z
|
lib/together/application.ex
|
BryanJBryce/Get-Together
|
7c6a5456e849a48d3575bf2caa957974228f1126
|
[
"MIT"
] | 1 |
2019-10-22T15:07:36.000Z
|
2019-10-22T15:07:36.000Z
|
defmodule Together.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the Ecto repository
Together.Repo,
# Start the endpoint when the application starts
TogetherWeb.Endpoint
# Starts a worker by calling: Together.Worker.start_link(arg)
# {Together.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Together.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
TogetherWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 29.28125 | 67 | 0.716115 |
736fc92b6224f5839910a488d98cbbcc8dff5400
| 2,241 |
exs
|
Elixir
|
test/weberTest/response_test.exs
|
elixir-web/weber
|
1c8caa43681cc432813dff33b2c6d08ca1d61f29
|
[
"MIT"
] | 124 |
2015-01-03T16:48:21.000Z
|
2022-02-02T21:13:11.000Z
|
test/weberTest/response_test.exs
|
elixir-web/weber
|
1c8caa43681cc432813dff33b2c6d08ca1d61f29
|
[
"MIT"
] | 2 |
2015-03-08T05:29:36.000Z
|
2015-07-19T15:31:19.000Z
|
test/weberTest/response_test.exs
|
elixir-web/weber
|
1c8caa43681cc432813dff33b2c6d08ca1d61f29
|
[
"MIT"
] | 12 |
2015-02-23T02:09:27.000Z
|
2016-08-07T13:50:38.000Z
|
defmodule WeberHttpResponseTest do
use ExUnit.Case
test "SimpleResponse test" do
{:ok, status, _, client} = :hackney.request(:get, 'http://localhost:8080/weber', [], <<>>, [])
body = :hackney.body(client)
assert(body == {:ok, "Main\n"})
assert(status == 200)
end
test "json response with custom status" do
{:ok, status, _, client} = :hackney.request(:get, 'http://localhost:8080/json/action', [], <<>>, [])
body = :hackney.body(client)
assert(body == {:ok, "[]"})
assert(status == 201)
end
test "`redirect` in route test" do
{:ok, status, _, _client} = :hackney.request(:get, 'http://localhost:8080/redirect', [], <<>>, [])
assert(status == 302)
end
test "`content_for` test" do
{:ok, _status, _, client} = :hackney.request(:get, 'http://localhost:8080/content_for', [], <<>>, [])
body = :hackney.body(client)
assert(body == {:ok, "<!DOCTYPE html>\n<html>\n <head>\n <title>\n My Project\n </title>\n <meta http-equiv=\"content-type\" content=\"text/html;charset=utf-8\" />\n </head>\n <body>\n <div id=\"container\">\n Hello Weber! \n </div>\n </body>\n</html> "})
end
test "raise unauthorized exception" do
{:ok, status, _, client} = :hackney.request(:get, 'http://localhost:8080/unauthorized', [], <<>>, [])
body = :hackney.body(client)
assert(status == 401)
assert(body == {:ok, "Unauthorized"})
end
test "raise 500 exception" do
{:ok, status, _, client} = :hackney.request(:get, 'http://localhost:8080/unknown', [], <<>>, [])
body = :hackney.body(client)
assert(status == 500)
assert(body == {:ok, "An unknown error occurred"})
end
test "rendering other action" do
{:ok, status, _, client} = :hackney.request(:get, 'http://localhost:8080/render_other_action', [], <<>>, [])
body = :hackney.body(client)
assert(status == 200)
assert(body == {:ok, "original value"})
end
test "rendering other controller and action" do
{:ok, status, _, client} = :hackney.request(:get, 'http://localhost:8080/render_other_controller', [], <<>>, [])
body = :hackney.body(client)
assert(status == 200)
assert(body == {:ok, "Main Controller: original value"})
end
end
| 39.315789 | 291 | 0.599732 |
736fd619e6b96d4e52e59f5a053beb59513e9a5e
| 969 |
ex
|
Elixir
|
templates/ecto/lib/repo.ex
|
Nebo15/enew
|
9a6ff3993b3be38943023df8d9f6e6a23dcbd8e2
|
[
"MIT"
] | 34 |
2016-08-13T17:05:32.000Z
|
2019-10-21T07:11:21.000Z
|
templates/ecto/lib/repo.ex
|
Nebo15/enew
|
9a6ff3993b3be38943023df8d9f6e6a23dcbd8e2
|
[
"MIT"
] | 7 |
2016-08-18T11:33:44.000Z
|
2017-10-03T12:28:27.000Z
|
templates/ecto/lib/repo.ex
|
Nebo15/enew
|
9a6ff3993b3be38943023df8d9f6e6a23dcbd8e2
|
[
"MIT"
] | 6 |
2016-10-12T08:57:25.000Z
|
2021-05-26T04:18:21.000Z
|
defmodule <%= @module_name %>.Repo do
@moduledoc """
Repo for Ecto database.
More info: https://hexdocs.pm/ecto/Ecto.Repo.html
"""
use Ecto.Repo, otp_app: :<%= @application_name %>
@doc """
Dynamically loads the repository configuration from the environment variables.
"""
def init(_, config) do
url = System.get_env("DATABASE_URL")
config =
if url,
do: Keyword.merge(config, Ecto.Repo.Supervisor.parse_url(url)),
else: Confex.process_env(config)
unless config[:database] do
raise "Set DB_NAME environment variable!"
end
unless config[:username] do
raise "Set DB_USER environment variable!"
end
unless config[:password] do
raise "Set DB_PASSWORD environment variable!"
end
unless config[:hostname] do
raise "Set DB_HOST environment variable!"
end
unless config[:port] do
raise "Set DB_PORT environment variable!"
end
{:ok, config}
end
end
| 23.071429 | 80 | 0.659443 |
737012d403e3dcede1c750e92ee916dfbb2481bf
| 1,692 |
ex
|
Elixir
|
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_uiv1beta3_export_processor_version_response.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1 |
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_uiv1beta3_export_processor_version_response.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1 |
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/document_ai/lib/google_api/document_ai/v1beta2/model/google_cloud_documentai_uiv1beta3_export_processor_version_response.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3ExportProcessorVersionResponse do
@moduledoc """
Response message associated with the ExportProcessorVersion operation.
## Attributes
* `gcsUri` (*type:* `String.t`, *default:* `nil`) - The Cloud Storage URI containing the output artifacts.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:gcsUri => String.t() | nil
}
field(:gcsUri)
end
defimpl Poison.Decoder,
for:
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3ExportProcessorVersionResponse do
def decode(value, options) do
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3ExportProcessorVersionResponse.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for:
GoogleApi.DocumentAI.V1beta2.Model.GoogleCloudDocumentaiUiv1beta3ExportProcessorVersionResponse do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.333333 | 110 | 0.759456 |
73705607c53c478094a6ad70f1e56c520aa91c8a
| 1,787 |
exs
|
Elixir
|
mix.exs
|
alexiob/scenic_driver_waveshare
|
8d0e026447649a94e439d226435cd667662a1f5c
|
[
"MIT"
] | 5 |
2020-01-09T09:09:57.000Z
|
2021-02-08T21:47:09.000Z
|
mix.exs
|
alexiob/scenic_driver_waveshare
|
8d0e026447649a94e439d226435cd667662a1f5c
|
[
"MIT"
] | null | null | null |
mix.exs
|
alexiob/scenic_driver_waveshare
|
8d0e026447649a94e439d226435cd667662a1f5c
|
[
"MIT"
] | null | null | null |
defmodule Waveshare.MixProject do
use Mix.Project
@app :scenic_driver_waveshare
@version "0.8.1"
@all_targets [:rpi, :rpi0, :rpi2, :rpi3, :rpi3a, :rpi4]
def project do
[
app: @app,
version: @version,
elixir: "~> 1.9",
description: description(),
start_permanent: Mix.env() == :prod,
deps: deps(),
docs: docs(),
package: package()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger, :runtime_tools]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# Dependencies for all targets
{:scenic, "~> 0.10.2"},
# Dependencies for all targets except :host
{:circuits_gpio, "~> 0.4.1", targets: @all_targets},
{:circuits_spi, "~> 0.1.3", targets: @all_targets},
{:scenic_driver_gpio, "~> 0.2", targets: @all_targets},
{:scenic_driver_nerves_rpi, "~> 0.10.1", targets: @all_targets},
{:rpi_fb_capture, "~> 0.2.1", targets: @all_targets},
# Dependencies for :host
{:scenic_driver_glfw, "~> 0.10.1", targets: :host},
# Dev dependencies
{:credo, "~> 1.0.0", only: [:dev, :test], runtime: false},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
defp description do
"Scenic render and input driver for Waveshare display HAT for Raspberry PI"
end
defp docs() do
[
main: Scenic.Driver.Nerves.Waveshare,
extras: [
"README.md": [
title: "Readme"
]
]
]
end
defp package do
%{
name: "scenic_driver_waveshare",
description: description(),
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/alexiob/scenic_driver_waveshare"}
}
end
end
| 24.148649 | 80 | 0.581981 |
737060e0927e98c16f02ba35fd2b54686258fb2f
| 3,398 |
exs
|
Elixir
|
test/tube/builder_test.exs
|
baradox/tube
|
50d127af88cc56ae93978ba326a4e43b61f5dbeb
|
[
"MIT"
] | 1 |
2016-07-07T05:46:22.000Z
|
2016-07-07T05:46:22.000Z
|
test/tube/builder_test.exs
|
baradox/tube
|
50d127af88cc56ae93978ba326a4e43b61f5dbeb
|
[
"MIT"
] | null | null | null |
test/tube/builder_test.exs
|
baradox/tube
|
50d127af88cc56ae93978ba326a4e43b61f5dbeb
|
[
"MIT"
] | null | null | null |
defmodule Tube.BuilderTest do
defmodule Module do
import Tube.Context
def init(val) do
{:init, val}
end
def call(context, opts) do
stack = [{:call, opts}|fetch!(context, :stack)]
assign(context, :stack, stack)
end
end
defmodule Sample do
use Tube.Builder
tube :fun
tube Module, :opts
def fun(context, opts) do
stack = [{:fun, opts}|fetch!(context, :stack)]
assign(context, :stack, stack)
end
end
defmodule Overridable do
use Tube.Builder
import Tube.Context
def call(context, opts) do
try do
super(context, opts)
catch
:throw, {:oops, context} -> assign(context, :oops, :caught)
end
end
tube :boom
def boom(context, opts) do
context = assign(context, :entered_stack, true)
throw {:oops, context}
end
end
defmodule Halter do
use Tube.Builder
import Tube.Context
tube :step, :first
tube :step, :second
tube :halt_here
tube :step, :end_of_chain_reached
def step(context, step), do: assign(context, step, true)
def halt_here(context, _) do
context |> assign(:halted, true) |> halt
end
end
defmodule FaultyModuleTube do
defmodule FaultyTube do
def init([]), do: []
# Doesn't return a Tube.Context
def call(_conntext, _opts), do: "foo"
end
use Tube.Builder
tube FaultyTube
end
defmodule FaultyFunctionTube do
use Tube.Builder
tube :faulty_function
# Doesn't return a Tube.Context
def faulty_function(_context, _opts), do: "foo"
end
defmodule ShorthandTube do
use Tube.Builder
tube foo(context) do
assign(context, :foo, true)
end
end
use ExUnit.Case, async: true
import Tube.Context
test "export init/1 function" do
assert Sample.init(:ok) == :ok
end
test "build stack in the order" do
context = context(stack: [])
assert Sample.call(context, []) |> fetch!(:stack) == [call: {:init, :opts}, fun: []]
end
test "shorthand definition defines a tube" do
context = context([]) |> ShorthandTube.call([])
assert fetch!(context, :foo)
end
test "allows call/2 to be overridden with super" do
context = context([]) |> Overridable.call([])
assert fetch!(context, :oops) == :caught
assert fetch!(context, :entered_stack)
end
test "halt/2 halts the tube stack" do
context = context([]) |> Halter.call([])
assert fetch!(context, :first)
assert fetch!(context, :second)
assert fetch!(context, :halted)
refute get(context, :end_of_chain_reached)
end
test "an exception is raised if a tube doesn't return a connection" do
assert_raise RuntimeError, fn ->
context([]) |> FaultyModuleTube.call([])
end
assert_raise RuntimeError, fn ->
context([]) |> FaultyFunctionTube.call([])
end
end
test "an exception is raised at compile time if a Tube.Builder tube " <>
"doesn't call tube/2" do
assert_raise RuntimeError, fn ->
defmodule BadTube, do: use Tube.Builder
end
end
test "an exception is raised at compile time if a tube with no call/2 " <>
"function is tubbed" do
assert_raise ArgumentError, fn ->
defmodule BadTube do
defmodule Bad do
def init(opts), do: opts
end
use Tube.Builder
tube Bad
end
end
end
end
| 22.20915 | 88 | 0.629194 |
7370a176ea4e31f53d9add345e1e22b7911bcb1d
| 53 |
ex
|
Elixir
|
test/support/system_mock.ex
|
jeffkreeftmeijer/bad_seed
|
9c29c310e334f54cae49f7b30cbb96268d03bb11
|
[
"MIT"
] | 1 |
2018-04-05T17:38:52.000Z
|
2018-04-05T17:38:52.000Z
|
test/support/system_mock.ex
|
jeffkreeftmeijer/bad_seed
|
9c29c310e334f54cae49f7b30cbb96268d03bb11
|
[
"MIT"
] | null | null | null |
test/support/system_mock.ex
|
jeffkreeftmeijer/bad_seed
|
9c29c310e334f54cae49f7b30cbb96268d03bb11
|
[
"MIT"
] | null | null | null |
defmodule SystemMock do
def at_exit(_), do: []
end
| 13.25 | 24 | 0.698113 |
7370b24c05c617331233e858b0cadd76b5865adc
| 1,653 |
exs
|
Elixir
|
config/dev.exs
|
Pliavi/NLW-4-Rocketpay
|
fc146eb534e8dac634d618c7779b928b6172cbb2
|
[
"MIT"
] | null | null | null |
config/dev.exs
|
Pliavi/NLW-4-Rocketpay
|
fc146eb534e8dac634d618c7779b928b6172cbb2
|
[
"MIT"
] | 1 |
2021-03-05T12:39:11.000Z
|
2021-03-05T12:39:11.000Z
|
config/dev.exs
|
Pliavi/NLW-4-Rocketpay
|
fc146eb534e8dac634d618c7779b928b6172cbb2
|
[
"MIT"
] | null | null | null |
use Mix.Config
# Configure your database
config :rocketpay, Rocketpay.Repo,
username: "root",
password: "root",
database: "rocketpay_dev",
hostname: "localhost",
show_sensitive_data_on_connection_error: true,
pool_size: 10
# 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 :rocketpay, RocketpayWeb.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
check_origin: false,
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 28.5 | 68 | 0.726558 |
7370c6553ed316e7d08417c0cb054c3b8071356f
| 433 |
ex
|
Elixir
|
lib/aph/qa/question.ex
|
tometoproject/tometo
|
ed91069b11a020723edb9a143de29d9bac86a2b0
|
[
"BlueOak-1.0.0",
"Apache-2.0"
] | 8 |
2019-09-26T13:59:25.000Z
|
2020-03-30T21:26:48.000Z
|
lib/aph/qa/question.ex
|
tometoproject/tometo
|
ed91069b11a020723edb9a143de29d9bac86a2b0
|
[
"BlueOak-1.0.0",
"Apache-2.0"
] | 39 |
2019-11-16T02:24:28.000Z
|
2020-01-14T16:40:28.000Z
|
lib/aph/qa/question.ex
|
tometoproject/tometo
|
ed91069b11a020723edb9a143de29d9bac86a2b0
|
[
"BlueOak-1.0.0",
"Apache-2.0"
] | 2 |
2019-12-16T07:55:14.000Z
|
2020-06-11T04:14:00.000Z
|
defmodule Aph.QA.Question do
@moduledoc """
The Question model.
"""
use Ecto.Schema
import Ecto.Changeset
schema "questions" do
field :content, :string
has_many :inboxes, Aph.QA.Inbox
timestamps(type: :utc_datetime)
end
@doc false
def changeset(question, attrs) do
question
|> cast(attrs, [:content])
|> validate_required([:content])
|> validate_length(:content, max: 500)
end
end
| 18.041667 | 42 | 0.662818 |
7370c72b924e7bdd54d2eb1dc2e597e76dc51e62
| 1,772 |
ex
|
Elixir
|
clients/docs/lib/google_api/docs/v1/model/create_named_range_request.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/docs/lib/google_api/docs/v1/model/create_named_range_request.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/docs/lib/google_api/docs/v1/model/create_named_range_request.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Docs.V1.Model.CreateNamedRangeRequest do
@moduledoc """
Creates a NamedRange referencing the given
range.
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the NamedRange. Names do not need to be unique.
Names must be at least 1 character and no more than 256 characters,
measured in UTF-16 code units.
* `range` (*type:* `GoogleApi.Docs.V1.Model.Range.t`, *default:* `nil`) - The range to apply the name to.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t(),
:range => GoogleApi.Docs.V1.Model.Range.t()
}
field(:name)
field(:range, as: GoogleApi.Docs.V1.Model.Range)
end
defimpl Poison.Decoder, for: GoogleApi.Docs.V1.Model.CreateNamedRangeRequest do
def decode(value, options) do
GoogleApi.Docs.V1.Model.CreateNamedRangeRequest.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Docs.V1.Model.CreateNamedRangeRequest do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.814815 | 113 | 0.721219 |
7370e9bee1b43225e940547b0cd4fef81875a24e
| 529 |
ex
|
Elixir
|
lib/mastani_server_web/middleware/put_current_user.ex
|
DavidAlphaFox/coderplanets_server
|
3fd47bf3bba6cc04c9a34698201a60ad2f3e8254
|
[
"Apache-2.0"
] | 1 |
2019-05-07T15:03:54.000Z
|
2019-05-07T15:03:54.000Z
|
lib/mastani_server_web/middleware/put_current_user.ex
|
DavidAlphaFox/coderplanets_server
|
3fd47bf3bba6cc04c9a34698201a60ad2f3e8254
|
[
"Apache-2.0"
] | null | null | null |
lib/mastani_server_web/middleware/put_current_user.ex
|
DavidAlphaFox/coderplanets_server
|
3fd47bf3bba6cc04c9a34698201a60ad2f3e8254
|
[
"Apache-2.0"
] | null | null | null |
# ---
# Absinthe.Middleware behaviour
# see https://hexdocs.pm/absinthe/Absinthe.Middleware.html#content
# ---
defmodule MastaniServerWeb.Middleware.PutCurrentUser do
@behaviour Absinthe.Middleware
def call(%{context: %{cur_user: cur_user}} = resolution, _) do
arguments = resolution.arguments |> Map.merge(%{cur_user: cur_user})
%{resolution | arguments: arguments}
end
def call(%{errors: errors} = resolution, _) when length(errors) > 0, do: resolution
def call(resolution, _) do
resolution
end
end
| 26.45 | 85 | 0.718336 |
737102f34f0e4f07020ba7b00f37a1067c2e6748
| 2,155 |
exs
|
Elixir
|
test/ex_oauth2_provider/oauth2/utils/device_flow_test.exs
|
heroinbob/ex_oauth2_provider
|
80c21a53bba0955ab3b66f1bd32cc81db0f04f49
|
[
"MIT"
] | null | null | null |
test/ex_oauth2_provider/oauth2/utils/device_flow_test.exs
|
heroinbob/ex_oauth2_provider
|
80c21a53bba0955ab3b66f1bd32cc81db0f04f49
|
[
"MIT"
] | null | null | null |
test/ex_oauth2_provider/oauth2/utils/device_flow_test.exs
|
heroinbob/ex_oauth2_provider
|
80c21a53bba0955ab3b66f1bd32cc81db0f04f49
|
[
"MIT"
] | null | null | null |
defmodule ExOauth2Provider.Utils.DeviceFlowTest do
use ExOauth2Provider.TestCase
alias ExOauth2Provider.Utils.DeviceFlow
describe "#generate_device_code/1" do
test "returns a unique 32 char string that's base64 encoded and url safe" do
expected_length =
"01234567890123456789012345678912"
|> Base.url_encode64()
|> String.length()
codes = Enum.map(1..10, fn _n -> DeviceFlow.generate_device_code() end)
num_uniq_codes =
codes
|> Enum.uniq()
|> Enum.count()
assert num_uniq_codes == 10
assert Enum.all?(
codes,
fn code ->
assert code =~ ~r/[a-z0-9=_-]{#{expected_length}}/i
end
)
end
test "uses the length in the config when defined" do
code =
DeviceFlow.generate_device_code(
otp_app: :ex_oauth2_provider,
device_flow_device_code_length: 10
)
expected_length =
"0123456789"
|> Base.url_encode64()
|> String.length()
assert String.length(code) == expected_length
end
end
describe "#generate_user_code/1" do
test "returns a unique 8 char alpha-numeric string" do
codes = Enum.map(1..10, fn _n -> DeviceFlow.generate_user_code() end)
num_uniq_codes =
codes
|> Enum.uniq()
|> Enum.count()
assert num_uniq_codes == 10
assert Enum.all?(
codes,
fn code ->
assert code =~ ~r/[a-z0-9]{8}/i
end
)
end
test "returns a code the same length as device_flow_device_code_length when given" do
code =
DeviceFlow.generate_user_code(
otp_app: :ex_oauth2_provider,
device_flow_user_code_length: 4
)
assert String.length(code) == 4
end
test "returns a code using the value of device_flow_user_code_base when given" do
code =
DeviceFlow.generate_user_code(
otp_app: :ex_oauth2_provider,
device_flow_user_code_base: 2
)
assert code =~ ~r/[01]{8}/
end
end
end
| 25.05814 | 89 | 0.585151 |
73715e35cd32e7131a14d74ee740b2ee6c5b3968
| 880 |
exs
|
Elixir
|
test/json_api_client/middleware/factory_test.exs
|
jmax/json_api_client
|
10518564077860c291008887639dcef13f9ac3a7
|
[
"MIT"
] | 36 |
2017-10-06T17:58:27.000Z
|
2022-01-07T13:52:50.000Z
|
test/json_api_client/middleware/factory_test.exs
|
jmax/json_api_client
|
10518564077860c291008887639dcef13f9ac3a7
|
[
"MIT"
] | 12 |
2017-11-30T00:17:05.000Z
|
2019-11-25T18:05:24.000Z
|
test/json_api_client/middleware/factory_test.exs
|
jmax/json_api_client
|
10518564077860c291008887639dcef13f9ac3a7
|
[
"MIT"
] | 12 |
2017-12-03T21:14:55.000Z
|
2020-09-08T23:43:33.000Z
|
defmodule JsonApiClient.Middleware.FactoryTest do
use ExUnit.Case
doctest JsonApiClient.Middleware.Factory, import: true
alias JsonApiClient.Middleware.Factory
test "includes configured Middleware (DefaultRequestConfig, DocumentParser and HTTPClient Middleware are the last)" do
middlewares = Application.get_env(:json_api_client, :middlewares, [])
configured = {JsonApiClient.Middleware.Fuse, [{:opts, {{:standard, 2, 10_000}, {:reset, 60_000}}}]}
Application.put_env(:json_api_client, :middlewares, [configured])
assert Factory.middlewares() == [
configured,
{JsonApiClient.Middleware.DefaultRequestConfig, nil},
{JsonApiClient.Middleware.DocumentParser, nil},
{JsonApiClient.Middleware.HTTPClient, nil}
]
Mix.Config.persist(json_api_client: [middlewares: [middlewares]])
end
end
| 38.26087 | 120 | 0.718182 |
7371609b97cd046767ff0b318bad58f48b281f2d
| 385 |
ex
|
Elixir
|
kousa/lib/beef/queries/user_blocks.ex
|
lazarospsa/dogehouse
|
4400518f5b6bce929e40eada615356e8814a8d28
|
[
"MIT"
] | 2 |
2021-05-01T16:57:50.000Z
|
2021-07-07T22:01:14.000Z
|
kousa/lib/beef/queries/user_blocks.ex
|
lazarospsa/dogehouse
|
4400518f5b6bce929e40eada615356e8814a8d28
|
[
"MIT"
] | 2 |
2022-02-15T04:33:25.000Z
|
2022-02-28T01:39:56.000Z
|
kousa/lib/beef/queries/user_blocks.ex
|
lazarospsa/dogehouse
|
4400518f5b6bce929e40eada615356e8814a8d28
|
[
"MIT"
] | 1 |
2021-03-19T13:04:24.000Z
|
2021-03-19T13:04:24.000Z
|
defmodule Beef.Queries.UserBlocks do
@moduledoc """
Query builder functions for UserBlocks
"""
import Ecto.Query, warn: false
alias Beef.Schemas.UserBlock
def start do
from(ub in UserBlock)
end
def filter_by_id_and_blockedId(query, user_id, user_id_blockedId) do
where(query, [ub], ub.userId == ^user_id and ub.userIdBlocked == ^user_id_blockedId)
end
end
| 22.647059 | 88 | 0.732468 |
7371672725a51613596fde2495598d94f7afa6c3
| 36,920 |
ex
|
Elixir
|
lib/iex/lib/iex/helpers.ex
|
fmterrorf/elixir
|
eafb7b87756179adac5dc2bc11edcb04c1f187cc
|
[
"Apache-2.0"
] | 1 |
2019-06-27T08:47:13.000Z
|
2019-06-27T08:47:13.000Z
|
lib/iex/lib/iex/helpers.ex
|
fmterrorf/elixir
|
eafb7b87756179adac5dc2bc11edcb04c1f187cc
|
[
"Apache-2.0"
] | null | null | null |
lib/iex/lib/iex/helpers.ex
|
fmterrorf/elixir
|
eafb7b87756179adac5dc2bc11edcb04c1f187cc
|
[
"Apache-2.0"
] | null | null | null |
defmodule IEx.Helpers do
@moduledoc """
Welcome to Interactive Elixir. You are currently
seeing the documentation for the module `IEx.Helpers`
which provides many helpers to make Elixir's shell
more joyful to work with.
This message was triggered by invoking the helper `h()`,
usually referred to as `h/0` (since it expects 0 arguments).
You can use the `h/1` function to invoke the documentation
for any Elixir module or function:
iex> h(Enum)
iex> h(Enum.map)
iex> h(Enum.reverse/1)
You can also use the `i/1` function to introspect any value
you have in the shell:
iex> i("hello")
There are many other helpers available, here are some examples:
* `b/1` - prints callbacks info and docs for a given module
* `c/1` - compiles a file
* `c/2` - compiles a file and writes bytecode to the given path
* `cd/1` - changes the current directory
* `clear/0` - clears the screen
* `exports/1` - shows all exports (functions + macros) in a module
* `flush/0` - flushes all messages sent to the shell
* `h/0` - prints this help message
* `h/1` - prints help for the given module, function or macro
* `i/0` - prints information about the last value
* `i/1` - prints information about the given term
* `ls/0` - lists the contents of the current directory
* `ls/1` - lists the contents of the specified directory
* `open/1` - opens the source for the given module or function in your editor
* `pid/1` - creates a PID from a string
* `pid/3` - creates a PID with the 3 integer arguments passed
* `port/1` - creates a port from a string
* `port/2` - creates a port with the 2 non-negative integers passed
* `pwd/0` - prints the current working directory
* `r/1` - recompiles the given module's source file
* `recompile/0` - recompiles the current project
* `ref/1` - creates a reference from a string
* `ref/4` - creates a reference with the 4 integer arguments passed
* `runtime_info/0` - prints runtime info (versions, memory usage, stats)
* `t/1` - prints the types for the given module or function
* `v/0` - retrieves the last value from the history
* `v/1` - retrieves the nth value from the history
Help for all of those functions can be consulted directly from
the command line using the `h/1` helper itself. Try:
iex> h(v/0)
To list all IEx helpers available, which is effectively all
exports (functions and macros) in the `IEx.Helpers` module:
iex> exports(IEx.Helpers)
This module also includes helpers for debugging purposes, see
`IEx.break!/4` for more information.
To learn more about IEx as a whole, type `h(IEx)`.
"""
import IEx, only: [dont_display_result: 0]
@doc """
Recompiles the current Mix application.
This helper only works when IEx is started with a Mix
project, for example, `iex -S mix`. Note this function
simply recompiles Elixir modules, without reloading
configuration and without restarting applications.
Therefore, any long running process may crash on recompilation,
as changed modules will be temporarily removed and recompiled,
without going through the proper code change callback.
If you want to reload a single module, consider using
`r(ModuleName)` instead.
This function is meant to be used for development and
debugging purposes. Do not depend on it in production code.
## Options
* `:force` - when `true`, forces the application to recompile
"""
def recompile(options \\ []) do
if mix_started?() do
config = Mix.Project.config()
consolidation = Mix.Project.consolidation_path(config)
reenable_tasks(config)
# No longer allow consolidations to be accessed.
Code.delete_path(consolidation)
purge_protocols(consolidation)
force? = Keyword.get(options, :force, false)
arguments = if force?, do: ["--force"], else: []
{result, _} = Mix.Task.run("compile", arguments)
# Re-enable consolidation and allow them to be loaded.
Code.prepend_path(consolidation)
purge_protocols(consolidation)
result
else
IO.puts(IEx.color(:eval_error, "Mix is not running. Please start IEx with: iex -S mix"))
:error
end
end
defp mix_started? do
List.keyfind(Application.started_applications(), :mix, 0) != nil
end
defp reenable_tasks(config) do
Mix.Task.reenable("compile")
Mix.Task.reenable("compile.all")
Mix.Task.reenable("compile.protocols")
compilers = config[:compilers] || Mix.compilers()
Enum.each(compilers, &Mix.Task.reenable("compile.#{&1}"))
end
defp purge_protocols(path) do
case File.ls(path) do
{:ok, beams} ->
Enum.each(beams, fn beam ->
module = beam |> Path.rootname() |> String.to_atom()
:code.purge(module)
:code.delete(module)
end)
{:error, _} ->
:ok
end
end
@doc """
Compiles the given files.
It expects a list of files to compile and an optional path to write
the compiled code to. By default files are in-memory compiled.
To write compiled files to the current directory, an empty string
can be given.
It returns the names of the compiled modules.
If you want to recompile an existing module, check `r/1` instead.
## Examples
In the example below, we pass a directory to where the `c/2` function will
write the compiled `.beam` files to. This directory is typically named "ebin"
in Erlang/Elixir systems:
iex> c(["foo.ex", "bar.ex"], "ebin")
[Foo, Bar]
When compiling one file, there is no need to wrap it in a list:
iex> c("baz.ex")
[Baz]
"""
def c(files, path \\ :in_memory) when is_binary(path) or path == :in_memory do
files = List.wrap(files)
unless Enum.all?(files, &is_binary/1) do
raise ArgumentError, "expected a binary or a list of binaries as argument"
end
{found, not_found} = Enum.split_with(files, &File.exists?/1)
unless Enum.empty?(not_found) do
raise ArgumentError, "could not find files #{Enum.join(not_found, ", ")}"
end
{erls, exs} = Enum.split_with(found, &String.ends_with?(&1, ".erl"))
erl_modules =
Enum.map(erls, fn source ->
{module, binary} = compile_erlang(source)
if path != :in_memory do
base = source |> Path.basename() |> Path.rootname()
File.write!(Path.join(path, base <> ".beam"), binary)
end
module
end)
ex_modules =
case compile_elixir(exs, path) do
{:ok, modules, _} -> modules
{:error, _, _} -> raise CompileError
end
erl_modules ++ ex_modules
end
@doc """
Clears the console screen.
This function only works if ANSI escape codes are enabled
on the shell, which means this function is by default
unavailable on Windows machines.
"""
def clear() do
if IO.ANSI.enabled?() do
IO.write([IO.ANSI.home(), IO.ANSI.clear()])
else
IO.puts("Cannot clear the screen because ANSI escape codes are not enabled on this shell")
end
dont_display_result()
end
@doc """
Opens the current prying location.
This command only works inside a pry session started manually
via `IEx.pry/0` or a breakpoint set via `IEx.break!/4`. Calling
this function during a regular `IEx` session will print an error.
Keep in mind the `open/0` location may not exist when prying
precompiled source code, such as Elixir itself.
For more information and to open any module or function, see
`open/1`.
"""
def open() do
case Process.get(:iex_whereami) do
{file, line, _} ->
IEx.Introspection.open({file, line})
_ ->
IO.puts(IEx.color(:eval_error, "Pry session is not currently enabled"))
end
dont_display_result()
end
@doc """
Opens the given `module`, `module.function/arity`, or `{file, line}`.
This function uses the `ELIXIR_EDITOR` environment variable
and falls back to `EDITOR` if the former is not available.
By default, it attempts to open the file and line using the
`file:line` notation. For example, if your editor is called
`subl`, it will open the file as:
subl path/to/file:line
It is important that you choose an editor command that does
not block nor that attempts to run an editor directly in the
terminal. Command-line based editors likely need extra
configuration so they open up the given file and line in a
separate window.
Custom editors are supported by using the `__FILE__` and
`__LINE__` notations, for example:
ELIXIR_EDITOR="my_editor +__LINE__ __FILE__"
and Elixir will properly interpolate values.
Since this function prints the result returned by the editor,
`ELIXIR_EDITOR` can be set "echo" if you prefer to display the
location rather than opening it.
Keep in mind the location may not exist when opening precompiled
source code.
## Examples
iex> open(MyApp)
iex> open(MyApp.fun/2)
iex> open({"path/to/file", 1})
"""
defmacro open(term) do
quote do
IEx.Introspection.open(unquote(IEx.Introspection.decompose(term, __CALLER__)))
end
end
@doc """
Prints the documentation for `IEx.Helpers`.
"""
def h() do
IEx.Introspection.h(IEx.Helpers)
end
@doc """
Prints the documentation for the given module
or for the given `function/arity` pair.
## Examples
iex> h(Enum)
It also accepts functions in the format `function/arity`
and `module.function/arity`, for example:
iex> h(receive/1)
iex> h(Enum.all?/2)
iex> h(Enum.all?)
"""
defmacro h(term) do
quote do
IEx.Introspection.h(unquote(IEx.Introspection.decompose(term, __CALLER__)))
end
end
@doc """
Prints the documentation for the given callback function.
It also accepts single module argument to list
all available behaviour callbacks.
## Examples
iex> b(Mix.Task.run/1)
iex> b(Mix.Task.run)
iex> b(GenServer)
"""
defmacro b(term) do
quote do
IEx.Introspection.b(unquote(IEx.Introspection.decompose(term, __CALLER__)))
end
end
@doc """
Prints the types for the given module or for the given function/arity pair.
## Examples
iex> t(Enum)
@type t() :: Enumerable.t()
@type acc() :: any()
@type element() :: any()
@type index() :: integer()
@type default() :: any()
iex> t(Enum.t/0)
@type t() :: Enumerable.t()
iex> t(Enum.t)
@type t() :: Enumerable.t()
"""
defmacro t(term) do
quote do
IEx.Introspection.t(unquote(IEx.Introspection.decompose(term, __CALLER__)))
end
end
@doc """
Returns the value of the `n`th expression in the history.
`n` can be a negative value: if it is, the corresponding expression value
relative to the current one is returned. For example, `v(-2)` returns the
value of the expression evaluated before the last evaluated expression. In
particular, `v(-1)` returns the result of the last evaluated expression and
`v()` does the same.
## Examples
iex(1)> "hello" <> " world"
"hello world"
iex(2)> 40 + 2
42
iex(3)> v(-2)
"hello world"
iex(4)> v(2)
42
iex(5)> v()
42
"""
def v(n \\ -1) do
IEx.History.nth(history(), n) |> elem(1)
end
@doc """
Recompiles and reloads the given `module` or `modules`.
Please note that all the modules defined in the same file as
`modules` are recompiled and reloaded. If you want to reload
multiple modules, it is best to reload them at the same time,
such as in `r [Foo, Bar]`. This is important to avoid false
warnings, since the module is only reloaded in memory and its
latest information is not persisted to disk. See the "In-memory
reloading" section below.
This function is meant to be used for development and
debugging purposes. Do not depend on it in production code.
## In-memory reloading
When we reload the module in IEx, we recompile the module source
code, updating its contents in memory. The original `.beam` file
in disk, probably the one where the first definition of the module
came from, does not change at all.
Since docs, typespecs, and exports information are loaded from the
.beam file, they are not reloaded when you invoke this function.
"""
def r(module_or_modules) do
modules = List.wrap(module_or_modules)
sources =
Enum.map(modules, fn module ->
unless Code.ensure_loaded?(module) do
raise ArgumentError, "could not load nor find module: #{inspect(module)}"
end
source = source(module)
cond do
source == nil ->
raise ArgumentError, "could not find source for module: #{inspect(module)}"
not File.exists?(source) ->
raise ArgumentError,
"could not find source (#{source}) for module: #{inspect(module)}"
true ->
source
end
end)
{erlang, elixir} = Enum.split_with(sources, &String.ends_with?(&1, ".erl"))
erlang =
for source <- erlang do
compile_erlang(source) |> elem(0)
end
elixir =
if elixir != [] do
{:ok, modules, _warning} = Kernel.ParallelCompiler.compile(elixir)
modules
else
[]
end
{:reloaded, erlang ++ elixir}
end
@doc """
Loads the given module's BEAM code (and ensures any previous
old version was properly purged before).
This function is useful when you know the bytecode for module
has been updated in the file system and you want to tell the VM
to load it.
"""
def l(module) when is_atom(module) do
:code.purge(module)
:code.load_file(module)
end
@doc """
Prints information about the data type of any given term.
If no argument is given, the value of the previous expression
is used.
## Examples
iex> i(1..5)
Will print:
Term
1..5
Data type
Range
Description
This is a struct. Structs are maps with a __struct__ key.
Reference modules
Range, Map
"""
def i(term \\ v(-1)) do
implemented_protocols = [{"Implemented protocols", all_implemented_protocols_for_term(term)}]
info = [{"Term", inspect(term)}] ++ IEx.Info.info(term) ++ implemented_protocols
for {subject, info} <- info do
info = info |> to_string() |> String.trim() |> String.replace("\n", "\n ")
IO.puts(IEx.color(:eval_result, to_string(subject)))
IO.puts(IEx.color(:eval_info, " #{info}"))
end
dont_display_result()
end
# Given any "term", this function returns all the protocols in
# :code.get_path() implemented by the data structure of such term, in the form
# of a binary like "Protocol1, Protocol2, Protocol3".
defp all_implemented_protocols_for_term(term) do
:code.get_path()
|> Protocol.extract_protocols()
|> Enum.uniq()
|> Enum.reject(fn protocol -> is_nil(protocol.impl_for(term)) end)
|> Enum.sort()
|> Enum.map_join(", ", &inspect/1)
end
@runtime_info_topics [:system, :memory, :limits, :applications]
@doc """
Prints VM/runtime information such as versions, memory usage and statistics.
Additional topics are available via `runtime_info/1`.
For more metrics, info, and debugging facilities, see the
[Recon](https://github.com/ferd/recon) project.
"""
@doc since: "1.5.0"
def runtime_info(), do: runtime_info([:system, :memory, :limits])
@doc """
Just like `runtime_info/0`, except accepts topic or a list of topics.
For example, topic `:applications` will list the applications loaded.
"""
@doc since: "1.5.0"
def runtime_info(topic) when is_atom(topic) and topic in @runtime_info_topics do
topic
|> List.wrap()
|> runtime_info
end
def runtime_info(topics) when is_list(topics) do
topics
|> Enum.uniq()
|> print_runtime_info
end
defp print_runtime_info(topics) do
Enum.each(topics, &print_runtime_info_topic/1)
IO.puts("")
print_topic_info(topics)
IO.puts("")
dont_display_result()
end
defp print_topic_info(topics) when is_list(topics) do
IO.write(pad_key("Showing topics"))
IO.puts(inspect(topics))
IO.write(pad_key("Additional topics"))
IO.puts(inspect(@runtime_info_topics -- topics))
IO.puts("")
IO.puts("To view a specific topic call runtime_info(topic)")
end
defp print_runtime_info_topic(:system) do
print_pane("System and architecture")
print_entry("Elixir version", System.version())
print_entry("Erlang/OTP version", System.otp_release())
print_entry("ERTS version", :erlang.system_info(:version))
print_entry("Compiled for", :erlang.system_info(:system_architecture))
print_entry("Schedulers", :erlang.system_info(:schedulers))
print_entry("Schedulers online", :erlang.system_info(:schedulers_online))
end
defp print_runtime_info_topic(:memory) do
print_pane("Memory")
print_memory("Total", :total)
print_memory("Atoms", :atom)
print_memory("Binaries", :binary)
print_memory("Code", :code)
print_memory("ETS", :ets)
print_memory("Processes", :processes)
end
defp print_runtime_info_topic(:limits) do
print_pane("Statistics / limits")
print_uptime()
print_entry("Run queue", :erlang.statistics(:run_queue))
print_percentage("Atoms", :atom_count, :atom_limit)
print_percentage("ETS", :ets_count, :ets_limit)
print_percentage("Ports", :port_count, :port_limit)
print_percentage("Processes", :process_count, :process_limit)
end
defp print_runtime_info_topic(:applications) do
print_pane("Loaded OTP Applications")
started = Application.started_applications()
loaded = Application.loaded_applications()
for {app, _, version} = entry <- Enum.sort(loaded) do
IO.write(pad_key(app))
IO.write(String.pad_trailing("#{version}", 20))
if entry in started do
IO.write("(started)")
end
IO.puts("")
end
:ok
end
defp print_pane(msg) do
IO.puts(IEx.color(:eval_result, ["\n## ", msg, " \n"]))
end
defp print_entry(_key, nil), do: :ok
defp print_entry(key, value), do: IO.puts("#{pad_key(key)}#{value}")
defp print_uptime() do
IO.write(pad_key("Uptime"))
:c.uptime()
end
defp print_percentage(key, min, max) do
min = get_stat(min)
max = get_stat(max)
percentage = trunc(min / max * 100)
IO.puts("#{pad_key(key)}#{min} / #{max} (#{percentage}% used)")
end
defp get_stat(:ets_count), do: :erlang.system_info(:ets_count)
defp get_stat(other), do: :erlang.system_info(other)
defp print_memory(key, memory) do
value = :erlang.memory(memory)
IO.puts("#{pad_key(key)}#{format_bytes(value)}")
end
defp format_bytes(bytes) when is_integer(bytes) do
cond do
bytes >= memory_unit(:GB) -> format_bytes(bytes, :GB)
bytes >= memory_unit(:MB) -> format_bytes(bytes, :MB)
bytes >= memory_unit(:KB) -> format_bytes(bytes, :KB)
true -> format_bytes(bytes, :B)
end
end
defp format_bytes(bytes, unit) when is_integer(bytes) and unit in [:GB, :MB, :KB] do
value =
bytes
|> div(memory_unit(unit))
|> round()
"#{value} #{unit}"
end
defp format_bytes(bytes, :B) when is_integer(bytes), do: "#{bytes} B"
defp memory_unit(:GB), do: 1024 * 1024 * 1024
defp memory_unit(:MB), do: 1024 * 1024
defp memory_unit(:KB), do: 1024
defp pad_key(key), do: String.pad_trailing("#{key}:", 20, " ")
@doc """
Clears out all messages sent to the shell's inbox and prints them out.
"""
def flush do
do_flush(IEx.inspect_opts())
end
defp do_flush(inspect_opts) do
receive do
msg ->
IO.inspect(msg, inspect_opts)
do_flush(inspect_opts)
after
0 -> :ok
end
end
defp source(module) do
source = module.module_info(:compile)[:source]
case source do
nil -> nil
source -> List.to_string(source)
end
end
@doc """
Prints the current working directory.
"""
def pwd do
IO.puts(IEx.color(:eval_info, File.cwd!()))
dont_display_result()
end
@doc """
Changes the current working directory to the given path.
"""
def cd(directory) when is_binary(directory) do
case File.cd(expand_home(directory)) do
:ok ->
pwd()
{:error, :enoent} ->
IO.puts(IEx.color(:eval_error, "No directory #{directory}"))
end
dont_display_result()
end
@doc """
Prints a list of all the functions and macros exported by the given module.
"""
@doc since: "1.5.0"
def exports(module \\ Kernel) do
exports = IEx.Autocomplete.exports(module)
list =
Enum.map(exports, fn {name, arity} ->
Atom.to_string(name) <> "/" <> Integer.to_string(arity)
end)
print_table(list)
dont_display_result()
end
@doc """
Prints a list of the given directory's contents.
If `path` points to a file, prints its full path.
"""
def ls(path \\ ".") when is_binary(path) do
path = expand_home(path)
case File.ls(path) do
{:ok, items} ->
sorted_items = Enum.sort(items)
printer = fn item, width ->
format_item(Path.join(path, item), String.pad_trailing(item, width))
end
print_table(sorted_items, printer)
{:error, :enoent} ->
IO.puts(IEx.color(:eval_error, "No such file or directory #{path}"))
{:error, :enotdir} ->
IO.puts(IEx.color(:eval_info, Path.absname(path)))
end
dont_display_result()
end
defp expand_home(<<?~, rest::binary>>) do
System.user_home!() <> rest
end
defp expand_home(other), do: other
defp print_table(list, printer \\ &String.pad_trailing/2)
defp print_table([], _printer) do
:ok
end
defp print_table(list, printer) do
# print items in multiple columns (2 columns in the worst case)
lengths = Enum.map(list, &String.length(&1))
max_length = max_length(lengths)
offset = min(max_length, 30) + 5
print_table(list, printer, offset)
end
defp print_table(list, printer, offset) do
Enum.reduce(list, 0, fn item, length ->
length =
if length >= 80 do
IO.puts("")
0
else
length
end
IO.write(printer.(item, offset))
length + offset
end)
IO.puts("")
end
defp max_length(list) do
Enum.reduce(list, 0, &max(&1, &2))
end
defp format_item(path, representation) do
case File.stat(path) do
{:ok, %File.Stat{type: :device}} ->
IEx.color(:ls_device, representation)
{:ok, %File.Stat{type: :directory}} ->
IEx.color(:ls_directory, representation)
_ ->
representation
end
end
@doc """
Respawns the current shell by starting a new shell process.
"""
def respawn do
if iex_server = Process.get(:iex_server) do
send(iex_server, {:respawn, self()})
end
dont_display_result()
end
@doc """
Continues execution of the current process.
This is usually called by sessions started with `IEx.pry/0`
or `IEx.break!/4`. This allows the current process to execute
until the next breakpoint, which will automatically yield control
back to IEx without requesting permission to pry.
If the running process terminates, a new IEx session is
started.
While the process executes, the user will no longer have
control of the shell. If you would rather start a new shell,
use `respawn/0` instead.
"""
@doc since: "1.5.0"
def continue do
if iex_server = Process.get(:iex_server) do
send(iex_server, {:continue, self()})
end
dont_display_result()
end
@doc """
Macro-based shortcut for `IEx.break!/4`.
"""
@doc since: "1.5.0"
defmacro break!(ast, stops \\ 1) do
quote do
require IEx
IEx.break!(unquote(ast), unquote(stops))
end
end
@doc """
Sets up a breakpoint in `module`, `function` and `arity`
with the given number of `stops`.
See `IEx.break!/4` for a complete description of breakpoints
in IEx.
"""
@doc since: "1.5.0"
defdelegate break!(module, function, arity, stops \\ 1), to: IEx
@doc """
Prints all breakpoints to the terminal.
"""
@doc since: "1.5.0"
def breaks do
breaks(IEx.Pry.breaks())
end
defp breaks([]) do
IO.puts(IEx.color(:eval_info, "No breakpoints set"))
dont_display_result()
end
defp breaks(breaks) do
entries =
for {id, module, {function, arity}, stops} <- breaks do
{
Integer.to_string(id),
Exception.format_mfa(module, function, arity),
Integer.to_string(stops)
}
end
entries = [{"ID", "Module.function/arity", "Pending stops"} | entries]
{id_max, mfa_max, stops_max} =
Enum.reduce(entries, {0, 0, 0}, fn {id, mfa, stops}, {id_max, mfa_max, stops_max} ->
{
max(byte_size(id), id_max),
max(byte_size(mfa), mfa_max),
max(byte_size(stops), stops_max)
}
end)
[header | entries] = entries
IO.puts("")
print_break(header, id_max, mfa_max)
IO.puts([
String.duplicate("-", id_max + 2),
?\s,
String.duplicate("-", mfa_max + 2),
?\s,
String.duplicate("-", stops_max + 2)
])
Enum.each(entries, &print_break(&1, id_max, mfa_max))
IO.puts("")
dont_display_result()
end
defp print_break({id, mfa, stops}, id_max, mfa_max) do
IO.puts([
?\s,
String.pad_trailing(id, id_max + 2),
?\s,
String.pad_trailing(mfa, mfa_max + 2),
?\s,
stops
])
end
@doc """
Sets the number of pending stops in the breakpoint
with the given `id` to zero.
Returns `:ok` if there is such breakpoint ID. `:not_found`
otherwise.
Note the module remains "instrumented" on reset. If you would
like to effectively remove all breakpoints and instrumentation
code from a module, use `remove_breaks/1` instead.
"""
@doc since: "1.5.0"
defdelegate reset_break(id), to: IEx.Pry
@doc """
Sets the number of pending stops in the given module,
function and arity to zero.
If the module is not instrumented or if the given function
does not have a breakpoint, it is a no-op and it returns
`:not_found`. Otherwise it returns `:ok`.
Note the module remains "instrumented" on reset. If you would
like to effectively remove all breakpoints and instrumentation
code from a module, use `remove_breaks/1` instead.
"""
@doc since: "1.5.0"
defdelegate reset_break(module, function, arity), to: IEx.Pry
@doc """
Removes all breakpoints and instrumentation from `module`.
"""
@doc since: "1.5.0"
defdelegate remove_breaks(module), to: IEx.Pry
@doc """
Removes all breakpoints and instrumentation from all modules.
"""
@doc since: "1.5.0"
defdelegate remove_breaks(), to: IEx.Pry
@doc """
Prints the current location and stacktrace in a pry session.
It expects a `radius` which chooses how many lines before and after
the current line we should print. By default the `radius` is of two
lines:
Location: lib/iex/lib/iex/helpers.ex:79
77:
78: def recompile do
79: require IEx; IEx.pry()
80: if mix_started?() do
81: config = Mix.Project.config
(IEx.Helpers) lib/iex/lib/iex/helpers.ex:78: IEx.Helpers.recompile/0
This command only works inside a pry session started manually
via `IEx.pry/0` or a breakpoint set via `IEx.break!/4`. Calling
this function during a regular `IEx` session will print an error.
Keep in mind the `whereami/1` location may not exist when prying
precompiled source code, such as Elixir itself.
"""
@doc since: "1.5.0"
def whereami(radius \\ 2) do
case Process.get(:iex_whereami) do
{file, line, stacktrace} ->
msg = ["Location: ", Path.relative_to_cwd(file), ":", Integer.to_string(line)]
IO.puts(IEx.color(:eval_info, msg))
case IEx.Pry.whereami(file, line, radius) do
{:ok, lines} ->
IO.write([?\n, lines, ?\n])
:error ->
msg = "Could not extract source snippet. Location is not available."
IO.puts(IEx.color(:eval_error, msg))
end
case stacktrace do
nil -> :ok
stacktrace -> IO.write([Exception.format_stacktrace(stacktrace), ?\n])
end
_ ->
IO.puts(IEx.color(:eval_error, "Pry session is not currently enabled"))
end
dont_display_result()
end
@doc """
Similar to `import_file` but only imports the file if it is available.
By default, `import_file/1` fails when the given file does not exist.
However, since `import_file/1` is expanded at compile-time, it's not
possible to conditionally import a file since the macro is always
expanded:
# This raises a File.Error if ~/.iex.exs doesn't exist.
if "~/.iex.exs" |> Path.expand() |> File.exists?() do
import_file("~/.iex.exs")
end
This macro addresses this issue by checking if the file exists or not
in behalf of the user.
"""
defmacro import_file_if_available(path) when is_binary(path) do
import_file_if_available(path, true)
end
defmacro import_file_if_available(_) do
raise ArgumentError, "import_file_if_available/1 expects a literal binary as its argument"
end
defp import_file_if_available(path, optional?) when is_binary(path) do
path = Path.expand(path)
if not optional? or File.exists?(path) do
if imported_paths = Process.get(:iex_imported_paths) do
if path in imported_paths do
IO.warn("path #{path} was already imported, skipping circular file imports", [])
else
Process.put(:iex_imported_paths, MapSet.put(imported_paths, path))
path |> File.read!() |> Code.string_to_quoted!(file: path)
end
else
path |> File.read!() |> Code.string_to_quoted!(file: path)
end
end
end
@doc """
Injects the contents of the file at `path` as if it was typed into
the shell.
This would be the equivalent of getting all of the file contents and
packing it all into a single line in IEx and executing it.
By default, the contents of a `.iex.exs` file in the same directory
as you are starting IEx are automatically imported. See the section
for ".iex.exs" in the `IEx` module docs for more information.
`path` has to be a literal string and is automatically expanded via
`Path.expand/1`.
## Examples
# ~/file.exs
value = 13
# in the shell
iex(1)> import_file("~/file.exs")
13
iex(2)> value
13
"""
@doc since: "1.4.0"
defmacro import_file(path) when is_binary(path) do
import_file_if_available(path, false)
end
defmacro import_file(_) do
raise ArgumentError, "import_file/1 expects a literal binary as its argument"
end
@doc false
@deprecated "Use import_file_if_available/1 instead"
defmacro import_file(path, opts) when is_binary(path) and is_list(opts) do
import_file_if_available(path, Keyword.get(opts, :optional, false))
end
@doc """
Calls `import/2` with the given arguments, but only if the module is available.
This lets you put imports in `.iex.exs` files (including `~/.iex.exs`) without
getting compile errors if you open a console where the module is not available.
## Example
# In ~/.iex.exs
import_if_available(Ecto.Query)
"""
defmacro import_if_available(quoted_module, opts \\ []) do
module = Macro.expand(quoted_module, __CALLER__)
if Code.ensure_loaded?(module) do
quote do
import unquote(quoted_module), unquote(opts)
end
end
end
@doc """
Calls `use/2` with the given arguments, but only if the module is available.
This lets you use the module in `.iex.exs` files (including `~/.iex.exs`) without
getting compile errors if you open a console where the module is not available.
## Example
# In ~/.iex.exs
use_if_available(Phoenix.HTML)
"""
@doc since: "1.7.0"
defmacro use_if_available(quoted_module, opts \\ []) do
module = Macro.expand(quoted_module, __CALLER__)
if Code.ensure_loaded?(module) do
quote do
use unquote(quoted_module), unquote(opts)
end
end
end
defp compile_elixir(exs, :in_memory), do: Kernel.ParallelCompiler.compile(exs)
defp compile_elixir(exs, path), do: Kernel.ParallelCompiler.compile_to_path(exs, path)
# Compiles and loads an Erlang source file, returns {module, binary}
defp compile_erlang(source) do
source = Path.relative_to_cwd(source) |> String.to_charlist()
case :compile.file(source, [:binary, :report]) do
{:ok, module, binary} ->
:code.purge(module)
{:module, module} = :code.load_binary(module, source, binary)
{module, binary}
_ ->
raise CompileError
end
end
defp history, do: Process.get(:iex_history)
@doc """
Creates a PID from `string` or `atom`.
## Examples
iex> pid("0.21.32")
#PID<0.21.32>
iex> pid(:init)
#PID<0.0.0>
"""
def pid(string) when is_binary(string) do
:erlang.list_to_pid('<#{string}>')
end
def pid(name) when is_atom(name) do
case Process.whereis(name) do
p when is_pid(p) -> p
_ -> raise ArgumentError, "could not find registered process with name: #{inspect(name)}"
end
end
@doc """
Creates a PID with 3 non-negative integers passed as arguments
to the function.
## Examples
iex> pid(0, 21, 32)
#PID<0.21.32>
iex> pid(0, 64, 2048)
#PID<0.64.2048>
"""
def pid(x, y, z)
when is_integer(x) and x >= 0 and is_integer(y) and y >= 0 and is_integer(z) and z >= 0 do
:erlang.list_to_pid(
'<' ++
Integer.to_charlist(x) ++
'.' ++ Integer.to_charlist(y) ++ '.' ++ Integer.to_charlist(z) ++ '>'
)
end
@doc """
Creates a Port from `string`.
## Examples
iex> port("0.4")
#Port<0.4>
"""
@doc since: "1.8.0"
def port(string) when is_binary(string) do
:erlang.list_to_port('#Port<#{string}>')
end
@doc """
Creates a Port from two non-negative integers.
## Examples
iex> port(0, 8080)
#Port<0.8080>
iex> port(0, 443)
#Port<0.443>
"""
@doc since: "1.8.0"
def port(major, minor)
when is_integer(major) and major >= 0 and is_integer(minor) and minor >= 0 do
:erlang.list_to_port(
'#Port<' ++ Integer.to_charlist(major) ++ '.' ++ Integer.to_charlist(minor) ++ '>'
)
end
@doc """
Creates a Reference from `string`.
## Examples
iex> ref("0.1.2.3")
#Reference<0.1.2.3>
"""
@doc since: "1.6.0"
def ref(string) when is_binary(string) do
:erlang.list_to_ref('#Ref<#{string}>')
end
@doc """
Creates a Reference from its 4 non-negative integers components.
## Examples
iex> ref(0, 1, 2, 3)
#Reference<0.1.2.3>
"""
@doc since: "1.6.0"
def ref(w, x, y, z)
when is_integer(w) and w >= 0 and is_integer(x) and x >= 0 and is_integer(y) and y >= 0 and
is_integer(z) and z >= 0 do
:erlang.list_to_ref(
'#Ref<' ++
Integer.to_charlist(w) ++
'.' ++
Integer.to_charlist(x) ++
'.' ++ Integer.to_charlist(y) ++ '.' ++ Integer.to_charlist(z) ++ '>'
)
end
@doc """
Deploys a given module's BEAM code to a list of nodes.
This function is useful for development and debugging when you have code that
has been compiled or updated locally that you want to run on other nodes.
The node list defaults to a list of all connected nodes.
Returns `{:error, :nofile}` if the object code (i.e. ".beam" file) for the module
could not be found locally.
## Examples
iex> nl(HelloWorld)
{:ok,
[
{:node1@easthost, :loaded, HelloWorld},
{:node1@westhost, :loaded, HelloWorld}
]}
iex> nl(NoSuchModuleExists)
{:error, :nofile}
"""
def nl(nodes \\ Node.list(), module) when is_list(nodes) and is_atom(module) do
case :code.get_object_code(module) do
{^module, bin, beam_path} ->
results =
for node <- nodes do
case :rpc.call(node, :code, :load_binary, [module, beam_path, bin]) do
{:module, _} -> {node, :loaded, module}
{:badrpc, message} -> {node, :badrpc, message}
{:error, message} -> {node, :error, message}
unexpected -> {node, :error, unexpected}
end
end
{:ok, results}
_otherwise ->
{:error, :nofile}
end
end
end
| 27.614061 | 97 | 0.641278 |
737176f20a04962d90f889bfb05f87b87f7a7076
| 1,002 |
ex
|
Elixir
|
web/models/user.ex
|
hotpyn/phoenix-rumbl
|
548ef0cfcaf166a6affa6e28f1a9238762422f1d
|
[
"MIT"
] | null | null | null |
web/models/user.ex
|
hotpyn/phoenix-rumbl
|
548ef0cfcaf166a6affa6e28f1a9238762422f1d
|
[
"MIT"
] | null | null | null |
web/models/user.ex
|
hotpyn/phoenix-rumbl
|
548ef0cfcaf166a6affa6e28f1a9238762422f1d
|
[
"MIT"
] | null | null | null |
defmodule Hello.User do
use Hello.Web, :model
schema "users" do
field :name, :string, required: true
field :username, :string, required: true
field :password, :string, virtual: true
field :password_hash, :string
has_many :videos, Hello.Video, on_delete: :delete_all
timestamps
end
def changeset(model, params \\ %{}) do
model
|> cast(params, ~w(name username), [])
|> validate_length(:username, min: 1, max: 20)
|> validate_length(:name, min: 1, max: 20)
|> unique_constraint(:username)
end
def registration_changeset(model, params) do
model
|> changeset(params)
|> cast(params, ~w(password), [])
|> validate_length(:password, min: 6, max: 100)
|> put_pass_hash()
end
defp put_pass_hash(changeset) do
case changeset do
%Ecto.Changeset{valid?: true, changes: %{password: pass}} ->
put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(pass))
_ ->
changeset
end
end
end
| 25.692308 | 79 | 0.645709 |
737180bf354e368558bc2ba4a3c1eb37c678d678
| 10,381 |
exs
|
Elixir
|
test/changelog_web/controllers/admin/episode_controller_test.exs
|
gustavoarmoa/changelog.com
|
e898a9979a237ae66962714821ed8633a4966f37
|
[
"MIT"
] | 1 |
2019-11-02T08:32:25.000Z
|
2019-11-02T08:32:25.000Z
|
test/changelog_web/controllers/admin/episode_controller_test.exs
|
sdrees/changelog.com
|
955cdcf93d74991062f19a03e34c9f083ade1705
|
[
"MIT"
] | null | null | null |
test/changelog_web/controllers/admin/episode_controller_test.exs
|
sdrees/changelog.com
|
955cdcf93d74991062f19a03e34c9f083ade1705
|
[
"MIT"
] | null | null | null |
defmodule ChangelogWeb.Admin.EpisodeControllerTest do
use ChangelogWeb.ConnCase
use Bamboo.Test
import Mock
alias Changelog.{Episode, EpisodeGuest, Github, NewsItem, NewsQueue}
@valid_attrs %{title: "The one where we win", slug: "181-win"}
@invalid_attrs %{title: ""}
setup_with_mocks(
[
{Github.Pusher, [], [push: fn _, _ -> {:ok, "success"} end]},
{Github.Puller, [], [update: fn _, _ -> true end]},
{Changelog.Merch, [], [create_discount: fn _, _ -> {:ok, %{code: "yup"}} end]}
],
assigns
) do
assigns
end
@tag :as_admin
test "lists all podcast episodes on index", %{conn: conn} do
p = insert(:podcast)
e1 = insert(:episode, podcast: p)
e2 = insert(:episode)
conn = get(conn, Routes.admin_podcast_episode_path(conn, :index, p.slug))
assert conn.status == 200
assert String.contains?(conn.resp_body, p.name)
assert String.contains?(conn.resp_body, e1.title)
refute String.contains?(conn.resp_body, e2.title)
end
@tag :as_admin
test "shows episode details on show", %{conn: conn} do
p = insert(:podcast)
e = insert(:episode, podcast: p)
insert(:episode_stat, episode: e, date: ~D[2016-01-01], downloads: 1.6, uniques: 1)
insert(:episode_stat, episode: e, date: ~D[2016-01-02], downloads: 320, uniques: 345)
conn = get(conn, Routes.admin_podcast_episode_path(conn, :show, p.slug, e.slug))
assert conn.status == 200
assert String.contains?(conn.resp_body, e.slug)
assert String.contains?(conn.resp_body, "2")
assert String.contains?(conn.resp_body, "320")
end
@tag :as_admin
test "renders form to create new podcast episode", %{conn: conn} do
p = insert(:podcast)
conn = get(conn, Routes.admin_podcast_episode_path(conn, :new, p.slug))
assert html_response(conn, 200) =~ ~r/new episode/i
end
@tag :as_admin
test "creates episode and redirects", %{conn: conn} do
p = insert(:podcast)
conn =
post(conn, Routes.admin_podcast_episode_path(conn, :create, p.slug), episode: @valid_attrs)
e = Repo.one(Episode)
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :edit, p.slug, e.slug)
assert count(Episode) == 1
end
@tag :as_admin
test "does not create with invalid attributes", %{conn: conn} do
p = insert(:podcast)
count_before = count(Episode)
conn =
post(conn, Routes.admin_podcast_episode_path(conn, :create, p.slug), episode: @invalid_attrs)
assert html_response(conn, 200) =~ ~r/error/
assert count(Episode) == count_before
end
@tag :as_admin
test "renders form to edit episode", %{conn: conn} do
p = insert(:podcast)
e = insert(:episode, podcast: p)
conn = get(conn, Routes.admin_podcast_episode_path(conn, :edit, p.slug, e.slug))
assert html_response(conn, 200) =~ ~r/edit/i
end
@tag :as_admin
test "updates an episode and redirects", %{conn: conn} do
p = insert(:podcast)
e = insert(:episode, podcast: p)
conn =
put(conn, Routes.admin_podcast_episode_path(conn, :update, p.slug, e.slug),
episode: @valid_attrs
)
refute called(Github.Pusher.push())
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode) == 1
end
@tag :as_admin
test "updates a public episode, pushing notes to GitHub", %{conn: conn} do
p = insert(:podcast)
e = insert(:published_episode, podcast: p)
conn =
put(conn, Routes.admin_podcast_episode_path(conn, :update, p.slug, e.slug),
episode: @valid_attrs
)
assert called(Github.Pusher.push(:_, e.notes))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
end
@tag :as_admin
test "does not update with invalid attrs", %{conn: conn} do
p = insert(:podcast)
e = insert(:episode, podcast: p)
conn =
put(conn, Routes.admin_podcast_episode_path(conn, :update, p.slug, e.slug),
episode: @invalid_attrs
)
refute called(Github.Pusher.push())
assert html_response(conn, 200) =~ ~r/error/
end
@tag :as_admin
test "deletes a draft episode and redirects", %{conn: conn} do
p = insert(:podcast)
e = insert(:episode, podcast: p)
conn = delete(conn, Routes.admin_podcast_episode_path(conn, :delete, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode) == 0
end
@tag :as_admin
test "doesn't delete a published episode", %{conn: conn} do
p = insert(:podcast)
e = insert(:published_episode, podcast: p)
assert_raise Ecto.NoResultsError, fn ->
delete(conn, Routes.admin_podcast_episode_path(conn, :delete, p.slug, e.slug))
end
end
@tag :as_inserted_admin
test "publishes an episode", %{conn: conn} do
p = insert(:podcast)
e = insert(:publishable_episode, podcast: p)
conn = post(conn, Routes.admin_podcast_episode_path(conn, :publish, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 1
assert called(Github.Pusher.push(:_, e.notes))
end
@tag :as_inserted_admin
test "schedules an episode for publishing", %{conn: conn} do
p = insert(:podcast)
e = insert(:publishable_episode, podcast: p, published_at: Timex.end_of_week(Timex.now()))
conn = post(conn, Routes.admin_podcast_episode_path(conn, :publish, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 0
assert count(Episode.scheduled()) == 1
assert called(Github.Pusher.push(:_, e.notes))
end
@tag :as_inserted_admin
test "publishes an episode, optionally setting guest 'thanks' to true", %{conn: conn} do
g1 = insert(:person)
g2 = insert(:person)
p = insert(:podcast)
e = insert(:publishable_episode, podcast: p)
eg1 = insert(:episode_guest, episode: e, person: g1, thanks: false)
eg2 = insert(:episode_guest, episode: e, person: g2, thanks: false)
conn =
post(conn, Routes.admin_podcast_episode_path(conn, :publish, p.slug, e.slug), %{
"thanks" => "true"
})
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 1
assert Repo.get(EpisodeGuest, eg1.id).thanks
assert Repo.get(EpisodeGuest, eg2.id).thanks
assert called(Github.Pusher.push(:_, e.notes))
end
@tag :as_inserted_admin
test "publishes an episode, optionally not setting guest thanks to 'true'", %{conn: conn} do
g1 = insert(:person)
g2 = insert(:person)
p = insert(:podcast)
e = insert(:publishable_episode, podcast: p)
eg1 = insert(:episode_guest, episode: e, person: g1)
eg2 = insert(:episode_guest, episode: e, person: g2)
conn = post(conn, Routes.admin_podcast_episode_path(conn, :publish, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 1
refute Repo.get(EpisodeGuest, eg1.id).thanks
refute Repo.get(EpisodeGuest, eg2.id).thanks
end
@tag :as_inserted_admin
test "publishes an episode, optionally creating a normal news item", %{conn: conn} do
p = insert(:podcast)
e = insert(:publishable_episode, podcast: p)
conn =
post(conn, Routes.admin_podcast_episode_path(conn, :publish, p.slug, e.slug), %{
"news" => "1"
})
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 1
assert count(NewsQueue) == 1
item = NewsItem |> NewsItem.with_episode(e) |> Repo.one()
assert item.headline == e.title
assert item.published_at == e.published_at
end
@tag :as_inserted_admin
test "publishes an episode, optionally creating a feed-only news item", %{conn: conn} do
p = insert(:podcast)
e = insert(:publishable_episode, podcast: p)
conn = post(conn, Routes.admin_podcast_episode_path(conn, :publish, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 1
assert count(NewsItem.feed_only()) == 1
assert count(NewsQueue) == 1
end
@tag :as_admin
test "unpublishes an episode", %{conn: conn} do
p = insert(:podcast)
e = insert(:published_episode, podcast: p)
conn = post(conn, Routes.admin_podcast_episode_path(conn, :unpublish, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert count(Episode.published()) == 0
end
@tag :as_admin
test "fetches and updates transcript", %{conn: conn} do
p = insert(:podcast, name: "Happy Cast", slug: "happy")
e = insert(:published_episode, podcast: p, slug: "12")
conn = post(conn, Routes.admin_podcast_episode_path(conn, :transcript, p.slug, e.slug))
assert redirected_to(conn) == Routes.admin_podcast_episode_path(conn, :index, p.slug)
assert called(Github.Puller.update(:_, :_))
end
test "requires user auth on all actions", %{conn: conn} do
podcast = insert(:podcast)
Enum.each(
[
get(conn, Routes.admin_podcast_episode_path(conn, :index, podcast.slug)),
get(conn, Routes.admin_podcast_episode_path(conn, :new, podcast.slug)),
get(conn, Routes.admin_podcast_episode_path(conn, :show, podcast.slug, "2")),
post(conn, Routes.admin_podcast_episode_path(conn, :create, podcast.slug),
episode: @valid_attrs
),
get(conn, Routes.admin_podcast_episode_path(conn, :edit, podcast.slug, "123")),
put(conn, Routes.admin_podcast_episode_path(conn, :update, podcast.slug, "123"),
episode: @valid_attrs
),
delete(conn, Routes.admin_podcast_episode_path(conn, :delete, podcast.slug, "123")),
post(conn, Routes.admin_podcast_episode_path(conn, :publish, podcast.slug, "123")),
post(conn, Routes.admin_podcast_episode_path(conn, :unpublish, podcast.slug, "123")),
post(conn, Routes.admin_podcast_episode_path(conn, :transcript, podcast.slug, "123"))
],
fn conn ->
assert html_response(conn, 302)
assert conn.halted
end
)
end
end
| 34.488372 | 99 | 0.673057 |
737183b9b185f84eb7ab0883fd841c3a338feadf
| 893 |
ex
|
Elixir
|
lib/hummingbird/telemetry.ex
|
NFIBrokerage/hummingbird
|
ed649bc4f715c6ebb10f7762a013e62c3c8dfdf9
|
[
"Apache-2.0"
] | 3 |
2020-06-04T18:59:51.000Z
|
2022-03-18T12:36:10.000Z
|
lib/hummingbird/telemetry.ex
|
NFIBrokerage/hummingbird
|
ed649bc4f715c6ebb10f7762a013e62c3c8dfdf9
|
[
"Apache-2.0"
] | 14 |
2020-05-15T20:02:17.000Z
|
2021-07-07T20:39:53.000Z
|
lib/hummingbird/telemetry.ex
|
NFIBrokerage/hummingbird
|
ed649bc4f715c6ebb10f7762a013e62c3c8dfdf9
|
[
"Apache-2.0"
] | null | null | null |
defmodule Hummingbird.Telemetry do
@moduledoc """
A handler for telemetry events which captures phoenix endpoint completions
and ships trace information to honeycomb.
Add it to your application children list:
children = [
..
Hummingbird.Telemetry,
..
]
"""
use Task
require Logger
@doc false
def start_link(_args) do
Task.start_link(__MODULE__, :attach, [])
end
@doc false
def attach do
:telemetry.attach(
"hummingbird-phoenix-endpoint-handler",
[:phoenix, :endpoint, :stop],
&handle_event/4,
[]
)
end
@doc false
def handle_event(
[:phoenix, :endpoint, :stop],
%{duration: duration_native},
%{conn: conn},
state
) do
conn
|> Plug.Conn.assign(:request_duration_native, duration_native)
|> Hummingbird.send_spans()
state
end
end
| 18.604167 | 76 | 0.619261 |
7371c32ed9eb6dd20c4b1b4613151f95a449eae6
| 4,165 |
exs
|
Elixir
|
test/hexpm/web/views/package_view_test.exs
|
findmypast/hexfmp
|
38a50f5e1057833fd98748faac230bf4b9cc26a3
|
[
"Apache-2.0"
] | null | null | null |
test/hexpm/web/views/package_view_test.exs
|
findmypast/hexfmp
|
38a50f5e1057833fd98748faac230bf4b9cc26a3
|
[
"Apache-2.0"
] | null | null | null |
test/hexpm/web/views/package_view_test.exs
|
findmypast/hexfmp
|
38a50f5e1057833fd98748faac230bf4b9cc26a3
|
[
"Apache-2.0"
] | null | null | null |
defmodule Hexpm.Web.PackageViewTest do
use Hexpm.ConnCase, async: true
alias Hexpm.Web.PackageView
test "show sort info" do
assert PackageView.show_sort_info("name") == "(Sorted by name)"
assert PackageView.show_sort_info("inserted_at") == "(Sorted by recently created)"
assert PackageView.show_sort_info("updated_at") == "(Sorted by recently updated)"
assert PackageView.show_sort_info("downloads") == "(Sorted by downloads)"
end
test "show sort info when sort param is not available" do
assert PackageView.show_sort_info("some param") == nil
end
test "show sort info when sort param is nil" do
assert PackageView.show_sort_info(nil) == "(Sorted by name)"
end
test "format simple mix dependency snippet" do
version = Version.parse!("1.0.0")
package_name = "ecto"
release = %{meta: %{app: package_name}, version: version}
assert PackageView.dep_snippet(:mix, package_name, release) == "{:ecto, \"~> 1.0\"}"
end
test "format mix dependency snippet" do
version = Version.parse!("1.0.0")
package_name = "timex"
release = %{meta: %{app: "extime"}, version: version}
assert PackageView.dep_snippet(:mix, package_name, release) == "{:extime, \"~> 1.0\", hex: :timex}"
end
test "format simple rebar dependency snippet" do
version = Version.parse!("1.0.0")
package_name = "rebar"
release = %{meta: %{app: package_name}, version: version}
assert PackageView.dep_snippet(:rebar, package_name, release) == "{rebar, \"1.0.0\"}"
end
test "format rebar dependency snippet" do
version = Version.parse!("1.0.1")
package_name = "rebar"
release = %{meta: %{app: "erlang_mk"}, version: version}
assert PackageView.dep_snippet(:rebar, package_name, release) == "{erlang_mk, \"1.0.1\", {pkg, rebar}}"
end
test "format erlang.mk dependency snippet" do
version = Version.parse!("1.0.4")
package_name = "cowboy"
release = %{meta: %{app: package_name}, version: version}
assert PackageView.dep_snippet(:erlang_mk, package_name, release) == "dep_cowboy = hex 1.0.4"
end
test "escape mix application name" do
version = Version.parse!("1.0.0")
package_name = "lfe_app"
release = %{meta: %{app: "lfe-app"}, version: version}
assert PackageView.dep_snippet(:mix, package_name, release) == "{:\"lfe-app\", \"~> 1.0\", hex: :lfe_app}"
end
test "escape rebar application name" do
version = Version.parse!("1.0.1")
package_name = "lfe_app"
release = %{meta: %{app: "lfe-app"}, version: version}
assert PackageView.dep_snippet(:rebar, package_name, release) == "{'lfe-app', \"1.0.1\", {pkg, lfe_app}}"
end
test "mix config version" do
version0 = %Version{major: 0, minor: 0, patch: 1, pre: ["dev", 0, 1]}
version1 = %Version{major: 0, minor: 0, patch: 2, pre: []}
version2 = %Version{major: 0, minor: 2, patch: 99, pre: []}
version3 = %Version{major: 2, minor: 0, patch: 2, pre: []}
assert PackageView.snippet_version(:mix, version0) == "~> 0.0.1-dev.0.1"
assert PackageView.snippet_version(:mix, version1) == "~> 0.0.2"
assert PackageView.snippet_version(:mix, version2) == "~> 0.2.99"
assert PackageView.snippet_version(:mix, version3) == "~> 2.0"
end
test "rebar and erlang.mk config version" do
version0 = %Version{major: 0, minor: 0, patch: 1, pre: ["dev", 0, 1]}
version1 = %Version{major: 0, minor: 0, patch: 2, pre: []}
version2 = %Version{major: 0, minor: 2, patch: 99, pre: []}
version3 = %Version{major: 2, minor: 0, patch: 2, pre: []}
assert PackageView.snippet_version(:rebar, version0) == "0.0.1-dev.0.1"
assert PackageView.snippet_version(:rebar, version1) == "0.0.2"
assert PackageView.snippet_version(:rebar, version2) == "0.2.99"
assert PackageView.snippet_version(:rebar, version3) == "2.0.2"
assert PackageView.snippet_version(:erlang_mk, version0) == "0.0.1-dev.0.1"
assert PackageView.snippet_version(:erlang_mk, version1) == "0.0.2"
assert PackageView.snippet_version(:erlang_mk, version2) == "0.2.99"
assert PackageView.snippet_version(:erlang_mk, version3) == "2.0.2"
end
end
| 41.65 | 110 | 0.659064 |
7371d83427f1ff635bb28d8dae6917fc03810779
| 2,880 |
ex
|
Elixir
|
lib/unbrella/utils.ex
|
smpallen99/unbrella
|
d8d902edd5d68cca46686cc17e435fe9d2bce0da
|
[
"MIT"
] | 9 |
2017-07-09T21:45:56.000Z
|
2020-09-26T04:19:58.000Z
|
lib/unbrella/utils.ex
|
smpallen99/unbrella
|
d8d902edd5d68cca46686cc17e435fe9d2bce0da
|
[
"MIT"
] | null | null | null |
lib/unbrella/utils.ex
|
smpallen99/unbrella
|
d8d902edd5d68cca46686cc17e435fe9d2bce0da
|
[
"MIT"
] | 2 |
2017-09-18T14:38:59.000Z
|
2017-11-27T10:31:36.000Z
|
defmodule Unbrella.Utils do
@moduledoc false
import Mix.Ecto
@doc false
@spec get_modules(atom) :: List.t()
def get_modules(calling_mod) do
get_schemas()
|> Enum.map(fn mod ->
Code.ensure_compiled(mod)
mod
end)
|> Enum.reduce([], fn mod, acc ->
case mod.schema_fields() do
{^calling_mod, entry} -> [entry | acc]
_ -> acc
end
end)
end
@doc false
@spec get_schemas() :: List.t()
def get_schemas do
:unbrella
|> Application.get_env(:plugins)
|> Enum.reduce([], fn {_, list}, acc ->
if mods = list[:schemas], do: acc ++ mods, else: acc
end)
end
@doc false
@spec get_migration_paths() :: [String.t()]
def get_migration_paths do
get_plugin_paths(~w(priv repo migrations))
end
@doc false
@spec get_seeds_paths() :: [String.t()]
def get_seeds_paths do
get_plugin_paths(~w(priv repo seeds.exs))
end
@spec get_plugin_paths([String.t()]) :: [String.t()]
def get_plugin_paths(paths \\ [""]) do
:unbrella
|> Application.get_env(:plugins)
|> Enum.reduce([], fn {plugin, list}, acc ->
path = Path.join(["plugins", list[:path] || to_string(plugin) | paths])
if File.exists?(path), do: [path | acc], else: acc
end)
end
def get_plugins do
Application.get_env(:unbrella, :plugins)
end
def get_assets_paths do
Enum.reduce(get_plugins(), [], fn {name, config}, acc ->
case config[:assets] do
nil ->
acc
assets ->
path = Path.join(["plugins", config[:path] || to_string(name), "assets"])
Enum.map(assets, fn {src, dest} ->
%{
src: src,
name: name,
destination_path: Path.join(["assets", to_string(src), to_string(dest)]),
source_path: Path.join([path, to_string(src)])
}
end) ++ acc
end
end)
end
def get_migrations(repo, _args \\ []) do
priv_migrations_path = Path.join([source_repo_priv(repo), "migrations", "*"])
base_paths =
priv_migrations_path
|> Path.wildcard()
|> Enum.filter(&(Path.extname(&1) == ".exs"))
plugin_paths =
["plugins", "*", priv_migrations_path]
|> Path.join()
|> Path.wildcard()
|> Enum.filter(&(Path.extname(&1) == ".exs"))
build_migrate_files(base_paths ++ plugin_paths)
end
defp build_migrate_files(paths) do
paths
|> Enum.map(fn path ->
[_, num] = Regex.run(~r/^([0-9]+)/, Path.basename(path))
{num, path}
end)
|> Enum.sort(&(elem(&1, 0) <= elem(&2, 0)))
|> List.foldr([], fn {num, path}, acc ->
case Code.eval_file(path) do
{{:module, mod, _, _}, _} ->
[{String.to_integer(num), mod} | acc]
other ->
IO.puts("error for #{path}: " <> inspect(other))
acc
end
end)
end
end
| 25.043478 | 87 | 0.561111 |
7372028a19592813986692a8ae155343d461f69f
| 84 |
exs
|
Elixir
|
test/intro_beam_web/views/page_view_test.exs
|
bloxera/intro_beam
|
6620c3ebc2d01a164233d15a6dfe9f17ed4c99d0
|
[
"MIT"
] | null | null | null |
test/intro_beam_web/views/page_view_test.exs
|
bloxera/intro_beam
|
6620c3ebc2d01a164233d15a6dfe9f17ed4c99d0
|
[
"MIT"
] | null | null | null |
test/intro_beam_web/views/page_view_test.exs
|
bloxera/intro_beam
|
6620c3ebc2d01a164233d15a6dfe9f17ed4c99d0
|
[
"MIT"
] | null | null | null |
defmodule IntroBeamWeb.PageViewTest do
use IntroBeamWeb.ConnCase, async: true
end
| 21 | 40 | 0.833333 |
73722b955921a861153d088bdb8cd3aa6c1c08e2
| 245 |
ex
|
Elixir
|
lib/mariaex/geometry/line_string.ex
|
nedap/mariaex
|
102a23088386eb5038337084be34775e59945924
|
[
"Apache-2.0"
] | 264 |
2015-03-05T06:55:21.000Z
|
2021-08-02T22:12:35.000Z
|
lib/mariaex/geometry/line_string.ex
|
nedap/mariaex
|
102a23088386eb5038337084be34775e59945924
|
[
"Apache-2.0"
] | 215 |
2015-03-04T23:39:52.000Z
|
2022-01-17T05:14:10.000Z
|
lib/mariaex/geometry/line_string.ex
|
nedap/mariaex
|
102a23088386eb5038337084be34775e59945924
|
[
"Apache-2.0"
] | 132 |
2015-03-04T22:50:48.000Z
|
2021-12-09T23:28:59.000Z
|
defmodule Mariaex.Geometry.LineString do
@moduledoc """
Define the LineString struct
"""
@type t :: %Mariaex.Geometry.LineString{ coordinates: [{number, number}], srid: non_neg_integer | nil }
defstruct coordinates: [], srid: nil
end
| 27.222222 | 105 | 0.714286 |
737232d9cba660056737bf242ab47d28b1e5c112
| 394 |
exs
|
Elixir
|
lib/mix/test/fixtures/umbrella_test/apps/bar/test/bar_tests.exs
|
doughsay/elixir
|
7356a47047d0b54517bd6886603f09b1121dde2b
|
[
"Apache-2.0"
] | 19,291 |
2015-01-01T02:42:49.000Z
|
2022-03-31T21:01:40.000Z
|
lib/mix/test/fixtures/umbrella_test/apps/bar/test/bar_tests.exs
|
doughsay/elixir
|
7356a47047d0b54517bd6886603f09b1121dde2b
|
[
"Apache-2.0"
] | 8,082 |
2015-01-01T04:16:23.000Z
|
2022-03-31T22:08:02.000Z
|
lib/mix/test/fixtures/umbrella_test/apps/bar/test/bar_tests.exs
|
doughsay/elixir
|
7356a47047d0b54517bd6886603f09b1121dde2b
|
[
"Apache-2.0"
] | 3,472 |
2015-01-03T04:11:56.000Z
|
2022-03-29T02:07:30.000Z
|
defmodule BarTest do
use ExUnit.Case
test "greets the world" do
assert Bar.hello() == :world
end
test "world the greets" do
assert Bar.Ignore.world() == :hello
end
@tag :maybe_skip
test "works with protocols" do
assert Bar.Protocol.to_uppercase("foo") == "FOO"
end
test "protocols are consolidated" do
assert Protocol.consolidated?(Bar.Protocol)
end
end
| 18.761905 | 52 | 0.682741 |
7372da9d85b50e995fa480dc8fa8dbd38f068207
| 1,548 |
ex
|
Elixir
|
lib/cforum/threads/tree_helper.ex
|
campingrider/cforum_ex
|
cf27684c47d6dc26c9c37a946f1c729a79d27c70
|
[
"MIT"
] | null | null | null |
lib/cforum/threads/tree_helper.ex
|
campingrider/cforum_ex
|
cf27684c47d6dc26c9c37a946f1c729a79d27c70
|
[
"MIT"
] | null | null | null |
lib/cforum/threads/tree_helper.ex
|
campingrider/cforum_ex
|
cf27684c47d6dc26c9c37a946f1c729a79d27c70
|
[
"MIT"
] | null | null | null |
defmodule Cforum.Threads.TreeHelper do
alias Cforum.Threads.Thread
alias Cforum.Messages.Message
alias Cforum.Helpers
def sort_threads(threads, direction, thread_modifier),
do: Enum.map(threads, &gen_thread_tree(&1, thread_modifier, direction))
def gen_thread_tree(thread, modifier, direction \\ "ascending") do
sorted_messages =
Enum.sort(thread.messages, fn a, b ->
cond do
a.parent_id == b.parent_id && direction == "ascending" ->
v = Timex.compare(a.created_at, b.created_at)
v == -1 || v == 0
a.parent_id == b.parent_id && direction == "descending" ->
v = Timex.compare(a.created_at, b.created_at)
v == 1 || v == 0
true ->
Helpers.to_int(a.parent_id) <= Helpers.to_int(b.parent_id)
end
end)
thread =
if modifier != nil do
%Thread{thread | sorted_messages: sorted_messages}
|> modifier.()
else
%Thread{thread | sorted_messages: sorted_messages}
end
tree =
thread.sorted_messages
|> Enum.reverse()
|> Enum.reduce(%{}, fn msg, map ->
msg = %Message{msg | messages: Map.get(map, msg.message_id, [])}
Map.update(map, msg.parent_id, [msg], fn msgs -> [msg | msgs] end)
end)
|> Map.get(nil)
|> hd
%Thread{
thread
| sorted_messages: sorted_messages,
message: tree,
tree: tree,
accepted: Enum.filter(sorted_messages, &(&1.flags["accepted"] == "yes"))
}
end
end
| 29.207547 | 80 | 0.584625 |
7372e1d0bb4942f0fd758d12dd3aef6da4659b0c
| 807 |
ex
|
Elixir
|
test/support/channel_case.ex
|
kpanic/phoenix_forecastr_live_view
|
e8471d64c28234b6bfe1489f40616dd0324a888f
|
[
"Apache-2.0"
] | 1 |
2020-01-12T21:52:23.000Z
|
2020-01-12T21:52:23.000Z
|
test/support/channel_case.ex
|
kpanic/phoenix_forecastr_live_view
|
e8471d64c28234b6bfe1489f40616dd0324a888f
|
[
"Apache-2.0"
] | null | null | null |
test/support/channel_case.ex
|
kpanic/phoenix_forecastr_live_view
|
e8471d64c28234b6bfe1489f40616dd0324a888f
|
[
"Apache-2.0"
] | null | null | null |
defmodule PhoenixForecastrLiveViewWeb.ChannelCase do
@moduledoc """
This module defines the test case to be used by
channel tests.
Such tests rely on `Phoenix.ChannelTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with channels
use Phoenix.ChannelTest
# The default endpoint for testing
@endpoint PhoenixForecastrLiveViewWeb.Endpoint
end
end
setup _tags do
:ok
end
end
| 25.21875 | 59 | 0.738538 |
73731bbe5abc275967ef7f0cc72550dd25ba4086
| 649 |
ex
|
Elixir
|
lib/mix/lib/mix/tasks/local.ex
|
sunaku/elixir
|
8aa43eaedd76be8ac0d495049eb9ecd56971f4fe
|
[
"Apache-2.0"
] | null | null | null |
lib/mix/lib/mix/tasks/local.ex
|
sunaku/elixir
|
8aa43eaedd76be8ac0d495049eb9ecd56971f4fe
|
[
"Apache-2.0"
] | null | null | null |
lib/mix/lib/mix/tasks/local.ex
|
sunaku/elixir
|
8aa43eaedd76be8ac0d495049eb9ecd56971f4fe
|
[
"Apache-2.0"
] | 1 |
2020-12-07T08:04:16.000Z
|
2020-12-07T08:04:16.000Z
|
defmodule Mix.Tasks.Local do
use Mix.Task
@shortdoc "List local tasks"
@moduledoc """
List local tasks.
"""
def run([]) do
shell = Mix.shell
modules = Mix.Local.all_tasks
docs = for module <- modules do
{Mix.Task.task_name(module), Mix.Task.shortdoc(module)}
end
max = Enum.reduce docs, 0, fn({task, _}, acc) ->
max(byte_size(task), acc)
end
sorted = Enum.sort(docs)
Enum.each sorted, fn({task, doc}) ->
shell.info format('mix ~-#{max}s # ~ts', [task, doc])
end
end
defp format(expression, args) do
:io_lib.format(expression, args) |> IO.iodata_to_binary
end
end
| 19.666667 | 61 | 0.610169 |
73733113b156e40e1724a1912b870e0b70711a8b
| 1,164 |
ex
|
Elixir
|
clients/elixir/generated/lib/swaggy_jenkins/model/github_repository.ex
|
cliffano/jenkins-api-clients-generator
|
522d02b3a130a29471df5ec1d3d22c822b3d0813
|
[
"MIT"
] | null | null | null |
clients/elixir/generated/lib/swaggy_jenkins/model/github_repository.ex
|
cliffano/jenkins-api-clients-generator
|
522d02b3a130a29471df5ec1d3d22c822b3d0813
|
[
"MIT"
] | null | null | null |
clients/elixir/generated/lib/swaggy_jenkins/model/github_repository.ex
|
cliffano/jenkins-api-clients-generator
|
522d02b3a130a29471df5ec1d3d22c822b3d0813
|
[
"MIT"
] | null | null | null |
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
# https://openapi-generator.tech
# Do not edit the class manually.
defmodule SwaggyJenkins.Model.GithubRepository do
@moduledoc """
"""
@derive [Poison.Encoder]
defstruct [
:"_class",
:"_links",
:"defaultBranch",
:"description",
:"name",
:"permissions",
:"private",
:"fullName"
]
@type t :: %__MODULE__{
:"_class" => String.t | nil,
:"_links" => SwaggyJenkins.Model.GithubRepositorylinks.t | nil,
:"defaultBranch" => String.t | nil,
:"description" => String.t | nil,
:"name" => String.t | nil,
:"permissions" => SwaggyJenkins.Model.GithubRepositorypermissions.t | nil,
:"private" => boolean() | nil,
:"fullName" => String.t | nil
}
end
defimpl Poison.Decoder, for: SwaggyJenkins.Model.GithubRepository do
import SwaggyJenkins.Deserializer
def decode(value, options) do
value
|> deserialize(:"_links", :struct, SwaggyJenkins.Model.GithubRepositorylinks, options)
|> deserialize(:"permissions", :struct, SwaggyJenkins.Model.GithubRepositorypermissions, options)
end
end
| 27.069767 | 101 | 0.668385 |
737335ace809b7650c53ff6a7b53e61e73b7d7e3
| 335 |
ex
|
Elixir
|
rust-to-elixir/grpc_server/lib/message/message.ex
|
poad/grpc-example
|
d1b775f6d2e89279cd29191d5d4dbec265bf0bf0
|
[
"Apache-2.0"
] | null | null | null |
rust-to-elixir/grpc_server/lib/message/message.ex
|
poad/grpc-example
|
d1b775f6d2e89279cd29191d5d4dbec265bf0bf0
|
[
"Apache-2.0"
] | 64 |
2021-08-30T23:54:04.000Z
|
2022-03-14T21:06:11.000Z
|
rust-to-elixir/grpc_server/lib/message/message.ex
|
poad/grpc-example
|
d1b775f6d2e89279cd29191d5d4dbec265bf0bf0
|
[
"Apache-2.0"
] | null | null | null |
defmodule Message.Schema do
use Ecto.Schema
defmacro __using__(_) do
quote do
use Ecto.Schema
@primary_key {:id, :string, autogenerate: false}
end
end
end
defmodule Message.Message do
use Message.Schema
@primary_key {:id, :string, autogenerate: false}
schema "message" do
field :message
end
end
| 17.631579 | 54 | 0.692537 |
7373480715a1dba6a718cb1148b11a5377cf1fd5
| 1,257 |
exs
|
Elixir
|
config/config.exs
|
scottming/absinthe_error_payload
|
500f7fa2ad1c17eeba644e7922dd0275994f6f94
|
[
"MIT",
"BSD-3-Clause"
] | 90 |
2019-04-30T00:21:58.000Z
|
2022-02-02T15:28:25.000Z
|
config/config.exs
|
scottming/absinthe_error_payload
|
500f7fa2ad1c17eeba644e7922dd0275994f6f94
|
[
"MIT",
"BSD-3-Clause"
] | 18 |
2019-05-01T19:24:16.000Z
|
2022-01-04T07:22:43.000Z
|
config/config.exs
|
scottming/absinthe_error_payload
|
500f7fa2ad1c17eeba644e7922dd0275994f6f94
|
[
"MIT",
"BSD-3-Clause"
] | 25 |
2019-05-24T23:57:24.000Z
|
2022-02-25T19:16:23.000Z
|
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
config :absinthe_error_payload,
ecto_repos: [],
field_constructor: AbsintheErrorPayload.FieldConstructor
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :absinthe_error_payload, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:absinthe_error_payload, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.914286 | 73 | 0.763723 |
73734eb42f218fa3271e44461fe4c7ab01267296
| 270 |
ex
|
Elixir
|
apps/site/lib/site/trip_plan/intermediate_stop.ex
|
noisecapella/dotcom
|
d5ef869412102d2230fac3dcc216f01a29726227
|
[
"MIT"
] | 42 |
2019-05-29T16:05:30.000Z
|
2021-08-09T16:03:37.000Z
|
apps/site/lib/site/trip_plan/intermediate_stop.ex
|
noisecapella/dotcom
|
d5ef869412102d2230fac3dcc216f01a29726227
|
[
"MIT"
] | 872 |
2019-05-29T17:55:50.000Z
|
2022-03-30T09:28:43.000Z
|
apps/site/lib/site/trip_plan/intermediate_stop.ex
|
noisecapella/dotcom
|
d5ef869412102d2230fac3dcc216f01a29726227
|
[
"MIT"
] | 12 |
2019-07-01T18:33:21.000Z
|
2022-03-10T02:13:57.000Z
|
defmodule Site.TripPlan.IntermediateStop do
defstruct description: nil,
stop_id: nil,
alerts: []
@type t :: %__MODULE__{
description: iodata,
stop_id: Stops.Stop.id_t(),
alerts: [Alerts.Alert.t()]
}
end
| 22.5 | 43 | 0.559259 |
737362520182f25c7587536131dd5c0036191bac
| 1,352 |
ex
|
Elixir
|
lib/pilot/supervisor.ex
|
MetisMachine/pilot
|
cb692ced9e20888cb4f528784639f94fc2a762f9
|
[
"MIT"
] | 2 |
2017-10-05T21:04:21.000Z
|
2018-09-19T19:50:28.000Z
|
lib/pilot/supervisor.ex
|
MetisMachine/pilot
|
cb692ced9e20888cb4f528784639f94fc2a762f9
|
[
"MIT"
] | 4 |
2017-10-19T16:00:00.000Z
|
2017-10-26T13:44:42.000Z
|
lib/pilot/supervisor.ex
|
MetisMachine/pilot
|
cb692ced9e20888cb4f528784639f94fc2a762f9
|
[
"MIT"
] | 2 |
2017-10-11T18:06:21.000Z
|
2017-10-12T20:01:53.000Z
|
defmodule Pilot.Supervisor do
@moduledoc false
use Supervisor
require Logger
@defaults [port: 8080]
# Client API
@doc """
Returns the endpoint configuration stored in the `:otp_app` environment
"""
def config(pilot, opts) do
otp_app = Keyword.fetch!(opts, :otp_app)
config =
@defaults
|> Keyword.merge(Application.get_env(otp_app, pilot, []))
|> Keyword.merge([otp_app: otp_app, pilot: pilot])
case Keyword.get(config, :router) do
nil ->
raise ArgumentError, "missing :router configuration in " <>
"config #{inspect(otp_app)}, #{inspect(pilot)}"
_ ->
:ok
end
{otp_app, config}
end
@doc """
Start the endpoint supervisor
"""
def start_link(pilot, config, opts \\ []) do
name = Keyword.get(opts, :name, pilot)
Supervisor.start_link(__MODULE__, {pilot, config}, [name: name])
end
# Server API
def init({_pilot, config}) do
port = Keyword.fetch!(config, :port)
router = Keyword.fetch!(config, :router)
Logger.debug(fn -> "Starting pilot on port #{inspect(port)} " <>
"routing through #{inspect(router)}" end)
children = [
{Plug.Cowboy, scheme: :http, plug: router, options: [port: port]}
]
Supervisor.init(children, strategy: :one_for_one)
end
end
| 23.719298 | 76 | 0.609467 |
73736b84961f52838bba871e052615a59df1c617
| 3,341 |
exs
|
Elixir
|
test/plenario_web/controllers/virtual_date_controller_test.exs
|
vforgione/plenario2
|
001526e5c60a1d32794a18f3fd65ead6cade1a29
|
[
"Apache-2.0"
] | 13 |
2017-12-11T13:59:42.000Z
|
2020-11-16T21:52:31.000Z
|
test/plenario_web/controllers/virtual_date_controller_test.exs
|
vforgione/plenario2
|
001526e5c60a1d32794a18f3fd65ead6cade1a29
|
[
"Apache-2.0"
] | 310 |
2017-11-13T22:52:26.000Z
|
2018-11-19T17:49:30.000Z
|
test/plenario_web/controllers/virtual_date_controller_test.exs
|
vforgione/plenario2
|
001526e5c60a1d32794a18f3fd65ead6cade1a29
|
[
"Apache-2.0"
] | 3 |
2017-12-05T00:36:12.000Z
|
2020-03-10T15:15:29.000Z
|
defmodule PlenarioWeb.Testing.VirtualDateControllerTest do
use PlenarioWeb.Testing.ConnCase
import Plenario.Testing.DataCase
describe "new" do
@tag :auth
test "will display a form", %{conn: conn, user: user} do
data_set = create_data_set(%{user: user})
field = create_field(%{data_set: data_set})
resp =
conn
|> get(Routes.data_set_virtual_date_path(conn, :new, data_set))
|> html_response(:ok)
assert resp =~ field.name
end
end
describe "create" do
@tag :auth
test "will redirect to the parent data set show on success", %{conn: conn, user: user} do
data_set = create_data_set(%{user: user})
field = create_field(%{data_set: data_set})
conn =
conn
|> post(Routes.data_set_virtual_date_path(conn, :create, data_set, %{"virtual_date" => %{"data_set_id" => data_set.id, "yr_field_id" => field.id}}))
redir_path = redirected_to(conn, 302)
resp =
conn
|> recycle()
|> get(redir_path)
|> html_response(:ok)
assert resp =~ "Created a new virtual date"
end
@tag :auth
test "will stay on the form and show errors", %{conn: conn, user: user} do
data_set = create_data_set(%{user: user})
field = create_field(%{data_set: data_set})
resp =
conn
|> post(Routes.data_set_virtual_date_path(conn, :create, data_set, %{"virtual_date" => %{"data_set_id" => data_set.id, "mo_field_id" => field.id}}))
|> html_response(:bad_request)
assert resp =~ "Please review and correct errors in the form below"
end
end
describe "edit" do
@tag :auth
test "will display a form with the date information filled out", %{conn: conn, user: user} do
data_set = create_data_set(%{user: user})
field = create_field(%{data_set: data_set})
date = create_virtual_date(%{data_set: data_set, field: field})
resp =
conn
|> get(Routes.data_set_virtual_date_path(conn, :edit, data_set, date))
|> html_response(:ok)
assert resp =~ "value=\"#{field.id}\""
end
end
describe "update" do
@tag :auth
test "will redirect to the parent data set show on success", %{conn: conn, user: user} do
data_set = create_data_set(%{user: user})
field = create_field(%{data_set: data_set})
date = create_virtual_date(%{data_set: data_set, field: field})
conn =
conn
|> put(Routes.data_set_virtual_date_path(conn, :update, data_set, date, %{"virtual_date" => %{"mo_field_id" => field.id}}))
redir_path = redirected_to(conn, 302)
resp =
conn
|> recycle()
|> get(redir_path)
|> html_response(:ok)
assert resp =~ "Updated virtual date"
end
@tag :auth
test "will stay on the form and show errors", %{conn: conn, user: user} do
data_set = create_data_set(%{user: user})
field = create_field(%{data_set: data_set})
date = create_virtual_date(%{data_set: data_set, field: field})
resp =
conn
|> put(Routes.data_set_virtual_date_path(conn, :update, data_set, date, %{"virtual_date" => %{"yr_field_id" => nil}}))
|> html_response(:bad_request)
assert resp =~ "Please review and correct errors in the form below"
end
end
end
| 30.651376 | 156 | 0.622568 |
737378b5408d5c1a55f20fc3b5ad5c72a9de08d3
| 1,925 |
ex
|
Elixir
|
clients/firestore/lib/google_api/firestore/v1beta1/model/write_result.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/firestore/lib/google_api/firestore/v1beta1/model/write_result.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1 |
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/firestore/lib/google_api/firestore/v1beta1/model/write_result.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1 |
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Firestore.V1beta1.Model.WriteResult do
@moduledoc """
The result of applying a write.
## Attributes
* `transformResults` (*type:* `list(GoogleApi.Firestore.V1beta1.Model.Value.t)`, *default:* `nil`) - The results of applying each DocumentTransform.FieldTransform, in the same order.
* `updateTime` (*type:* `DateTime.t`, *default:* `nil`) - The last update time of the document after applying the write. Not set after a `delete`. If the write did not actually change the document, this will be the previous update_time.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:transformResults => list(GoogleApi.Firestore.V1beta1.Model.Value.t()),
:updateTime => DateTime.t()
}
field(:transformResults, as: GoogleApi.Firestore.V1beta1.Model.Value, type: :list)
field(:updateTime, as: DateTime)
end
defimpl Poison.Decoder, for: GoogleApi.Firestore.V1beta1.Model.WriteResult do
def decode(value, options) do
GoogleApi.Firestore.V1beta1.Model.WriteResult.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Firestore.V1beta1.Model.WriteResult do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.5 | 240 | 0.741299 |
737382de864cfa6c03e0d11732d4c92409c875a1
| 2,164 |
ex
|
Elixir
|
lib/arango.ex
|
mpoeter/arangoex
|
161ed0223f4e75ca47ca921660f162d01fdab863
|
[
"Apache-2.0"
] | null | null | null |
lib/arango.ex
|
mpoeter/arangoex
|
161ed0223f4e75ca47ca921660f162d01fdab863
|
[
"Apache-2.0"
] | null | null | null |
lib/arango.ex
|
mpoeter/arangoex
|
161ed0223f4e75ca47ca921660f162d01fdab863
|
[
"Apache-2.0"
] | 3 |
2018-03-27T09:47:04.000Z
|
2019-11-04T22:41:46.000Z
|
# TODO: batch requests
# TODO: batch async requets
# TODO: async job loookup (does it work?)
# TODO: batch async job lookup request (does it work??)
defmodule Arango do
@moduledoc File.read!("#{__DIR__}/../README.md")
@type ok_error(success) :: {:ok, success} | {:error, any()} | [{:ok, success} | {:error, map()}]
defmodule Error do
defexception message: "ArangoDB error"
end
@doc """
Perform an ArangoDB request
First build an operation from one of the APIs. Then pass it to this
function to perform it.
This function takes an optional second parameter of configuration
overrides. This is useful if you want to have certain configuration
changed on a per request basis.
## Examples
```
{:ok, dbs} = Arango.Database.list_databases() |> ArangoDB.request
{:ok, dbs} = Arango.Database.list_databases() |> ArangoDB.request(username: joe, password: sekret)
```
"""
# @spec request(Arango.Operation.t) :: term
@spec request(Arango.Request.t, Keyword.t) :: ok_error(any())
def request(op, config_overrides \\ []) do
Arango.Request.perform(op, config_overrides)
end
# @doc """
# Perform an ArangoDB request, raise if it fails.
# Same as `request/1,2` except it will either return the successful response from
# ArangoDB or raise an exception.
# """
# @spec request!(Arango.Operation.t) :: term | no_return
# @spec request!(Arango.Operation.t, Keyword.t) :: term | no_return
# def request!(op, config_overrides \\ []) do
# case request(op, config_overrides) do
# {:ok, result} ->
# result
# error ->
# raise Arango.Error, """
# Arango Request Error!
# #{inspect error}
# """
# end
# end
# @doc """
# Return a stream for the ArangoDB resource.
# ## Examples
# ```
# Arango.Cursor.create("FOR p IN products RETURN p") |> Arango.stream!
# ```
# """
# @spec stream!(Arango.Operation.t) :: Enumerable.t
# @spec stream!(Arango.Operation.t, Keyword.t) :: Enumerable.t
# def stream!(op, config_overrides \\ []) do
# Arango.Operation.stream!(op, Arango.Config.new(op.service, config_overrides))
# end
end
| 28.473684 | 100 | 0.64695 |
7373b0174969d07fd99d7da8dc686379163b10c0
| 486 |
ex
|
Elixir
|
testData/org/elixir_lang/parser_definition/function_reference_parsing_test_case/AtomDotOperator.ex
|
keyno63/intellij-elixir
|
4033e319992c53ddd42a683ee7123a97b5e34f02
|
[
"Apache-2.0"
] | 1,668 |
2015-01-03T05:54:27.000Z
|
2022-03-25T08:01:20.000Z
|
testData/org/elixir_lang/parser_definition/function_reference_parsing_test_case/AtomDotOperator.ex
|
keyno63/intellij-elixir
|
4033e319992c53ddd42a683ee7123a97b5e34f02
|
[
"Apache-2.0"
] | 2,018 |
2015-01-01T22:43:39.000Z
|
2022-03-31T20:13:08.000Z
|
testData/org/elixir_lang/parser_definition/function_reference_parsing_test_case/AtomDotOperator.ex
|
keyno63/intellij-elixir
|
4033e319992c53ddd42a683ee7123a97b5e34f02
|
[
"Apache-2.0"
] | 145 |
2015-01-15T11:37:16.000Z
|
2021-12-22T05:51:02.000Z
|
:one.&&/2
:one.&&&/2
:one.<<</2
:one.<<~/2
:one.<|>/2
:one.<~>/2
:one.>>>/2
:one.~>>/2
:one.<~/2
:one.|>/2
:one.~>/2
:one.@/1
:one.&/1
:one.after/1
:one.and/2
:one.catch/1
:one.do/1
:one.else/1
:one.end/0
:one.in/2
:one.not/1
:one.or/2
:one.rescue/1
:one.!==/2
:one.===/2
:one.!=/2
:one.+/2
:one.-/2
:one.^^^/2
:one.||/2
:one.|||/2
:one.~~~/2
:one.!/1
:one.<-/2
:one.\\/2
:one.=/2
:one.*/2
:one.//2
:one.|/2
:one.<=/2
:one.>=/2
:one.</2
:one.>/2
:one.->/2
:one.++/2
:one.--/2
:one.<>/2
| 10.125 | 13 | 0.458848 |
7373da7d9cc428d12f0681918caf7f2506263685
| 1,761 |
ex
|
Elixir
|
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_crop_hints_annotation.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | 1 |
2018-12-03T23:43:10.000Z
|
2018-12-03T23:43:10.000Z
|
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_crop_hints_annotation.ex
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
clients/vision/lib/google_api/vision/v1/model/google_cloud_vision_v1p2beta1_crop_hints_annotation.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.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHintsAnnotation do
@moduledoc """
Set of crop hints that are used to generate new crops when serving images.
## Attributes
* `cropHints` (*type:* `list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHint.t)`, *default:* `nil`) - Crop hint results.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:cropHints => list(GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHint.t())
}
field(:cropHints, as: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHint, type: :list)
end
defimpl Poison.Decoder,
for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHintsAnnotation do
def decode(value, options) do
GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHintsAnnotation.decode(value, options)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Vision.V1.Model.GoogleCloudVisionV1p2beta1CropHintsAnnotation do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.938776 | 137 | 0.767746 |
7373dba4cadeefb9779807fa2508729acbc15908
| 1,421 |
exs
|
Elixir
|
config/dev.exs
|
nilenso/exkubed
|
84586ab75ebc417cf5a5bed5323d9032b23ea2ec
|
[
"MIT"
] | 1 |
2019-08-29T20:35:54.000Z
|
2019-08-29T20:35:54.000Z
|
config/dev.exs
|
nilenso/exkubed
|
84586ab75ebc417cf5a5bed5323d9032b23ea2ec
|
[
"MIT"
] | null | null | null |
config/dev.exs
|
nilenso/exkubed
|
84586ab75ebc417cf5a5bed5323d9032b23ea2ec
|
[
"MIT"
] | null | null | null |
use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with webpack to recompile .js and .css sources.
config :exkubed, ExkubedWeb.Endpoint,
http: [port: 4000],
server: true,
debug_errors: true,
check_origin: false,
watchers: []
# ## SSL Support
#
# In order to use HTTPS in development, a self-signed
# certificate can be generated by running the following
# Mix task:
#
# mix phx.gen.cert
#
# Note that this task requires Erlang/OTP 20 or later.
# Run `mix help phx.gen.cert` for more information.
#
# The `http:` config above can be replaced with:
#
# https: [
# port: 4001,
# cipher_suite: :strong,
# keyfile: "priv/cert/selfsigned_key.pem",
# certfile: "priv/cert/selfsigned.pem"
# ],
#
# If desired, both `http:` and `https:` keys can be
# configured to run both http and https servers on
# different ports.
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development. Avoid configuring such
# in production as building large stacktraces may be expensive.
config :phoenix, :stacktrace_depth, 20
# Initialize plugs at runtime for faster development compilation
config :phoenix, :plug_init_mode, :runtime
| 29 | 68 | 0.721323 |
7373fc21a2b018126e44528a6c7f72a2f5782893
| 98 |
exs
|
Elixir
|
v02/ch09/pipe2.edit1.exs
|
oiax/elixir-primer
|
c8b89a29f108cc335b8e1341b7a1e90ec12adc66
|
[
"MIT"
] | null | null | null |
v02/ch09/pipe2.edit1.exs
|
oiax/elixir-primer
|
c8b89a29f108cc335b8e1341b7a1e90ec12adc66
|
[
"MIT"
] | null | null | null |
v02/ch09/pipe2.edit1.exs
|
oiax/elixir-primer
|
c8b89a29f108cc335b8e1341b7a1e90ec12adc66
|
[
"MIT"
] | null | null | null |
%{a: 1, b: 2}
|> Map.merge(%{c: 3})
|> Enum.map(fn({k, v}) -> {k, v * 2} end)
|> IO.inspect
| 19.6 | 43 | 0.408163 |
73746cb8b0ba9e4b621e504d53efedd7c39958c1
| 939 |
ex
|
Elixir
|
web/router.ex
|
meilab/meilab_blog
|
86fca779c8b01559440ea3f686695700e8cf5ed2
|
[
"MIT"
] | null | null | null |
web/router.ex
|
meilab/meilab_blog
|
86fca779c8b01559440ea3f686695700e8cf5ed2
|
[
"MIT"
] | null | null | null |
web/router.ex
|
meilab/meilab_blog
|
86fca779c8b01559440ea3f686695700e8cf5ed2
|
[
"MIT"
] | null | null | null |
defmodule MeilabBlog.Router do
use MeilabBlog.Web, :router
pipeline :browser do
plug :accepts, ["html"]
plug :fetch_session
plug :fetch_flash
plug :protect_from_forgery
plug :put_secure_browser_headers
end
pipeline :api do
plug :accepts, ["json"]
end
scope "/", MeilabBlog do
pipe_through :browser # Use the default browser stack
get "/", PageController, :index
get "/login", PageController, :index
get "/register", PageController, :index
get "/postlist", PageController, :index
get "/postdetail/:slug", PageController, :index
get "/projectlist", PageController, :index
get "/projectdetail/:slug", PageController, :index
get "/rent", PageController, :index
end
# Other scopes may use custom stacks.
scope "/api/v1/meilab", MeilabBlog do
pipe_through :api
post ( "/auth" ), ApiController, :login
get ("/posts"), ApiController, :posts
end
end
| 25.378378 | 57 | 0.679446 |
7374710741a36c9b8c8f7488f0dd5b2ed77f2f5d
| 1,135 |
exs
|
Elixir
|
clients/service_user/config/config.exs
|
leandrocp/elixir-google-api
|
a86e46907f396d40aeff8668c3bd81662f44c71e
|
[
"Apache-2.0"
] | 1 |
2018-12-03T23:43:10.000Z
|
2018-12-03T23:43:10.000Z
|
clients/service_user/config/config.exs
|
leandrocp/elixir-google-api
|
a86e46907f396d40aeff8668c3bd81662f44c71e
|
[
"Apache-2.0"
] | null | null | null |
clients/service_user/config/config.exs
|
leandrocp/elixir-google-api
|
a86e46907f396d40aeff8668c3bd81662f44c71e
|
[
"Apache-2.0"
] | 1 |
2020-11-10T16:58:27.000Z
|
2020-11-10T16:58:27.000Z
|
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :service_user_api, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:service_user_api, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 36.612903 | 73 | 0.755066 |
73747759dd9d0546b9344ae57887c91b8466fd4c
| 791 |
ex
|
Elixir
|
test/support/resources/post.ex
|
totaltrash/ash_postgres
|
7af29756fadaaad018d6fcf35e7f806cd304d6d2
|
[
"MIT"
] | null | null | null |
test/support/resources/post.ex
|
totaltrash/ash_postgres
|
7af29756fadaaad018d6fcf35e7f806cd304d6d2
|
[
"MIT"
] | null | null | null |
test/support/resources/post.ex
|
totaltrash/ash_postgres
|
7af29756fadaaad018d6fcf35e7f806cd304d6d2
|
[
"MIT"
] | null | null | null |
defmodule AshPostgres.Test.Post do
@moduledoc false
use Ash.Resource,
data_layer: AshPostgres.DataLayer
postgres do
table "posts"
repo AshPostgres.TestRepo
end
actions do
read(:read)
create(:create)
end
attributes do
attribute(:id, :uuid, primary_key?: true, default: &Ecto.UUID.generate/0)
attribute(:title, :string)
attribute(:score, :integer)
attribute(:public, :boolean)
end
relationships do
has_many(:comments, AshPostgres.Test.Comment, destination_field: :post_id)
end
aggregates do
count(:count_of_comments, :comments)
count :count_of_comments_called_match, :comments do
filter(title: "match")
end
first :first_comment, :comments, :title do
sort(title: :asc_nils_last)
end
end
end
| 20.282051 | 78 | 0.692794 |
73747ee04183d9371d39d647ead89610f64d87a0
| 2,715 |
exs
|
Elixir
|
test/pilot_responses_test.exs
|
MetisMachine/pilot
|
cb692ced9e20888cb4f528784639f94fc2a762f9
|
[
"MIT"
] | 2 |
2017-10-05T21:04:21.000Z
|
2018-09-19T19:50:28.000Z
|
test/pilot_responses_test.exs
|
MetisMachine/pilot
|
cb692ced9e20888cb4f528784639f94fc2a762f9
|
[
"MIT"
] | 4 |
2017-10-19T16:00:00.000Z
|
2017-10-26T13:44:42.000Z
|
test/pilot_responses_test.exs
|
MetisMachine/pilot
|
cb692ced9e20888cb4f528784639f94fc2a762f9
|
[
"MIT"
] | 2 |
2017-10-11T18:06:21.000Z
|
2017-10-12T20:01:53.000Z
|
defmodule Pilot.Tests.Responses do
require Logger
use ExUnit.Case
import Plug.Conn
import Plug.Test
use Pilot.Responses
doctest Pilot.Responses
test "ensure redirect status and headers are set." do
test_conn()
|> redirect("/test/path")
|> assert_redirect("/test/path")
end
test "ensure status is properly set for return response" do
test_conn()
|> status(404)
|> assert_status(404)
end
test "ensure status properly sets headers for return response" do
test_conn()
|> status(404, resp_headers: %{"x-foo" => "bar"})
|> assert_status(404)
|> assert_header({"x-foo", "bar"})
end
test "ensure text body and text/plain content type is in the response" do
assert test_conn()
|> text(:ok, "testing text", resp_headers: %{"x-foo" => "bar"})
|> assert_state()
|> assert_status(200)
|> assert_header({"x-foo", "bar"})
|> assert_content_type("text/plain")
|> sent_resp()
|> elem(2)
|> String.equivalent?("testing text")
end
test "ensure html body and text/html content type is in the response" do
assert test_conn()
|> html(:ok, "<h1>testing html</h1>", resp_headers: %{"x-foo" => "bar"})
|> assert_state()
|> assert_status(200)
|> assert_header({"x-foo", "bar"})
|> assert_content_type("text/html")
|> sent_resp()
|> elem(2)
|> String.equivalent?("<h1>testing html</h1>")
end
test "ensure json body and content type" do
assert test_conn()
|> json(:ok, %{hello: "world"}, resp_headers: %{"x-foo" => "bar"})
|> assert_state()
|> assert_status(200)
|> assert_header({"x-foo", "bar"})
|> assert_content_type("application/json")
|> sent_resp()
|> elem(2)
|> String.equivalent?(Poison.encode!(%{hello: "world"}))
end
defp test_conn(method \\ :get, path \\ "/path") do
conn(method, path)
end
defp assert_header(conn, {key, val}) do
assert Plug.Conn.get_resp_header(conn, key) == [val]
conn
end
defp assert_content_type(conn, type) do
assert conn
|> Plug.Conn.get_resp_header("content-type")
|> to_string()
|> String.contains?(type)
conn
end
defp assert_state(conn, state \\ :sent) do
assert conn.state == state
conn
end
defp assert_status(conn, status) do
assert conn.status == status
conn
end
defp assert_redirect(conn, status \\ 302, to) do
conn
|> assert_state()
|> assert_status(status)
|> assert_header({"location", to})
conn
end
end
| 25.373832 | 84 | 0.578269 |
73748207870ae798581504b5c0bdf44dc33592b9
| 328 |
ex
|
Elixir
|
lib/four_lucha/resource/dlc.ex
|
Thomas-Jean/four_lucha
|
591627059c02edc3315b5cac2c35eacb821108ff
|
[
"Apache-2.0"
] | 1 |
2021-02-21T19:15:27.000Z
|
2021-02-21T19:15:27.000Z
|
lib/four_lucha/resource/dlc.ex
|
Thomas-Jean/four_lucha
|
591627059c02edc3315b5cac2c35eacb821108ff
|
[
"Apache-2.0"
] | null | null | null |
lib/four_lucha/resource/dlc.ex
|
Thomas-Jean/four_lucha
|
591627059c02edc3315b5cac2c35eacb821108ff
|
[
"Apache-2.0"
] | null | null | null |
defmodule FourLucha.Resource.DLC do
@moduledoc false
defstruct(
api_detail_url: nil,
date_added: nil,
date_last_updated: nil,
deck: nil,
description: nil,
game: nil,
guid: nil,
id: nil,
image: nil,
name: nil,
platform: nil,
release_date: nil,
site_detail_url: nil
)
end
| 17.263158 | 35 | 0.628049 |
7374866c9c9f2a1ba63fbdfe59dc7deb4a35b2ab
| 579 |
ex
|
Elixir
|
lib/web/plugs/ensure_user_verified.ex
|
sb8244/grapevine
|
effaaa01294d30114090c20f9cc40b8665d834f2
|
[
"MIT"
] | 107 |
2018-10-05T18:20:32.000Z
|
2022-02-28T04:02:50.000Z
|
lib/web/plugs/ensure_user_verified.ex
|
sb8244/grapevine
|
effaaa01294d30114090c20f9cc40b8665d834f2
|
[
"MIT"
] | 33 |
2018-10-05T14:11:18.000Z
|
2022-02-10T22:19:18.000Z
|
lib/web/plugs/ensure_user_verified.ex
|
sb8244/grapevine
|
effaaa01294d30114090c20f9cc40b8665d834f2
|
[
"MIT"
] | 18 |
2019-02-03T03:08:20.000Z
|
2021-12-28T04:29:36.000Z
|
defmodule Web.Plugs.EnsureUserVerified do
@moduledoc """
Verify a user is in the session
"""
import Plug.Conn
import Phoenix.Controller
alias GrapevineData.Accounts
alias Web.Router.Helpers, as: Routes
def init(default), do: default
def call(conn, _opts) do
%{current_user: user} = conn.assigns
case Accounts.email_verified?(user) do
true ->
conn
false ->
conn
|> put_flash(:error, "You must verify your email first.")
|> redirect(to: Routes.page_path(conn, :index))
|> halt()
end
end
end
| 19.965517 | 65 | 0.635579 |
73749a1e9c063fd49423bd8d63456d563762bd79
| 9,147 |
ex
|
Elixir
|
lib/ex_zipper/zipper.ex
|
mikowitz/ex_zipper
|
9ae652af30941ae6bab2b5f6d4f18e853c151280
|
[
"Unlicense"
] | 5 |
2017-11-28T16:59:27.000Z
|
2021-05-24T00:39:39.000Z
|
lib/ex_zipper/zipper.ex
|
mikowitz/ex_zipper
|
9ae652af30941ae6bab2b5f6d4f18e853c151280
|
[
"Unlicense"
] | null | null | null |
lib/ex_zipper/zipper.ex
|
mikowitz/ex_zipper
|
9ae652af30941ae6bab2b5f6d4f18e853c151280
|
[
"Unlicense"
] | 1 |
2018-09-20T21:26:50.000Z
|
2018-09-20T21:26:50.000Z
|
defmodule ExZipper.Zipper do
@moduledoc """
An Elixir implementation of [Huet's Zipper][huet], with gratitude to Rich Hickey's
[Clojure implementation][clojure].
Zippers provide a method of navigating and editing a tree while maintaining
enough state data to reconstruct the tree from the currently focused node.
For the most part, functions defined on `ExZipper.Zipper` return either an
`ExZipper.Zipper` struct or an error tuple of the form `{:error, :error_type}`,
if the function tries to move to a point on the tree that doesn't exist.
This allows easy chaining of functions with a quick failure mode if any function
in the chain returns an error.
[huet]: https://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-fp/docs/huet-zipper.pdf
[clojure]: https://clojure.github.io/clojure/clojure.zip-api.html
"""
defstruct [:focus, :crumbs, :functions]
@type t :: %__MODULE__{focus: any(), crumbs: nil | map(), functions: map()}
@type error :: {:error, atom}
@type maybe_zipper :: Zipper.t | Zipper.error
@doc """
Returns a new zipper with `root` as the root tree of the zipper, and
`is_branch`, `children` and `make_node` as the internal functions that
define construction parameters for the tree.
In order, the arguments are
1. a function to determine whether a node is a branch
2. a function to return the children of a branch node
3. a function to create a new node from an existing node and a new set of children
4. the root node of the zipper
## Example
iex> zipper = Zipper.zipper( # zipper for nested lists
...> &is_list/1, # a branch can have children, so, a list
...> &(&1), # the children of a list is the list itself
...> fn _node, children -> children end, # a new node is just the new list
...> [1,[2,3,[4,5]]]
...> )
iex> zipper.focus
[1,[2,3,[4,5]]]
"""
@spec zipper(
(any() -> boolean),
(any() -> [any()]),
(any(), [any()] -> any()),
any()
) :: Zipper.t
def zipper(is_branch, children, make_node, root) do
%__MODULE__{
focus: root,
crumbs: nil,
functions: %{
branch?: is_branch,
children: children,
make_node: make_node
}
}
end
@doc """
Returns a new zipper built from the given list
## Example
iex> zipper = Zipper.list_zipper([1,[2,3,[4,5]]])
iex> zipper.focus
[1,[2,3,[4,5]]]
"""
@spec list_zipper(list()) :: Zipper.t
def list_zipper(list) when is_list(list) do
zipper(
&is_list/1,
&(&1),
fn _node, children -> children end,
list
)
end
@doc """
Returns the current focus of the zipper
## Example
iex> zipper = Zipper.list_zipper([1,[2,3,[4,5]]])
iex> Zipper.node(zipper)
[1,[2,3,[4,5]]]
iex> zipper |> Zipper.down |> Zipper.node
1
"""
@spec node(Zipper.t) :: any
def node(%__MODULE__{focus: focus}), do: focus
@doc """
Returns to the root of the zipper. Remains in place if already on the root.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> zipper |> Zipper.root |> Zipper.node
[1,[],[2,3,[4,5]]]
iex> zipper |> Zipper.down |> Zipper.rightmost |> Zipper.down |> Zipper.root |> Zipper.node
[1,[],[2,3,[4,5]]]
"""
@spec root(Zipper.t) :: Zipper.t
def root(zipper = %__MODULE__{crumbs: nil}), do: zipper
def root(zipper = %__MODULE__{}), do: zipper |> up |> root
@doc """
Returns all left siblings of the current focus. Returns an error if called
on the root.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.lefts(zipper)
{:error, :lefts_of_root}
iex> zipper |> Zipper.down |> Zipper.lefts
[]
iex> zipper |> Zipper.down |> Zipper.rightmost |> Zipper.lefts
[1,[]]
"""
@spec lefts(Zipper.t) :: [any()] | Zipper.error
def lefts(%__MODULE__{crumbs: nil}), do: {:error, :lefts_of_root}
def lefts(%__MODULE__{crumbs: %{left: left}}), do: Enum.reverse(left)
@doc """
Returns all left right of the current focus. Returns an error if called
on the root.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.rights(zipper)
{:error, :rights_of_root}
iex> zipper |> Zipper.down |> Zipper.rights
[[],[2,3,[4,5]]]
iex> zipper |> Zipper.down |> Zipper.rightmost |> Zipper.rights
[]
"""
@spec rights(Zipper.t) :: [any()] | Zipper.error
def rights(%__MODULE__{crumbs: nil}), do: {:error, :rights_of_root}
def rights(%__MODULE__{crumbs: %{right: right}}), do: right
@doc """
Returns a path of nodes leading from the root to, but excluding, the current
focus. Returns an empty list at the root.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.path(zipper)
[]
iex> zipper = zipper |> Zipper.down |> Zipper.rightmost |> Zipper.down
iex> zipper.focus
2
iex> Zipper.path(zipper)
[[1,[],[2,3,[4,5]]],[2,3,[4,5]]]
"""
@spec path(Zipper.t) :: [any()]
def path(%__MODULE__{crumbs: nil}), do: []
def path(%__MODULE__{crumbs: %{ppath: paths}}), do: Enum.reverse(paths)
@doc """
Returns true if the current focus of the zipper is a branch, even if it has
no children, false otherwise.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.branch?(zipper)
true
iex> zipper |> Zipper.down |> Zipper.branch?
false
iex> zipper |> Zipper.down |> Zipper.right |> Zipper.branch?
true
"""
@spec branch?(Zipper.t) :: boolean
def branch?(zipper = %__MODULE__{}) do
zipper.functions.branch?.(zipper.focus)
end
@doc """
Returns the children of the current focus, or an error if called on a leaf.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.children(zipper)
[1,[],[2,3,[4,5]]]
iex> zipper |> Zipper.down |> Zipper.children
{:error, :children_of_leaf}
iex> zipper |> Zipper.down |> Zipper.right |> Zipper.children
[]
"""
@spec children(Zipper.t) :: [any()] | Zipper.error
def children(zipper = %__MODULE__{}) do
case branch?(zipper) do
true -> zipper.functions.children.(zipper.focus)
false -> {:error, :children_of_leaf}
end
end
@doc """
Returns a new node created from `node` and `children`. The `zipper` first argument
is to provide the context from which to determine how to create a new node.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.make_node(zipper, [8,9], [10,11,12])
[10,11,12]
"""
@spec make_node(Zipper.t, any(), [any()]) :: any()
def make_node(zipper = %__MODULE__{}, node, children) do
zipper.functions.make_node.(node, children)
end
@doc """
Returns true if a depth-first walkthrough of the zipper has been exhausted.
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> zipper = zipper |> Zipper.next |> Zipper.next |> Zipper.next
iex> Zipper.node(zipper)
[2,3,[4,5]]
iex> Zipper.end?(zipper)
false
iex> zipper = zipper |> Zipper.next |> Zipper.next |> Zipper.next |> Zipper.next |> Zipper.next |> Zipper.next
iex> Zipper.node(zipper)
[1,[],[2,3,[4,5]]]
iex> Zipper.end?(zipper)
true
"""
@spec end?(Zipper.t) :: boolean
def end?(%__MODULE__{crumbs: :end}), do: true
def end?(%__MODULE__{}), do: false
@doc """
Returns a flat list of all the elements in the zipper, ordered via a
depth-first walk, including the root
## Examples
iex> zipper = Zipper.list_zipper([1,[],[2,3,[4,5]]])
iex> Zipper.to_list(zipper)
[[1,[],[2,3,[4,5]]], 1, [], [2,3,[4,5]], 2, 3, [4,5], 4, 5]
"""
@spec to_list(Zipper.t) :: [any()]
def to_list(zipper = %__MODULE__{}), do: _to_list(zipper, [])
defdelegate down(zipper), to: ExZipper.Zipper.Navigation
defdelegate up(zipper), to: ExZipper.Zipper.Navigation
defdelegate right(zipper), to: ExZipper.Zipper.Navigation
defdelegate left(zipper), to: ExZipper.Zipper.Navigation
defdelegate rightmost(zipper), to: ExZipper.Zipper.Navigation
defdelegate leftmost(zipper), to: ExZipper.Zipper.Navigation
defdelegate next(zipper), to: ExZipper.Zipper.Navigation
defdelegate prev(zipper), to: ExZipper.Zipper.Navigation
defdelegate insert_right(zipper, node), to: ExZipper.Zipper.Editing
defdelegate insert_left(zipper, node), to: ExZipper.Zipper.Editing
defdelegate insert_child(zipper, node), to: ExZipper.Zipper.Editing
defdelegate append_child(zipper, node), to: ExZipper.Zipper.Editing
defdelegate replace(zipper, node), to: ExZipper.Zipper.Editing
defdelegate edit(zipper, node), to: ExZipper.Zipper.Editing
defdelegate remove(zipper), to: ExZipper.Zipper.Editing
## Private
defp _to_list(zipper, acc) do
case end?(zipper) do
true -> Enum.reverse(acc)
false -> _to_list(next(zipper), [__MODULE__.node(zipper)|acc])
end
end
end
| 30.694631 | 116 | 0.624358 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.