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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e81052564931fd858e173593f70d8d04adc0cbec | 12,221 | exs | Elixir | lib/elixir/test/elixir/code_formatter/general_test.exs | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | 1 | 2021-05-20T13:08:37.000Z | 2021-05-20T13:08:37.000Z | lib/elixir/test/elixir/code_formatter/general_test.exs | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/code_formatter/general_test.exs | namjae/elixir | 6d1561a5939d68fb61f422b83271fbc824847395 | [
"Apache-2.0"
] | 8 | 2018-02-20T18:30:53.000Z | 2019-06-18T14:23:31.000Z | Code.require_file("../test_helper.exs", __DIR__)
defmodule Code.Formatter.GeneralTest do
use ExUnit.Case, async: true
import CodeFormatterHelpers
@short_length [line_length: 10]
describe "aliases" do
test "with atom-only parts" do
assert_same "Elixir"
assert_same "Elixir.Foo"
assert_same "Foo.Bar.Baz"
end
test "removes spaces between aliases" do
assert_format "Foo . Bar . Baz", "Foo.Bar.Baz"
end
test "starting with expression" do
assert_same "__MODULE__.Foo.Bar"
# Syntatically valid, semantically invalid
assert_same "'Foo'.Bar.Baz"
end
test "wraps the head in parens if it has an operator" do
assert_format "+(Foo . Bar . Baz)", "+Foo.Bar.Baz"
assert_format "(+Foo) . Bar . Baz", "(+Foo).Bar.Baz"
end
end
describe "sigils" do
test "without interpolation" do
assert_same ~S[~s(foo)]
assert_same ~S[~s{foo bar}]
assert_same ~S[~r/Bar Baz/]
assert_same ~S[~w<>]
assert_same ~S[~W()]
end
test "with escapes" do
assert_same ~S[~s(foo \) bar)]
assert_same ~S[~s(f\a\b\ro)]
assert_same ~S"""
~S(foo\
bar)
"""
end
test "with nested new lines" do
assert_same ~S"""
foo do
~S(foo\
bar)
end
"""
assert_same ~S"""
foo do
~s(#{bar}
)
end
"""
end
test "with interpolation" do
assert_same ~S[~s(one #{2} three)]
end
test "with modifiers" do
assert_same ~S[~w(one two three)a]
assert_same ~S[~z(one two three)foo]
end
test "with interpolation on line limit" do
bad = ~S"""
~s(one #{"two"} three)
"""
good = ~S"""
~s(one #{
"two"
} three)
"""
assert_format bad, good, @short_length
end
test "with heredoc syntax" do
assert_same ~S"""
~s'''
one\a
#{:two}\r
three\0
'''
"""
assert_same ~S'''
~s"""
one\a
#{:two}\r
three\0
"""
'''
end
test "with heredoc syntax and modifier" do
assert_same ~S"""
~s'''
foo
'''rsa
"""
end
test "with heredoc syntax and interpolation on line limit" do
bad = ~S"""
~s'''
one #{"two two"} three
'''
"""
good = ~S"""
~s'''
one #{
"two two"
} three
'''
"""
assert_format bad, good, @short_length
end
end
describe "anonymous functions" do
test "with a single clause and no arguments" do
assert_format "fn ->:ok end", "fn -> :ok end"
bad = "fn -> :foo end"
good = """
fn ->
:foo
end
"""
assert_format bad, good, @short_length
assert_same "fn () when node() == :nonode@nohost -> true end"
end
test "with a single clause and arguments" do
assert_format "fn x ,y-> x + y end", "fn x, y -> x + y end"
bad = "fn x -> foo(x) end"
good = """
fn x ->
foo(x)
end
"""
assert_format bad, good, @short_length
bad = "fn one, two, three -> foo(x) end"
good = """
fn one,
two,
three ->
foo(x)
end
"""
assert_format bad, good, @short_length
end
test "with a single clause and when" do
code = """
fn arg
when guard ->
:ok
end
"""
assert_same code, @short_length
end
test "with multiple clauses" do
code = """
fn
1 -> :ok
2 -> :ok
end
"""
assert_same code, @short_length
code = """
fn
1 ->
:ok
2 ->
:error
end
"""
assert_same code, @short_length
code = """
fn
arg11,
arg12 ->
body1
arg21,
arg22 ->
body2
end
"""
assert_same code, @short_length
code = """
fn
arg11,
arg12 ->
body1
arg21,
arg22 ->
body2
arg31,
arg32 ->
body3
end
"""
assert_same code, @short_length
end
test "with heredocs" do
assert_same """
fn
arg1 ->
'''
foo
'''
arg2 ->
'''
bar
'''
end
"""
end
test "with multiple empty clauses" do
assert_same """
fn
() -> :ok1
() -> :ok2
end
"""
end
test "with when in clauses" do
assert_same """
fn
a1 when a + b -> :ok
b1 when c + d -> :ok
end
"""
long = """
fn
a1, a2 when a + b -> :ok
b1, b2 when c + d -> :ok
end
"""
assert_same long
good = """
fn
a1, a2
when a +
b ->
:ok
b1, b2
when c +
d ->
:ok
end
"""
assert_format long, good, @short_length
end
test "uses block context for the body of each clause" do
assert_same "fn -> @foo bar end"
end
test "preserves user choice even when it fits" do
assert_same """
fn
1 ->
:ok
2 ->
:ok
end
"""
assert_same """
fn
1 ->
:ok
2 ->
:ok
3 ->
:ok
end
"""
end
end
describe "anonymous functions types" do
test "with a single clause and no arguments" do
assert_format "(->:ok)", "(() -> :ok)"
assert_same "(() -> :really_long_atom)", @short_length
assert_same "(() when node() == :nonode@nohost -> true)"
end
test "with a single clause and arguments" do
assert_format "( x ,y-> x + y )", "(x, y -> x + y)"
bad = "(x -> :really_long_atom)"
good = """
(x ->
:really_long_atom)
"""
assert_format bad, good, @short_length
bad = "(one, two, three -> foo(x))"
good = """
(one,
two,
three ->
foo(x))
"""
assert_format bad, good, @short_length
end
test "with multiple clauses" do
code = """
(
1 -> :ok
2 -> :ok
)
"""
assert_same code, @short_length
code = """
(
1 ->
:ok
2 ->
:error
)
"""
assert_same code, @short_length
code = """
(
arg11,
arg12 ->
body1
arg21,
arg22 ->
body2
)
"""
assert_same code, @short_length
code = """
(
arg11,
arg12 ->
body1
arg21,
arg22 ->
body2
arg31,
arg32 ->
body2
)
"""
assert_same code, @short_length
end
test "with heredocs" do
assert_same """
(
arg1 ->
'''
foo
'''
arg2 ->
'''
bar
'''
)
"""
end
test "with multiple empty clauses" do
assert_same """
(
() -> :ok1
() -> :ok2
)
"""
end
test "preserves user choice even when it fits" do
assert_same """
(
1 ->
:ok
2 ->
:ok
)
"""
assert_same """
(
1 ->
:ok
2 ->
:ok
3 ->
:ok
)
"""
end
end
describe "blocks" do
test "with multiple lines" do
assert_same """
foo = bar
baz = bat
"""
end
test "with multiple lines with line limit" do
code = """
foo =
bar(one)
baz =
bat(two)
a(b)
"""
assert_same code, @short_length
code = """
foo =
bar(one)
a(b)
baz =
bat(two)
"""
assert_same code, @short_length
code = """
a(b)
foo =
bar(one)
baz =
bat(two)
"""
assert_same code, @short_length
code = """
foo =
bar(one)
one =
two(ghi)
baz =
bat(two)
"""
assert_same code, @short_length
end
test "with multiple lines with line limit inside block" do
code = """
block do
a =
b(foo)
c =
d(bar)
e =
f(baz)
end
"""
assert_same code, @short_length
end
test "with multiple lines with cancel expressions" do
code = """
foo(%{
key: 1
})
bar(%{
key: 1
})
baz(%{
key: 1
})
"""
assert_same code, @short_length
end
test "with heredoc" do
assert_same """
block do
'''
a
b
c
'''
end
"""
end
test "keeps user newlines" do
assert_same """
defmodule Mod do
field(:foo)
field(:bar)
field(:baz)
belongs_to(:one)
belongs_to(:two)
timestamp()
lock()
has_many(:three)
has_many(:four)
:ok
has_one(:five)
has_one(:six)
foo = 1
bar = 2
:before
baz = 3
:after
end
"""
bad = """
defmodule Mod do
field(:foo)
field(:bar)
field(:baz)
belongs_to(:one)
belongs_to(:two)
timestamp()
lock()
has_many(:three)
has_many(:four)
:ok
has_one(:five)
has_one(:six)
foo = 1
bar = 2
:before
baz = 3
:after
end
"""
good = """
defmodule Mod do
field(:foo)
field(:bar)
field(:baz)
belongs_to(:one)
belongs_to(:two)
timestamp()
lock()
has_many(:three)
has_many(:four)
:ok
has_one(:five)
has_one(:six)
foo = 1
bar = 2
:before
baz = 3
:after
end
"""
assert_format bad, good
end
test "with multiple defs" do
assert_same """
def foo(:one), do: 1
def foo(:two), do: 2
def foo(:three), do: 3
"""
end
test "with module attributes" do
assert_same """
defmodule Foo do
@constant 1
@constant 2
@doc '''
foo
'''
def foo do
:ok
end
@spec bar :: 1
@spec bar :: 2
def bar do
:ok
end
@other_constant 3
@spec baz :: 4
@doc '''
baz
'''
def baz do
:ok
end
@another_constant 5
@another_constant 5
@doc '''
baz
'''
@spec baz :: 6
def baz do
:ok
end
end
"""
end
test "as function arguments" do
assert_same """
fun(
(
foo
bar
)
)
"""
assert_same """
assert true,
do:
(
foo
bar
)
"""
end
end
describe "renames deprecated calls" do
test "without deprecation option" do
assert_same "Enum.partition(foo, bar)"
assert_same "&Enum.partition/2"
end
test "with matching deprecation option" do
assert_format "Enum.partition(foo, bar)", "Enum.split_with(foo, bar)",
rename_deprecated_at: "1.4.0"
assert_format "Enum.partition(foo, bar)", "Enum.split_with(foo, bar)",
rename_deprecated_at: "1.4.0"
end
test "without matching deprecation option" do
assert_same "Enum.partition(foo, bar)", rename_deprecated_at: "1.3.0"
assert_same "Enum.partition(foo, bar)", rename_deprecated_at: "1.3.0"
end
test "raises on invalid version" do
assert_raise ArgumentError, ~r"invalid version", fn ->
assert_same "Enum.partition(foo, bar)", rename_deprecated_at: "1.3"
end
end
end
end
| 15.769032 | 76 | 0.435562 |
e810584251a8ea40ade18211d75e1ba4a8e72439 | 986 | ex | Elixir | lib/calculator/operations/entities/operation.ex | kadmohardy/calculator | 671e0d6c6c8d7ef7fba75b7f47a76aaeb29eaf7e | [
"MIT"
] | null | null | null | lib/calculator/operations/entities/operation.ex | kadmohardy/calculator | 671e0d6c6c8d7ef7fba75b7f47a76aaeb29eaf7e | [
"MIT"
] | null | null | null | lib/calculator/operations/entities/operation.ex | kadmohardy/calculator | 671e0d6c6c8d7ef7fba75b7f47a76aaeb29eaf7e | [
"MIT"
] | null | null | null | defmodule Calculator.Operations.Entities.Operation do
@moduledoc false
use Ecto.Schema
import Ecto.Changeset
@primary_key {:id, :binary_id, autogenerate: true}
@derive {Phoenix.Param, key: :id}
schema "operations" do
field :number_one, :decimal
field :number_two, :decimal
field :result, :decimal
field :type, :string
field :status, :string, default: false
timestamps()
end
@doc false
def changeset(operation, attrs) do
operation
|> cast(attrs, [:number_one, :number_two, :type, :status, :result])
|> validate_required([:number_one, :number_two, :type, :status])
|> validate_required([:number_one, :number_two, :type], message: "O parâmetro é obrigatório")
|> validate_inclusion(:type, ["soma", "subtracao", "multiplicacao", "divisao"],
message:
"Por favor, escolha uma das seguintes operaçoes: soma, subtracao, multiplica, divisao"
)
|> validate_inclusion(:status, ["sucesso", "falha"])
end
end
| 30.8125 | 97 | 0.681542 |
e810b9c746735000e05574472aa8cc398ece798d | 495 | exs | Elixir | apps/bookmarker/test/models/bookmark_test.exs | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 4 | 2019-10-04T16:11:15.000Z | 2021-08-18T21:00:13.000Z | apps/bookmarker/test/models/bookmark_test.exs | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | 5 | 2020-03-16T23:52:25.000Z | 2021-09-03T16:52:17.000Z | apps/bookmarker/test/models/bookmark_test.exs | allen-garvey/phoenix-umbrella | 1d444bbd62a5e7b5f51d317ce2be71ee994125d5 | [
"MIT"
] | null | null | null | defmodule Bookmarker.BookmarkTest do
use Bookmarker.ModelCase
alias Bookmarker.Bookmark
@valid_attrs %{description: "some content", title: "some content", url: "some content"}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = Bookmark.changeset(%Bookmark{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = Bookmark.changeset(%Bookmark{}, @invalid_attrs)
refute changeset.valid?
end
end
| 26.052632 | 89 | 0.737374 |
e810f8417bdef03fa8e5667bf1a9f4ad5f7929de | 407 | ex | Elixir | lib/ex_oauth2_provider/utils.ex | gozego/ex_oauth2_provider | d3a7658d28233dda2dfdef7ed397b5b440a2f737 | [
"Unlicense",
"MIT"
] | 2 | 2021-04-25T20:59:53.000Z | 2021-07-13T22:49:20.000Z | lib/ex_oauth2_provider/utils.ex | gozego/ex_oauth2_provider | d3a7658d28233dda2dfdef7ed397b5b440a2f737 | [
"Unlicense",
"MIT"
] | null | null | null | lib/ex_oauth2_provider/utils.ex | gozego/ex_oauth2_provider | d3a7658d28233dda2dfdef7ed397b5b440a2f737 | [
"Unlicense",
"MIT"
] | null | null | null | defmodule ExOauth2Provider.Utils do
@moduledoc false
@doc false
def remove_empty_values(map) when is_map(map) do
map
|> Enum.filter(fn {_, v} -> v != nil && v != "" end)
|> Enum.into(%{})
end
@doc false
def generate_token(opts \\ %{}) do
token_size = Map.get(opts, :size, 32)
string = :crypto.strong_rand_bytes(token_size)
Base.encode16(string, case: :lower)
end
end
| 22.611111 | 56 | 0.636364 |
e81100a5842564325b751252a1d84008a6040b36 | 2,548 | ex | Elixir | jena-core/etc/location-mapping.ex | Hendrikto/jena | 9a6de9d7295c2068904e2b464de72364c4d64117 | [
"Apache-2.0"
] | null | null | null | jena-core/etc/location-mapping.ex | Hendrikto/jena | 9a6de9d7295c2068904e2b464de72364c4d64117 | [
"Apache-2.0"
] | 1 | 2022-03-08T21:14:28.000Z | 2022-03-08T21:14:28.000Z | jena-core/etc/location-mapping.ex | Hendrikto/jena | 9a6de9d7295c2068904e2b464de72364c4d64117 | [
"Apache-2.0"
] | 1 | 2020-06-11T12:26:06.000Z | 2020-06-11T12:26:06.000Z | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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.
## EXAMPLE
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix lm: <http://jena.hpl.hp.com/2004/08/location-mapping#> .
# Application location to alternative location mappings.
#
# + Order does not matter.
# + The location mapping parser looks for lm:mapping properties
# and uses the object value so this can be written in several different styles.
#
# The translation algorithm is:
#
# 1 - Exact mappings: these are tried before attempting a prefix match.
# 2 - By prefix: find the longest matching prefix
# 3 - Use the original if no alternative.
# Use N3's , (multiple objects => multiple statements of same subject and predicate)
# Note the commas
## -- Example 1
[] lm:mapping
[ lm:name "file:foo.ttl" ; lm:altName "file:etc/foo.ttl" ] ,
[ lm:prefix "file:etc/" ; lm:altPrefix "file:ETC/" ] ,
[ lm:name "file:etc/foo.ttl" ; lm:altName "file:DIR/foo.ttl" ] ,
.
## -- Example 2
# This is exactly the same graph using the ; syntax of N3
# Multiple statements with the same subject - and we used the same predicate.
## [] lm:mapping [ lm:name "file:foo.ttl" ; lm:altName "file:etc/foo.ttl" ] ;
## lm:mapping [ lm:prefix "file:etc/" ; lm:altPrefix "file:ETC/" ] ;
## lm:mapping [ lm:name "file:etc/foo.ttl" ; lm:altName "file:DIR/foo.ttl" ] ;
## .
## -- Example 3
# Different graph - same effect. The fact there are different subjects is immaterial.
## [] lm:mapping [ lm:name "file:foo.ttl" ; lm:altName "file:etc/foo.ttl" ] .
## [] lm:mapping [ lm:prefix "file:etc/" ; lm:altPrefix "file:ETC/" ] .
## [] lm:mapping [ lm:name "file:etc/foo.ttl" ; lm:altName "file:DIR/foo.ttl" ] .
| 39.8125 | 86 | 0.69427 |
e8113189af7de9cbe900b720c1ca6de493aa3231 | 851 | exs | Elixir | test/bitcoin/node/network/addr_test.exs | coinscript/bitcoinsv-elixir | 2dda03c81edc5662743ed2922abb5b1910d9c09a | [
"Apache-2.0"
] | 2 | 2019-08-12T04:53:57.000Z | 2019-09-03T03:47:33.000Z | test/bitcoin/node/network/addr_test.exs | coinscript/bitcoinsv-elixir | 2dda03c81edc5662743ed2922abb5b1910d9c09a | [
"Apache-2.0"
] | null | null | null | test/bitcoin/node/network/addr_test.exs | coinscript/bitcoinsv-elixir | 2dda03c81edc5662743ed2922abb5b1910d9c09a | [
"Apache-2.0"
] | null | null | null | defmodule Bitcoin.Node.Network.AddrTest do
use ExUnit.Case
alias Bitcoin.Node.Network.Addr
alias Bitcoin.Protocol.Types.NetworkAddress, as: NA
test "addrs management" do
{:ok, node_pid} = Bitcoin.Node.start_link()
{:ok, addr_pid} = Addr.start_link()
Addr.clear()
assert Addr.count() == 0
assert Addr.get() == nil
na1 = %NA{address: {1, 2, 3, 4}}
na2 = %NA{address: {1, 2, 3, 5}}
na1 |> Addr.add()
assert Addr.count() == 1
assert Addr.get() == na1
na2 |> Addr.add()
assert Addr.count() == 2
# couldn't figure out how to force :rand.seed (it seems to be local per process?)
results = 1..100 |> Enum.reduce(MapSet.new(), fn _x, r -> r |> MapSet.put(Addr.get()) end)
assert results == MapSet.new([na1, na2])
node_pid |> GenServer.stop()
addr_pid |> GenServer.stop()
end
end
| 30.392857 | 94 | 0.620447 |
e8113b5a6be7ff9ffa2d3048150f38038be740fb | 1,979 | ex | Elixir | clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_ban_snippet.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_ban_snippet.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/you_tube/lib/google_api/you_tube/v3/model/live_chat_ban_snippet.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.YouTube.V3.Model.LiveChatBanSnippet do
@moduledoc """
## Attributes
* `banDurationSeconds` (*type:* `String.t`, *default:* `nil`) - The duration of a ban, only filled if the ban has type TEMPORARY.
* `bannedUserDetails` (*type:* `GoogleApi.YouTube.V3.Model.ChannelProfileDetails.t`, *default:* `nil`) -
* `liveChatId` (*type:* `String.t`, *default:* `nil`) - The chat this ban is pertinent to.
* `type` (*type:* `String.t`, *default:* `nil`) - The type of ban.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:banDurationSeconds => String.t(),
:bannedUserDetails => GoogleApi.YouTube.V3.Model.ChannelProfileDetails.t(),
:liveChatId => String.t(),
:type => String.t()
}
field(:banDurationSeconds)
field(:bannedUserDetails, as: GoogleApi.YouTube.V3.Model.ChannelProfileDetails)
field(:liveChatId)
field(:type)
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.LiveChatBanSnippet do
def decode(value, options) do
GoogleApi.YouTube.V3.Model.LiveChatBanSnippet.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.LiveChatBanSnippet do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.339286 | 133 | 0.713997 |
e8113b64f59a861705a31c45cbf501c0820574b9 | 6,073 | exs | Elixir | test/models/account_test.exs | cedretaber/bibliotheca | 642ec9908d6d98f16e25b6a482c52e9cbaa21ad2 | [
"MIT"
] | null | null | null | test/models/account_test.exs | cedretaber/bibliotheca | 642ec9908d6d98f16e25b6a482c52e9cbaa21ad2 | [
"MIT"
] | 22 | 2017-05-15T07:34:08.000Z | 2018-02-25T07:26:18.000Z | test/models/account_test.exs | cedretaber/bibliotheca | 642ec9908d6d98f16e25b6a482c52e9cbaa21ad2 | [
"MIT"
] | null | null | null | defmodule Bibliotheca.AccountTest do
use Bibliotheca.ModelCase
alias Bibliotheca.{Account, User}
@valid_attr %{name: "account1"}
@account %Account{
id: 1,
name: "account1",
inserted_at: ~N[2015-04-01 12:00:00],
updated_at: ~N[2015-04-01 12:00:00]
}
@user %User{
id: 1,
email: "test@example.com",
password_digest: "hogehogefufgafuga",
auth_code: "ADMIN",
inserted_at: ~N[2015-04-01 12:00:00],
updated_at: ~N[2015-04-01 12:00:00]
}
describe "changeset" do
test "changeset with valid attributes." do
changeset = Account.changeset(%Account{}, @valid_attr)
assert changeset.valid?
end
test "changeset with valid attributes and users." do
users = [@user]
changeset = Account.changeset(%Account{}, @valid_attr, users)
assert changeset.valid?
end
test "changeset with invalid attributes." do
invalid_attr = %{}
changeset = Account.changeset(%Account{}, invalid_attr)
refute changeset.valid?
end
end
describe "all" do
test "query all accounts." do
account1 = @account
account2 = %Account{account1 | id: 2, name: "account2"}
account3 = %Account{account1 | id: 3, name: "account3"}
list = [account1, account2, account3]
list
|> Enum.each(fn account -> Repo.insert!(account) end)
Account.all()
|> Enum.zip(list)
|> Enum.each(fn {ret, exp} -> assert ret.name == exp.name end)
end
test "query all undeleted accounts." do
account1 = %Account{
id: 1,
name: "account1",
inserted_at: ~N[2015-04-01 12:00:00],
updated_at: ~N[2015-04-01 12:00:00]
}
account2 = %Account{account1 | id: 2, name: "account2", deleted_at: ~N[2016-04-01 12:00:00]}
account3 = %Account{account1 | id: 3, name: "account3"}
list = [account1, account2, account3]
list
|> Enum.each(fn account -> Repo.insert!(cast(account, %{}, [])) end)
list = [account1, account3]
Account.all()
|> Enum.zip(list)
|> Enum.each(fn {ret, exp} -> assert ret.name == exp.name end)
end
test "return empty list when there are no account." do
assert Enum.empty?(Account.all())
end
test "get all accounts with users." do
user1 = @user
user2 = %User{user1 | id: 2, email: "test2@example.com"}
user3 = %User{user1 | id: 3, email: "test3@example.com"}
[user1, user2, user3]
|> Enum.each(fn user -> Repo.insert!(user) end)
account1 = %Account{
id: 1,
name: "account1",
inserted_at: ~N[2015-04-01 12:00:00],
updated_at: ~N[2015-04-01 12:00:00]
}
account2 = %Account{account1 | id: 2, name: "account2"}
account3 = %Account{account1 | id: 3, name: "account3"}
list = [account1, account2, account3]
user_assoc = [[1, 2], [2], [3]]
list
|> Enum.zip(user_assoc)
|> Enum.each(fn {account, users} ->
changeset =
account
|> change
|> put_assoc(:users, users |> Enum.map(fn id -> Repo.get(User, id) end))
Repo.insert!(changeset)
end)
Account.all()
|> Enum.zip(list)
|> Enum.zip(user_assoc)
|> Enum.each(fn {{ret, exp}, users} ->
assert ret.name == exp.name
assert length(ret.users) == length(users)
ret.users
|> Enum.zip(users)
|> Enum.each(fn {ret, exp_id} -> assert ret.id == exp_id end)
end)
end
end
@valid_param %{name: "account1"}
describe "create" do
test "create an account without user." do
refute Repo.get_by(Account, name: @valid_param[:name])
assert {:ok, account} = Account.create(@valid_param)
assert account == Repo.get_by(Account, name: @valid_param[:name])
end
test "create an account with user." do
Repo.insert!(@user)
users = [Repo.get(User, @user.id)]
refute Repo.get_by(Account, name: @valid_param[:name])
assert {:ok, account} = Account.create(@valid_param, users)
assert account.users == users
end
test "creation failed with invalid params." do
param = %{}
assert match?({:error, _}, Account.create(param))
end
test "creation failed with ivalid users." do
user = %User{@user | id: 42}
Account.create(@valid_param, [user])
assert match?({:error, _}, Account.create(@valid_param, [user]))
end
end
describe "find" do
test "find an account." do
Repo.insert!(@account)
account = Account.find(@account.id)
assert @account.id == account.id
assert @account.name == account.name
end
test "try to find nonexistent account." do
refute Account.find(42)
end
end
describe "find_by_name" do
test "find an account." do
Repo.insert!(@account)
account = Account.find_by_name(@account.name)
assert @account.id == account.id
assert @account.name == account.name
end
test "try to find nonexistent account." do
refute Account.find_by_name("no such account")
end
end
describe "update" do
test "update an account successfully." do
Repo.insert!(@account)
new_name = "new name"
param = %{"name" => new_name}
assert {:ok, account} = Account.update(@account.id, param)
assert account.name == new_name
account = Repo.get(Account, @account.id)
assert account.name == new_name
end
test "try to update nonexistent account." do
new_name = "new name"
param = %{"name" => new_name}
refute Account.update(42, param)
end
end
describe "delete" do
test "delete an account." do
Repo.insert!(@account)
assert match?({:ok, _}, Account.delete(@account.id))
account = Repo.get(Account, @account.id)
assert account
assert account.deleted_at
refute Account.find(@account.id)
refute Account.find_by_name(@account.name)
end
test "try to delete nonexistent account." do
refute Account.delete(42)
end
end
end
| 26.064378 | 98 | 0.601021 |
e811507cc49b6b9175bb20fa55b21616197cc4b3 | 185 | ex | Elixir | lib/mix/tasks/encrypted_secrets/decrypt.ex | pjo336/encrypted_secrets_ex | 601805067321355ba3a3262fa169f5c973dd7a2c | [
"MIT"
] | null | null | null | lib/mix/tasks/encrypted_secrets/decrypt.ex | pjo336/encrypted_secrets_ex | 601805067321355ba3a3262fa169f5c973dd7a2c | [
"MIT"
] | null | null | null | lib/mix/tasks/encrypted_secrets/decrypt.ex | pjo336/encrypted_secrets_ex | 601805067321355ba3a3262fa169f5c973dd7a2c | [
"MIT"
] | null | null | null | defmodule Mix.Tasks.EncryptedSecrets.Decrypt do
use Mix.Task
def run(args) do
EncryptedSecrets.decrypt() do
:ok -> nil
{:error, err} -> raise err
end
end
end
| 16.818182 | 47 | 0.643243 |
e8115e84a523bcbb189977ee83b6dcb7b73a2a23 | 487 | ex | Elixir | lib/liberator/media_type.ex | Cantido/liberator | fa958699ffc699a350a06dbcac6402b81208f282 | [
"MIT"
] | 36 | 2020-10-03T16:58:57.000Z | 2021-11-27T09:33:51.000Z | lib/liberator/media_type.ex | Cantido/liberator | fa958699ffc699a350a06dbcac6402b81208f282 | [
"MIT"
] | 23 | 2020-10-13T00:23:03.000Z | 2022-03-10T11:05:22.000Z | lib/liberator/media_type.ex | Cantido/liberator | fa958699ffc699a350a06dbcac6402b81208f282 | [
"MIT"
] | 1 | 2020-10-12T20:33:30.000Z | 2020-10-12T20:33:30.000Z | # SPDX-FileCopyrightText: 2021 Rosa Richter
#
# SPDX-License-Identifier: MIT
defmodule Liberator.MediaType do
@moduledoc """
A behaviour module for media type codecs.
Liberator uses this behaviour to help make sure at compile-time that codecs will be called successfully.
Include it in your own module for the same peace of mind.
"""
@doc """
Encode an Elixir term into an encoded binary, and raise if there's an error.
"""
@callback encode!(term()) :: binary()
end
| 27.055556 | 106 | 0.726899 |
e8119bc47a609883bab8d99cbbf8bd383544ebb1 | 837 | ex | Elixir | lib/pile/extras/map_x.ex | jesseshieh/crit19 | 0bba407fea09afed72cbb90ca579ba34c537edef | [
"MIT"
] | null | null | null | lib/pile/extras/map_x.ex | jesseshieh/crit19 | 0bba407fea09afed72cbb90ca579ba34c537edef | [
"MIT"
] | null | null | null | lib/pile/extras/map_x.ex | jesseshieh/crit19 | 0bba407fea09afed72cbb90ca579ba34c537edef | [
"MIT"
] | null | null | null | defmodule MapX do
def just?(map, key) do
Map.fetch!(map, key) != :nothing
end
def just!(map, key) do
if just?(map, key) do
Map.fetch!(map, key)
else
raise("#{inspect map} has a blank key: #{inspect key}")
end
end
# Taken from ex_machina.
def convert_atom_keys_to_strings(values) when is_list(values) do
Enum.map(values, &convert_atom_keys_to_strings/1)
end
def convert_atom_keys_to_strings(%{__struct__: _} = record) when is_map(record) do
Map.from_struct(record) |> convert_atom_keys_to_strings()
end
def convert_atom_keys_to_strings(record) when is_map(record) do
Enum.reduce(record, Map.new(), fn {key, value}, acc ->
Map.put(acc, to_string(key), convert_atom_keys_to_strings(value))
end)
end
def convert_atom_keys_to_strings(value), do: value
end
| 25.363636 | 84 | 0.689367 |
e811a437b0bfcfc5de5809d7336f413b23f3cef0 | 22,553 | ex | Elixir | clients/container/lib/google_api/container/v1/model/cluster.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/container/lib/google_api/container/v1/model/cluster.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/container/lib/google_api/container/v1/model/cluster.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.Container.V1.Model.Cluster do
@moduledoc """
A Google Kubernetes Engine cluster.
## Attributes
* `authenticatorGroupsConfig` (*type:* `GoogleApi.Container.V1.Model.AuthenticatorGroupsConfig.t`, *default:* `nil`) - Configuration controlling RBAC group membership information.
* `meshCertificates` (*type:* `GoogleApi.Container.V1.Model.MeshCertificates.t`, *default:* `nil`) - Configuration for issuance of mTLS keys and certificates to Kubernetes pods.
* `clusterIpv4Cidr` (*type:* `String.t`, *default:* `nil`) - The IP address range of the container pods in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `10.96.0.0/14`). Leave blank to have one automatically chosen or specify a `/14` block in `10.0.0.0/8`.
* `instanceGroupUrls` (*type:* `list(String.t)`, *default:* `nil`) - Deprecated. Use node_pools.instance_group_urls.
* `currentMasterVersion` (*type:* `String.t`, *default:* `nil`) - [Output only] The current software version of the master endpoint.
* `enableTpu` (*type:* `boolean()`, *default:* `nil`) - Enable the ability to use Cloud TPUs in this cluster.
* `nodeIpv4CidrSize` (*type:* `integer()`, *default:* `nil`) - [Output only] The size of the address space on each node for hosting containers. This is provisioned from within the `container_ipv4_cidr` range. This field will only be set when cluster is in route-based network mode.
* `legacyAbac` (*type:* `GoogleApi.Container.V1.Model.LegacyAbac.t`, *default:* `nil`) - Configuration for the legacy ABAC authorization mode.
* `shieldedNodes` (*type:* `GoogleApi.Container.V1.Model.ShieldedNodes.t`, *default:* `nil`) - Shielded Nodes configuration.
* `statusMessage` (*type:* `String.t`, *default:* `nil`) - [Output only] Deprecated. Use conditions instead. Additional information about the current status of this cluster, if available.
* `createTime` (*type:* `String.t`, *default:* `nil`) - [Output only] The time the cluster was created, in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format.
* `currentNodeVersion` (*type:* `String.t`, *default:* `nil`) - [Output only] Deprecated, use [NodePools.version](https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters.nodePools) instead. The current version of the node software components. If they are currently at multiple versions because they're in the process of being upgraded, this reflects the minimum version of all nodes.
* `autoscaling` (*type:* `GoogleApi.Container.V1.Model.ClusterAutoscaling.t`, *default:* `nil`) - Cluster-level autoscaling configuration.
* `conditions` (*type:* `list(GoogleApi.Container.V1.Model.StatusCondition.t)`, *default:* `nil`) - Which conditions caused the current cluster state.
* `monitoringService` (*type:* `String.t`, *default:* `nil`) - The monitoring service the cluster should use to write metrics. Currently available options: * "monitoring.googleapis.com/kubernetes" - The Cloud Monitoring service with a Kubernetes-native resource model * `monitoring.googleapis.com` - The legacy Cloud Monitoring service (no longer available as of GKE 1.15). * `none` - No metrics will be exported from the cluster. If left as an empty string,`monitoring.googleapis.com/kubernetes` will be used for GKE 1.14+ or `monitoring.googleapis.com` for earlier versions.
* `workloadIdentityConfig` (*type:* `GoogleApi.Container.V1.Model.WorkloadIdentityConfig.t`, *default:* `nil`) - Configuration for the use of Kubernetes Service Accounts in GCP IAM policies.
* `zone` (*type:* `String.t`, *default:* `nil`) - [Output only] The name of the Google Compute Engine [zone](https://cloud.google.com/compute/docs/zones#available) in which the cluster resides. This field is deprecated, use location instead.
* `description` (*type:* `String.t`, *default:* `nil`) - An optional description of this cluster.
* `privateClusterConfig` (*type:* `GoogleApi.Container.V1.Model.PrivateClusterConfig.t`, *default:* `nil`) - Configuration for private cluster.
* `enableKubernetesAlpha` (*type:* `boolean()`, *default:* `nil`) - Kubernetes alpha features are enabled on this cluster. This includes alpha API groups (e.g. v1alpha1) and features that may not be production ready in the kubernetes version of the master and nodes. The cluster has no SLA for uptime and master/node upgrades are disabled. Alpha enabled clusters are automatically deleted thirty days after creation.
* `loggingConfig` (*type:* `GoogleApi.Container.V1.Model.LoggingConfig.t`, *default:* `nil`) - Logging configuration for the cluster.
* `loggingService` (*type:* `String.t`, *default:* `nil`) - The logging service the cluster should use to write logs. Currently available options: * `logging.googleapis.com/kubernetes` - The Cloud Logging service with a Kubernetes-native resource model * `logging.googleapis.com` - The legacy Cloud Logging service (no longer available as of GKE 1.15). * `none` - no logs will be exported from the cluster. If left as an empty string,`logging.googleapis.com/kubernetes` will be used for GKE 1.14+ or `logging.googleapis.com` for earlier versions.
* `resourceUsageExportConfig` (*type:* `GoogleApi.Container.V1.Model.ResourceUsageExportConfig.t`, *default:* `nil`) - Configuration for exporting resource usages. Resource usage export is disabled when this config is unspecified.
* `endpoint` (*type:* `String.t`, *default:* `nil`) - [Output only] The IP address of this cluster's master endpoint. The endpoint can be accessed from the internet at `https://username:password@endpoint/`. See the `masterAuth` property of this resource for username and password information.
* `initialNodeCount` (*type:* `integer()`, *default:* `nil`) - The number of nodes to create in this cluster. You must ensure that your Compute Engine [resource quota](https://cloud.google.com/compute/quotas) is sufficient for this number of instances. You must also have available firewall and routes quota. For requests, this field should only be used in lieu of a "node_pool" object, since this configuration (along with the "node_config") will be used to create a "NodePool" object with an auto-generated name. Do not use this and a node_pool at the same time. This field is deprecated, use node_pool.initial_node_count instead.
* `networkConfig` (*type:* `GoogleApi.Container.V1.Model.NetworkConfig.t`, *default:* `nil`) - Configuration for cluster networking.
* `masterAuthorizedNetworksConfig` (*type:* `GoogleApi.Container.V1.Model.MasterAuthorizedNetworksConfig.t`, *default:* `nil`) - The configuration options for master authorized networks feature.
* `networkPolicy` (*type:* `GoogleApi.Container.V1.Model.NetworkPolicy.t`, *default:* `nil`) - Configuration options for the NetworkPolicy feature.
* `name` (*type:* `String.t`, *default:* `nil`) - The name of this cluster. The name must be unique within this project and location (e.g. zone or region), and can be up to 40 characters with the following restrictions: * Lowercase letters, numbers, and hyphens only. * Must start with a letter. * Must end with a number or a letter.
* `releaseChannel` (*type:* `GoogleApi.Container.V1.Model.ReleaseChannel.t`, *default:* `nil`) - Release channel configuration.
* `masterAuth` (*type:* `GoogleApi.Container.V1.Model.MasterAuth.t`, *default:* `nil`) - The authentication information for accessing the master endpoint. If unspecified, the defaults are used: For clusters before v1.12, if master_auth is unspecified, `username` will be set to "admin", a random password will be generated, and a client certificate will be issued.
* `location` (*type:* `String.t`, *default:* `nil`) - [Output only] The name of the Google Compute Engine [zone](https://cloud.google.com/compute/docs/regions-zones/regions-zones#available) or [region](https://cloud.google.com/compute/docs/regions-zones/regions-zones#available) in which the cluster resides.
* `subnetwork` (*type:* `String.t`, *default:* `nil`) - The name of the Google Compute Engine [subnetwork](https://cloud.google.com/compute/docs/subnetworks) to which the cluster is connected.
* `status` (*type:* `String.t`, *default:* `nil`) - [Output only] The current status of this cluster.
* `network` (*type:* `String.t`, *default:* `nil`) - The name of the Google Compute Engine [network](https://cloud.google.com/compute/docs/networks-and-firewalls#networks) to which the cluster is connected. If left unspecified, the `default` network will be used.
* `nodeConfig` (*type:* `GoogleApi.Container.V1.Model.NodeConfig.t`, *default:* `nil`) - Parameters used in creating the cluster's nodes. For requests, this field should only be used in lieu of a "node_pool" object, since this configuration (along with the "initial_node_count") will be used to create a "NodePool" object with an auto-generated name. Do not use this and a node_pool at the same time. For responses, this field will be populated with the node configuration of the first node pool. (For configuration of each node pool, see `node_pool.config`) If unspecified, the defaults are used. This field is deprecated, use node_pool.config instead.
* `tpuIpv4CidrBlock` (*type:* `String.t`, *default:* `nil`) - [Output only] The IP address range of the Cloud TPUs in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`).
* `ipAllocationPolicy` (*type:* `GoogleApi.Container.V1.Model.IPAllocationPolicy.t`, *default:* `nil`) - Configuration for cluster IP allocation.
* `addonsConfig` (*type:* `GoogleApi.Container.V1.Model.AddonsConfig.t`, *default:* `nil`) - Configurations for the various addons available to run in the cluster.
* `locations` (*type:* `list(String.t)`, *default:* `nil`) - The list of Google Compute Engine [zones](https://cloud.google.com/compute/docs/zones#available) in which the cluster's nodes should be located. This field provides a default value if [NodePool.Locations](https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters.nodePools#NodePool.FIELDS.locations) are not specified during node pool creation. Warning: changing cluster locations will update the [NodePool.Locations](https://cloud.google.com/kubernetes-engine/docs/reference/rest/v1/projects.locations.clusters.nodePools#NodePool.FIELDS.locations) of all node pools and will result in nodes being added and/or removed.
* `autopilot` (*type:* `GoogleApi.Container.V1.Model.Autopilot.t`, *default:* `nil`) - Autopilot configuration for the cluster.
* `resourceLabels` (*type:* `map()`, *default:* `nil`) - The resource labels for the cluster to use to annotate any related Google Compute Engine resources.
* `labelFingerprint` (*type:* `String.t`, *default:* `nil`) - The fingerprint of the set of labels for this cluster.
* `expireTime` (*type:* `String.t`, *default:* `nil`) - [Output only] The time the cluster will be automatically deleted in [RFC3339](https://www.ietf.org/rfc/rfc3339.txt) text format.
* `currentNodeCount` (*type:* `integer()`, *default:* `nil`) - [Output only] The number of nodes currently in the cluster. Deprecated. Call Kubernetes API directly to retrieve node information.
* `defaultMaxPodsConstraint` (*type:* `GoogleApi.Container.V1.Model.MaxPodsConstraint.t`, *default:* `nil`) - The default constraint on the maximum number of pods that can be run simultaneously on a node in the node pool of this cluster. Only honored if cluster created with IP Alias support.
* `notificationConfig` (*type:* `GoogleApi.Container.V1.Model.NotificationConfig.t`, *default:* `nil`) - Notification configuration of the cluster.
* `binaryAuthorization` (*type:* `GoogleApi.Container.V1.Model.BinaryAuthorization.t`, *default:* `nil`) - Configuration for Binary Authorization.
* `monitoringConfig` (*type:* `GoogleApi.Container.V1.Model.MonitoringConfig.t`, *default:* `nil`) - Monitoring configuration for the cluster.
* `initialClusterVersion` (*type:* `String.t`, *default:* `nil`) - The initial Kubernetes version for this cluster. Valid versions are those found in validMasterVersions returned by getServerConfig. The version can be upgraded over time; such upgrades are reflected in currentMasterVersion and currentNodeVersion. Users may specify either explicit versions offered by Kubernetes Engine or version aliases, which have the following behavior: - "latest": picks the highest valid Kubernetes version - "1.X": picks the highest valid patch+gke.N patch in the 1.X version - "1.X.Y": picks the highest valid gke.N patch in the 1.X.Y version - "1.X.Y-gke.N": picks an explicit Kubernetes version - "","-": picks the default Kubernetes version
* `id` (*type:* `String.t`, *default:* `nil`) - Output only. Unique id for the cluster.
* `nodePoolDefaults` (*type:* `GoogleApi.Container.V1.Model.NodePoolDefaults.t`, *default:* `nil`) - Default NodePool settings for the entire cluster. These settings are overridden if specified on the specific NodePool object.
* `nodePools` (*type:* `list(GoogleApi.Container.V1.Model.NodePool.t)`, *default:* `nil`) - The node pools associated with this cluster. This field should not be set if "node_config" or "initial_node_count" are specified.
* `selfLink` (*type:* `String.t`, *default:* `nil`) - [Output only] Server-defined URL for the resource.
* `servicesIpv4Cidr` (*type:* `String.t`, *default:* `nil`) - [Output only] The IP address range of the Kubernetes services in this cluster, in [CIDR](http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing) notation (e.g. `1.2.3.4/29`). Service addresses are typically put in the last `/16` from the container CIDR.
* `databaseEncryption` (*type:* `GoogleApi.Container.V1.Model.DatabaseEncryption.t`, *default:* `nil`) - Configuration of etcd encryption.
* `maintenancePolicy` (*type:* `GoogleApi.Container.V1.Model.MaintenancePolicy.t`, *default:* `nil`) - Configure the maintenance policy for this cluster.
* `confidentialNodes` (*type:* `GoogleApi.Container.V1.Model.ConfidentialNodes.t`, *default:* `nil`) - Configuration of Confidential Nodes
* `verticalPodAutoscaling` (*type:* `GoogleApi.Container.V1.Model.VerticalPodAutoscaling.t`, *default:* `nil`) - Cluster-level Vertical Pod Autoscaling configuration.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:authenticatorGroupsConfig =>
GoogleApi.Container.V1.Model.AuthenticatorGroupsConfig.t() | nil,
:meshCertificates => GoogleApi.Container.V1.Model.MeshCertificates.t() | nil,
:clusterIpv4Cidr => String.t() | nil,
:instanceGroupUrls => list(String.t()) | nil,
:currentMasterVersion => String.t() | nil,
:enableTpu => boolean() | nil,
:nodeIpv4CidrSize => integer() | nil,
:legacyAbac => GoogleApi.Container.V1.Model.LegacyAbac.t() | nil,
:shieldedNodes => GoogleApi.Container.V1.Model.ShieldedNodes.t() | nil,
:statusMessage => String.t() | nil,
:createTime => String.t() | nil,
:currentNodeVersion => String.t() | nil,
:autoscaling => GoogleApi.Container.V1.Model.ClusterAutoscaling.t() | nil,
:conditions => list(GoogleApi.Container.V1.Model.StatusCondition.t()) | nil,
:monitoringService => String.t() | nil,
:workloadIdentityConfig =>
GoogleApi.Container.V1.Model.WorkloadIdentityConfig.t() | nil,
:zone => String.t() | nil,
:description => String.t() | nil,
:privateClusterConfig => GoogleApi.Container.V1.Model.PrivateClusterConfig.t() | nil,
:enableKubernetesAlpha => boolean() | nil,
:loggingConfig => GoogleApi.Container.V1.Model.LoggingConfig.t() | nil,
:loggingService => String.t() | nil,
:resourceUsageExportConfig =>
GoogleApi.Container.V1.Model.ResourceUsageExportConfig.t() | nil,
:endpoint => String.t() | nil,
:initialNodeCount => integer() | nil,
:networkConfig => GoogleApi.Container.V1.Model.NetworkConfig.t() | nil,
:masterAuthorizedNetworksConfig =>
GoogleApi.Container.V1.Model.MasterAuthorizedNetworksConfig.t() | nil,
:networkPolicy => GoogleApi.Container.V1.Model.NetworkPolicy.t() | nil,
:name => String.t() | nil,
:releaseChannel => GoogleApi.Container.V1.Model.ReleaseChannel.t() | nil,
:masterAuth => GoogleApi.Container.V1.Model.MasterAuth.t() | nil,
:location => String.t() | nil,
:subnetwork => String.t() | nil,
:status => String.t() | nil,
:network => String.t() | nil,
:nodeConfig => GoogleApi.Container.V1.Model.NodeConfig.t() | nil,
:tpuIpv4CidrBlock => String.t() | nil,
:ipAllocationPolicy => GoogleApi.Container.V1.Model.IPAllocationPolicy.t() | nil,
:addonsConfig => GoogleApi.Container.V1.Model.AddonsConfig.t() | nil,
:locations => list(String.t()) | nil,
:autopilot => GoogleApi.Container.V1.Model.Autopilot.t() | nil,
:resourceLabels => map() | nil,
:labelFingerprint => String.t() | nil,
:expireTime => String.t() | nil,
:currentNodeCount => integer() | nil,
:defaultMaxPodsConstraint => GoogleApi.Container.V1.Model.MaxPodsConstraint.t() | nil,
:notificationConfig => GoogleApi.Container.V1.Model.NotificationConfig.t() | nil,
:binaryAuthorization => GoogleApi.Container.V1.Model.BinaryAuthorization.t() | nil,
:monitoringConfig => GoogleApi.Container.V1.Model.MonitoringConfig.t() | nil,
:initialClusterVersion => String.t() | nil,
:id => String.t() | nil,
:nodePoolDefaults => GoogleApi.Container.V1.Model.NodePoolDefaults.t() | nil,
:nodePools => list(GoogleApi.Container.V1.Model.NodePool.t()) | nil,
:selfLink => String.t() | nil,
:servicesIpv4Cidr => String.t() | nil,
:databaseEncryption => GoogleApi.Container.V1.Model.DatabaseEncryption.t() | nil,
:maintenancePolicy => GoogleApi.Container.V1.Model.MaintenancePolicy.t() | nil,
:confidentialNodes => GoogleApi.Container.V1.Model.ConfidentialNodes.t() | nil,
:verticalPodAutoscaling => GoogleApi.Container.V1.Model.VerticalPodAutoscaling.t() | nil
}
field(:authenticatorGroupsConfig, as: GoogleApi.Container.V1.Model.AuthenticatorGroupsConfig)
field(:meshCertificates, as: GoogleApi.Container.V1.Model.MeshCertificates)
field(:clusterIpv4Cidr)
field(:instanceGroupUrls, type: :list)
field(:currentMasterVersion)
field(:enableTpu)
field(:nodeIpv4CidrSize)
field(:legacyAbac, as: GoogleApi.Container.V1.Model.LegacyAbac)
field(:shieldedNodes, as: GoogleApi.Container.V1.Model.ShieldedNodes)
field(:statusMessage)
field(:createTime)
field(:currentNodeVersion)
field(:autoscaling, as: GoogleApi.Container.V1.Model.ClusterAutoscaling)
field(:conditions, as: GoogleApi.Container.V1.Model.StatusCondition, type: :list)
field(:monitoringService)
field(:workloadIdentityConfig, as: GoogleApi.Container.V1.Model.WorkloadIdentityConfig)
field(:zone)
field(:description)
field(:privateClusterConfig, as: GoogleApi.Container.V1.Model.PrivateClusterConfig)
field(:enableKubernetesAlpha)
field(:loggingConfig, as: GoogleApi.Container.V1.Model.LoggingConfig)
field(:loggingService)
field(:resourceUsageExportConfig, as: GoogleApi.Container.V1.Model.ResourceUsageExportConfig)
field(:endpoint)
field(:initialNodeCount)
field(:networkConfig, as: GoogleApi.Container.V1.Model.NetworkConfig)
field(:masterAuthorizedNetworksConfig,
as: GoogleApi.Container.V1.Model.MasterAuthorizedNetworksConfig
)
field(:networkPolicy, as: GoogleApi.Container.V1.Model.NetworkPolicy)
field(:name)
field(:releaseChannel, as: GoogleApi.Container.V1.Model.ReleaseChannel)
field(:masterAuth, as: GoogleApi.Container.V1.Model.MasterAuth)
field(:location)
field(:subnetwork)
field(:status)
field(:network)
field(:nodeConfig, as: GoogleApi.Container.V1.Model.NodeConfig)
field(:tpuIpv4CidrBlock)
field(:ipAllocationPolicy, as: GoogleApi.Container.V1.Model.IPAllocationPolicy)
field(:addonsConfig, as: GoogleApi.Container.V1.Model.AddonsConfig)
field(:locations, type: :list)
field(:autopilot, as: GoogleApi.Container.V1.Model.Autopilot)
field(:resourceLabels, type: :map)
field(:labelFingerprint)
field(:expireTime)
field(:currentNodeCount)
field(:defaultMaxPodsConstraint, as: GoogleApi.Container.V1.Model.MaxPodsConstraint)
field(:notificationConfig, as: GoogleApi.Container.V1.Model.NotificationConfig)
field(:binaryAuthorization, as: GoogleApi.Container.V1.Model.BinaryAuthorization)
field(:monitoringConfig, as: GoogleApi.Container.V1.Model.MonitoringConfig)
field(:initialClusterVersion)
field(:id)
field(:nodePoolDefaults, as: GoogleApi.Container.V1.Model.NodePoolDefaults)
field(:nodePools, as: GoogleApi.Container.V1.Model.NodePool, type: :list)
field(:selfLink)
field(:servicesIpv4Cidr)
field(:databaseEncryption, as: GoogleApi.Container.V1.Model.DatabaseEncryption)
field(:maintenancePolicy, as: GoogleApi.Container.V1.Model.MaintenancePolicy)
field(:confidentialNodes, as: GoogleApi.Container.V1.Model.ConfidentialNodes)
field(:verticalPodAutoscaling, as: GoogleApi.Container.V1.Model.VerticalPodAutoscaling)
end
defimpl Poison.Decoder, for: GoogleApi.Container.V1.Model.Cluster do
def decode(value, options) do
GoogleApi.Container.V1.Model.Cluster.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Container.V1.Model.Cluster do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 98.484716 | 738 | 0.728817 |
e811b607368fea455e0c3254d49f53185c5daf16 | 238 | ex | Elixir | lib/portmidi/nifs/devices.ex | olafklingt/ex-portmidi | 524c4567c4951b55cfa12aee2517a2eb32fa4792 | [
"MIT"
] | null | null | null | lib/portmidi/nifs/devices.ex | olafklingt/ex-portmidi | 524c4567c4951b55cfa12aee2517a2eb32fa4792 | [
"MIT"
] | null | null | null | lib/portmidi/nifs/devices.ex | olafklingt/ex-portmidi | 524c4567c4951b55cfa12aee2517a2eb32fa4792 | [
"MIT"
] | 1 | 2020-12-16T15:35:51.000Z | 2020-12-16T15:35:51.000Z | defmodule PortMidi.Nifs.Devices do
@on_load :init
def init do
:portmidi
|> :code.priv_dir()
|> :filename.join("portmidi_devices")
|> :erlang.load_nif(0)
end
def do_list, do: :erlang.nif_error(:nif_not_loaded)
end
| 19.833333 | 53 | 0.672269 |
e811c7c5da79f48666a5e941541c13da6b3b3c60 | 595 | exs | Elixir | test/signing_keys_manager_test.exs | Mohammad-Haseeb/ex_microsoftbot | 72c417ce1e6dd42cf982bf856f3b402b67cf820e | [
"MIT"
] | 35 | 2016-05-11T02:34:27.000Z | 2021-04-29T07:34:11.000Z | test/signing_keys_manager_test.exs | Mohammad-Haseeb/ex_microsoftbot | 72c417ce1e6dd42cf982bf856f3b402b67cf820e | [
"MIT"
] | 27 | 2016-07-10T18:32:25.000Z | 2021-09-29T07:00:22.000Z | test/signing_keys_manager_test.exs | Mohammad-Haseeb/ex_microsoftbot | 72c417ce1e6dd42cf982bf856f3b402b67cf820e | [
"MIT"
] | 23 | 2016-05-10T18:53:13.000Z | 2021-06-25T22:04:21.000Z | defmodule ExMicrosoftBot.Test.SigningKeysManager do
use ExUnit.Case
require Logger
alias ExMicrosoftBot.SigningKeysManager
test "Get signing keys from MBF" do
SigningKeysManager.start_link([])
{:ok, keys} = SigningKeysManager.get_keys()
assert length(keys) > 0
assert [%JOSE.JWK{} | _] = keys
end
test "Force refresh signing keys from MBF" do
SigningKeysManager.start_link([])
assert :ok = SigningKeysManager.force_refresh_keys()
{:ok, keys} = SigningKeysManager.get_keys()
assert length(keys) > 0
assert [%JOSE.JWK{} | _] = keys
end
end
| 22.884615 | 56 | 0.69916 |
e811c9c754136d5d08011bac4df905da6b76da02 | 482 | ex | Elixir | lib/inspect/tuple.ex | ElixirWerkz/exlogger | 57e2da8c0883b5e83be00fe0764628f4b5f3bdf5 | [
"MIT"
] | 2 | 2015-08-25T09:23:21.000Z | 2016-04-14T12:30:06.000Z | lib/inspect/tuple.ex | ElixirWerkz/exlogger | 57e2da8c0883b5e83be00fe0764628f4b5f3bdf5 | [
"MIT"
] | null | null | null | lib/inspect/tuple.ex | ElixirWerkz/exlogger | 57e2da8c0883b5e83be00fe0764628f4b5f3bdf5 | [
"MIT"
] | null | null | null | defimpl ExLogger.Inspect, for: Tuple do
import Kernel, except: [to_string: 1]
def to_string(thing) when is_atom(elem(thing, 0)) and tuple_size(thing) > 1 do
module = elem(thing, 0)
if Code.ensure_loaded?(module) and
function_exported?(module, :__record__, 1) and
module.__record__(:fields)[:__exception__] == :__exception__ do
module.message(thing)
else
inspect(thing)
end
end
def to_string(thing) do
inspect(thing)
end
end | 25.368421 | 80 | 0.678423 |
e811df7ceba5439127b34f51bf96dc92167bfb9e | 8,791 | exs | Elixir | test/mogrify_test.exs | kpanic/mogrify | 48fc57cf0a019ce3648871c29f0167555498dbe5 | [
"MIT"
] | null | null | null | test/mogrify_test.exs | kpanic/mogrify | 48fc57cf0a019ce3648871c29f0167555498dbe5 | [
"MIT"
] | null | null | null | test/mogrify_test.exs | kpanic/mogrify | 48fc57cf0a019ce3648871c29f0167555498dbe5 | [
"MIT"
] | null | null | null | defmodule MogrifyTest do
import Mogrify
alias Mogrify.Image
use Mogrify.Options
use ExUnit.Case, async: true
@fixture Path.join(__DIR__, "fixtures/bender.jpg")
@fixture_with_space Path.join(__DIR__, "fixtures/image with space in name/ben der.jpg")
@fixture_animated Path.join(__DIR__, "fixtures/bender_anim.gif")
@fixture_rgbw Path.join(__DIR__, "fixtures/rgbw.png")
@temp_test_directory "#{System.tmp_dir}/mogrify test folder" |> Path.expand
@temp_image_with_space Path.join(@temp_test_directory, "1 1.jpg")
test ".open" do
image = open("./test/fixtures/bender.jpg")
assert %Image{path: @fixture, ext: ".jpg"} = image
image = open(@fixture)
assert %Image{path: @fixture, ext: ".jpg"} = image
end
test ".open when file name has spaces" do
image = open("./test/fixtures/image with space in name/ben der.jpg")
assert %Image{path: @fixture_with_space, ext: ".jpg"} = image
image = open(@fixture_with_space)
assert %Image{path: @fixture_with_space, ext: ".jpg"} = image
end
test ".open when file does not exist" do
assert_raise File.Error, fn ->
open("./test/fixtures/does_not_exist.jpg")
end
end
test ".save" do
path = Path.join(System.tmp_dir, "1.jpg")
image = open(@fixture) |> save(path: path)
assert File.regular?(path)
assert %Image{path: path} = image
File.rm!(path)
end
test ".save when file name has spaces" do
File.mkdir_p!(@temp_test_directory)
image = open(@fixture) |> save(path: @temp_image_with_space)
assert File.regular?(@temp_image_with_space)
assert %Image{path: @temp_image_with_space} = image
File.rm_rf!(@temp_test_directory)
end
test ".save in place" do
# setup, make a copy
path = Path.join(System.tmp_dir, "1.jpg")
open(@fixture) |> save(path: path)
# test begins
image = open(path) |> resize("600x600") |> save(in_place: true) |> verbose
assert %Image{path: path, height: 584, width: 600} = image
File.rm!(path)
end
test ".save in place when file name has spaces" do
# setup, make a copy
File.mkdir_p!(@temp_test_directory)
open(@fixture) |> save(path: @temp_image_with_space)
# test begins
image = open(@temp_image_with_space) |> resize("600x600") |> save(in_place: true) |> verbose
assert %Image{path: @temp_image_with_space, height: 584, width: 600} = image
File.rm_rf!(@temp_test_directory)
end
test ".save :in_place ignores :path option" do
# setup, make a copy
path = Path.join(System.tmp_dir, "1.jpg")
open(@fixture) |> save(path: path)
# test begins
image = open(path) |> resize("600x600") |> save(in_place: true, path: "#{path}-ignore") |> verbose
assert %Image{path: path, height: 584, width: 600} = image
File.rm!(path)
end
test ".save :in_place ignores :path option when file name has spaces" do
# setup, make a copy
File.mkdir_p!(@temp_test_directory)
open(@fixture) |> save(path: @temp_image_with_space)
# test begins
image = open(@temp_image_with_space) |> resize("600x600") |> save(in_place: true, path: "#{@temp_image_with_space}-ignore") |> verbose
assert %Image{path: @temp_image_with_space, height: 584, width: 600} = image
File.rm_rf!(@temp_test_directory)
end
test ".create" do
path = Path.join(System.tmp_dir, "1.jpg")
image = %Image{path: path} |> canvas("white") |> create(path: path)
assert File.exists?(path)
assert %Image{path: path} = image
File.rm!(path)
end
test ".create when file name has spaces" do
File.mkdir_p!(@temp_test_directory)
image = %Image{path: @temp_image_with_space} |> canvas("white") |> create(path: @temp_image_with_space)
assert File.exists?(@temp_image_with_space)
assert %Image{path: @temp_image_with_space} = image
File.rm_rf!(@temp_test_directory)
end
test ".copy" do
image = open(@fixture) |> copy
tmp_dir = System.tmp_dir |> Regex.escape
slash = if String.ends_with?(tmp_dir, "/"), do: "", else: "/"
assert Regex.match?(~r(#{tmp_dir}#{slash}\d+-bender\.jpg), image.path)
end
test ".copy when file name has spaces" do
image = open(@fixture_with_space) |> copy
tmp_dir = System.tmp_dir |> Regex.escape
slash = if String.ends_with?(tmp_dir, "/"), do: "", else: "/"
assert Regex.match?(~r(#{tmp_dir}#{slash}\d+-ben\sder\.jpg), image.path)
end
test ".verbose" do
image = open(@fixture)
assert %Image{format: "jpeg", height: 292, width: 300, animated: false} = verbose(image)
end
test ".verbose when file name has spaces" do
image = open(@fixture_with_space)
assert %Image{format: "jpeg", height: 292, width: 300, animated: false} = verbose(image)
end
test ".verbose animated" do
image = open(@fixture_animated)
assert %Image{format: "gif", animated: true} = verbose(image)
end
test ".verbose should not change file modification time" do
%{mtime: old_time} = File.stat! @fixture
:timer.sleep(1000)
open(@fixture) |> verbose
%{mtime: new_time} = File.stat! @fixture
assert old_time == new_time
end
test ".verbose frame_count" do
assert %Image{frame_count: 1} = open(@fixture) |> verbose
assert %Image{frame_count: 2} = open(@fixture_animated) |> verbose
end
test ".format" do
image = open(@fixture) |> format("png") |> save |> verbose
assert %Image{ext: ".png", format: "png", height: 292, width: 300} = image
end
test ".format updates format after save" do
image = open(@fixture) |> format("png") |> save
assert %Image{ext: ".png", format: "png"} = image
end
test ".resize" do
image = open(@fixture) |> resize("100x100") |> save |> verbose
assert %Image{width: 100, height: 97} = image
end
test ".resize_to_fill" do
image = open(@fixture) |> resize_to_fill("450x300") |> save |> verbose
assert %Image{width: 450, height: 300} = image
end
test ".resize_to_limit" do
image = open(@fixture) |> resize_to_limit("200x200") |> save |> verbose
assert %Image{width: 200, height: 195} = image
end
test ".extent" do
image = open(@fixture) |> extent("500x500") |> save |> verbose
assert %Image{width: 500, height: 500} = image
end
test ".custom with plus-form of a command" do
image_minus = open(@fixture) |> custom("raise", 50) |> save |> verbose
image_plus = open(@fixture) |> custom("+raise", 50) |> save |> verbose
%{size: size_minus} = File.stat! image_minus.path
%{size: size_plus} = File.stat! image_plus.path
assert size_minus != size_plus
end
test ".custom with explicit minus-form of a command" do
image_implicit = open(@fixture) |> custom("raise", 50) |> save |> verbose
image_explicit = open(@fixture) |> custom("-raise", 50) |> save |> verbose
%{size: size_implicit} = File.stat! image_implicit.path
%{size: size_explicit} = File.stat! image_explicit.path
assert size_implicit == size_explicit
end
test ".histogram" do
hist = open(@fixture_rgbw) |> histogram |> Enum.sort_by( fn %{"hex" => hex} -> hex end )
expected = [
%{"blue" => 255, "count" => 400, "green" => 0, "hex" => "#0000ff", "red" => 0},
%{"blue" => 0, "count" => 225, "green" => 255, "hex" => "#00ff00", "red" => 0},
%{"blue" => 0, "count" => 525, "green" => 0, "hex" => "#ff0000", "red" => 255},
%{"blue" => 255, "count" => 1350, "green" => 255, "hex" => "#ffffff", "red" => 255}
]
assert hist == expected
end
test "allows to pass options to command throw add_option" do
rotate_image = open(@fixture) |> add_option(option_rotate("-90>"))
assert rotate_image.operations == [{"-rotate", "-90>"}]
end
test "raise ArgumentError when no argument is passed to option when is required " do
assert_raise ArgumentError, "the option rotate need arguments. Be sure to pass arguments to option_rotate(arg)", fn ->
open(@fixture) |> add_option(option_rotate())
end
end
test "raise ArgumentError when no argument is passed to option when is required and return correct message for options with plus sign" do
assert_raise ArgumentError, "the option gamma need arguments. Be sure to pass arguments to option_plus_gamma(arg)", fn ->
open(@fixture) |> add_option(option_plus_gamma())
end
end
test "raise ArgumentError when no argument is passed to option when is required and return correct message for options name with hyphens in the middle of the name" do
assert_raise ArgumentError, "the option gaussian_blur need arguments. Be sure to pass arguments to option_gaussian_blur(arg)", fn ->
open(@fixture) |> add_option(option_gaussian_blur())
end
end
@tag timeout: 5000
test ".auto_orient should not hang" do
open(@fixture) |> auto_orient |> save
end
end
| 34.339844 | 168 | 0.658401 |
e811f19ec48f81961910d248966616c6b2ee057c | 131 | ex | Elixir | postgis-ecto/gis_demo/lib/gis_demo/repo_postgis.ex | wisq/slides | e0a1b9dd8187b82c8772b4e6ab20f8b069e1feb1 | [
"MIT"
] | null | null | null | postgis-ecto/gis_demo/lib/gis_demo/repo_postgis.ex | wisq/slides | e0a1b9dd8187b82c8772b4e6ab20f8b069e1feb1 | [
"MIT"
] | null | null | null | postgis-ecto/gis_demo/lib/gis_demo/repo_postgis.ex | wisq/slides | e0a1b9dd8187b82c8772b4e6ab20f8b069e1feb1 | [
"MIT"
] | null | null | null | Postgrex.Types.define(
GisDemo.PostgresTypes,
[Geo.PostGIS.Extension] ++ Ecto.Adapters.Postgres.extensions(),
json: Poison
)
| 21.833333 | 65 | 0.748092 |
e812221ae1b5227e7be067b1b0cb6d9fc7032bd0 | 66 | exs | Elixir | test/test_helper.exs | fuelen/apq | 3cf1d5bdf58d690711ed33d506b92096939da9ae | [
"MIT"
] | 41 | 2018-09-15T13:02:28.000Z | 2022-01-11T23:17:11.000Z | test/test_helper.exs | fuelen/apq | 3cf1d5bdf58d690711ed33d506b92096939da9ae | [
"MIT"
] | 41 | 2018-09-15T13:17:56.000Z | 2022-03-24T04:03:50.000Z | test/test_helper.exs | fuelen/apq | 3cf1d5bdf58d690711ed33d506b92096939da9ae | [
"MIT"
] | 4 | 2018-09-25T09:59:30.000Z | 2021-11-15T10:08:37.000Z | ExUnit.start()
Mox.defmock(Apq.CacheMock, for: Apq.CacheProvider)
| 22 | 50 | 0.787879 |
e8123315370b04b9de9a3223808e40d516921920 | 172 | ex | Elixir | lib/elixir/test/elixir/fixtures/dialyzer/boolean_check.ex | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 19,291 | 2015-01-01T02:42:49.000Z | 2022-03-31T21:01:40.000Z | lib/elixir/test/elixir/fixtures/dialyzer/boolean_check.ex | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 8,082 | 2015-01-01T04:16:23.000Z | 2022-03-31T22:08:02.000Z | lib/elixir/test/elixir/fixtures/dialyzer/boolean_check.ex | doughsay/elixir | 7356a47047d0b54517bd6886603f09b1121dde2b | [
"Apache-2.0"
] | 3,472 | 2015-01-03T04:11:56.000Z | 2022-03-29T02:07:30.000Z | defmodule Dialyzer.BooleanCheck do
def and_check(arg) when is_boolean(arg) do
arg and arg
end
def or_check(arg) when is_boolean(arg) do
arg or arg
end
end
| 17.2 | 44 | 0.72093 |
e8123bc4bd828e7c5dd6c60c41b8c801e8d18d08 | 842 | ex | Elixir | lib/espec/finally.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 807 | 2015-03-25T14:00:19.000Z | 2022-03-24T08:08:15.000Z | lib/espec/finally.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 254 | 2015-03-27T10:12:25.000Z | 2021-07-12T01:40:15.000Z | lib/espec/finally.ex | MeneDev/espec | ec4b3d579c5192999e930224a8a2650bb1fdf0bc | [
"Apache-2.0"
] | 85 | 2015-04-02T10:25:19.000Z | 2021-01-30T21:30:43.000Z | defmodule ESpec.Finally do
@moduledoc """
Defines `finally` macro.
The block is evaluated after the example.
`shared` is available.
Define the `finally` before example!.
"""
@doc "Struct has random fuction name."
defstruct module: nil, function: nil
@doc """
Adds %ESpec.Finally structs to the context and
defines random function with random name which will be called when example is run.
"""
defmacro finally(do: block) do
function = random_finally_name()
quote do
tail = @context
head = %ESpec.Finally{module: __MODULE__, function: unquote(function)}
def unquote(function)(var!(shared)) do
var!(shared)
unquote(block)
end
@context [head | tail]
end
end
defp random_finally_name, do: String.to_atom("finally_#{ESpec.Support.random_string()}")
end
| 24.764706 | 90 | 0.67696 |
e8123bf76a593a6ff7be23ca7a373b5fb04b175c | 1,008 | ex | Elixir | lib/hackton/endpoint.ex | raincrash/hackton | f85f049c79df25039d2c04e174d8a7b8fb946942 | [
"MIT"
] | 1 | 2016-03-15T17:50:12.000Z | 2016-03-15T17:50:12.000Z | lib/hackton/endpoint.ex | raincrash/hackton | f85f049c79df25039d2c04e174d8a7b8fb946942 | [
"MIT"
] | null | null | null | lib/hackton/endpoint.ex | raincrash/hackton | f85f049c79df25039d2c04e174d8a7b8fb946942 | [
"MIT"
] | null | null | null | defmodule Hackton.Endpoint do
use Phoenix.Endpoint, otp_app: :hackton
socket "/socket", Hackton.UserSocket
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phoenix.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/", from: :hackton, gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
plug Phoenix.LiveReloader
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
plug Plug.MethodOverride
plug Plug.Head
plug Plug.Session,
store: :cookie,
key: "_hackton_key",
signing_salt: "CAReVkbD"
plug Hackton.Router
end
| 25.2 | 69 | 0.709325 |
e8126b4b298c6b1ae0fae314a546583713dbe216 | 354 | exs | Elixir | priv/repo/migrations/20170716085027_create_xp_history.exs | trewdys/source-academy2-debug | 6146e1fac81472184877f47aa32dee7fdceb4fb6 | [
"Unlicense"
] | null | null | null | priv/repo/migrations/20170716085027_create_xp_history.exs | trewdys/source-academy2-debug | 6146e1fac81472184877f47aa32dee7fdceb4fb6 | [
"Unlicense"
] | null | null | null | priv/repo/migrations/20170716085027_create_xp_history.exs | trewdys/source-academy2-debug | 6146e1fac81472184877f47aa32dee7fdceb4fb6 | [
"Unlicense"
] | null | null | null | defmodule SourceAcademy.Repo.Migrations.CreateXpHistory do
use Ecto.Migration
def change do
create table(:xp_history) do
add :reason, :string
add :amount, :integer
add :giver_id, references(:users)
add :student_id, references(:students)
timestamps()
end
create index(:xp_history, [:student_id])
end
end
| 20.823529 | 58 | 0.680791 |
e8129b22aa1534ef4fdd071c4e57761b77ab62d5 | 726 | ex | Elixir | lib/questionator_web/gettext.ex | krodante/questionator | f23f34ccf063b7969b60514aa9af433bb05369d5 | [
"MIT"
] | 3 | 2021-08-30T20:22:39.000Z | 2022-03-16T10:27:50.000Z | lib/questionator_web/gettext.ex | krodante/questionator | f23f34ccf063b7969b60514aa9af433bb05369d5 | [
"MIT"
] | null | null | null | lib/questionator_web/gettext.ex | krodante/questionator | f23f34ccf063b7969b60514aa9af433bb05369d5 | [
"MIT"
] | 2 | 2021-08-18T17:20:46.000Z | 2021-09-01T04:15:31.000Z | defmodule QuestionatorWeb.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 QuestionatorWeb.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: :questionator
end
| 29.04 | 72 | 0.684573 |
e8129f4864162e062a3c7ef95fa1254835185b47 | 278 | ex | Elixir | lib/space_mongers/models/user_data.ex | ericgroom/space_mongers | e9f979318dca2e8ee4f685014bae585db15cd117 | [
"MIT"
] | 2 | 2021-03-18T02:00:29.000Z | 2021-04-18T06:11:07.000Z | lib/space_mongers/models/user_data.ex | ericgroom/space_mongers | e9f979318dca2e8ee4f685014bae585db15cd117 | [
"MIT"
] | null | null | null | lib/space_mongers/models/user_data.ex | ericgroom/space_mongers | e9f979318dca2e8ee4f685014bae585db15cd117 | [
"MIT"
] | null | null | null | defmodule SpaceMongers.Models.UserData do
@moduledoc """
Contains various data about the user
"""
use SpaceMongers.Model,
username: String.t(),
credits: integer(),
loans: [Models.OwnedLoan.t()],
ships: [Models.OwnedShip.t()],
extra_fields: map()
end
| 23.166667 | 41 | 0.669065 |
e812a4bc8b857e1b545e096590414a8a874f4ca5 | 238 | ex | Elixir | test/support/setup_users.ex | fidr/qh | 14d392c5612889c7ed9e88cf558e677ac06b39f4 | [
"MIT"
] | 5 | 2022-01-10T10:57:44.000Z | 2022-01-22T18:15:05.000Z | test/support/setup_users.ex | fidr/qh | 14d392c5612889c7ed9e88cf558e677ac06b39f4 | [
"MIT"
] | null | null | null | test/support/setup_users.ex | fidr/qh | 14d392c5612889c7ed9e88cf558e677ac06b39f4 | [
"MIT"
] | null | null | null | defmodule QTest.Repo.Migrations.SetupUsers do
use Ecto.Migration
def change do
create table(:users) do
add(:name, :text)
add(:age, :integer)
add(:nicknames, {:array, :text})
timestamps()
end
end
end
| 18.307692 | 45 | 0.62605 |
e812af65782fc005afc856c0fd170213143881e8 | 537 | ex | Elixir | backend/lib/budgetsh_web/views/error_view.ex | djquan/budget.sh.old | e0c3ac772ce061c4a8c990ef86ea341172146d18 | [
"MIT"
] | 2 | 2019-09-08T23:26:20.000Z | 2019-10-04T21:05:40.000Z | backend/lib/budgetsh_web/views/error_view.ex | djquan/budget.sh | e0c3ac772ce061c4a8c990ef86ea341172146d18 | [
"MIT"
] | null | null | null | backend/lib/budgetsh_web/views/error_view.ex | djquan/budget.sh | e0c3ac772ce061c4a8c990ef86ea341172146d18 | [
"MIT"
] | null | null | null | defmodule BudgetSHWeb.ErrorView do
use BudgetSHWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.json", _assigns) do
# %{errors: %{detail: "Internal Server Error"}}
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.json" becomes
# "Not Found".
def template_not_found(template, _assigns) do
%{errors: %{detail: Phoenix.Controller.status_message_from_template(template)}}
end
end
| 31.588235 | 83 | 0.72067 |
e812fa7e516c7bf09147552be9678e306a02f876 | 474 | exs | Elixir | test/virgo_web/views/error_view_test.exs | GinShio/AstraeaVirgo | 92804cbae01f67e21b8f421009fa37fddc9054e1 | [
"BSD-2-Clause"
] | null | null | null | test/virgo_web/views/error_view_test.exs | GinShio/AstraeaVirgo | 92804cbae01f67e21b8f421009fa37fddc9054e1 | [
"BSD-2-Clause"
] | null | null | null | test/virgo_web/views/error_view_test.exs | GinShio/AstraeaVirgo | 92804cbae01f67e21b8f421009fa37fddc9054e1 | [
"BSD-2-Clause"
] | null | null | null | defmodule AstraeaVirgoWeb.ErrorViewTest do
use AstraeaVirgoWeb.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(AstraeaVirgoWeb.ErrorView, "404.json", []) == %{errors: %{detail: "Not Found"}}
end
test "renders 500.json" do
assert render(AstraeaVirgoWeb.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| 29.625 | 97 | 0.696203 |
e812fd4e42d9e5c71dcdf8d02b659c9e014095d2 | 273 | exs | Elixir | apps/elixir_ls_utils/test/placeholder_test.exs | maciej-szlosarczyk/elixir-ls | f9e3a969a32212482a7625deec9e0fd0f533f991 | [
"Apache-2.0"
] | 865 | 2018-10-31T20:29:13.000Z | 2022-03-29T11:13:39.000Z | apps/elixir_ls_utils/test/placeholder_test.exs | maciej-szlosarczyk/elixir-ls | f9e3a969a32212482a7625deec9e0fd0f533f991 | [
"Apache-2.0"
] | 441 | 2019-01-05T02:33:52.000Z | 2022-03-30T20:56:50.000Z | apps/elixir_ls_utils/test/placeholder_test.exs | maciej-szlosarczyk/elixir-ls | f9e3a969a32212482a7625deec9e0fd0f533f991 | [
"Apache-2.0"
] | 126 | 2018-11-12T19:16:53.000Z | 2022-03-26T13:27:50.000Z | defmodule ElixirLS.Utils.PlaceholderTest do
use ExUnit.Case, async: true
@tag :fixture
test "pretend fixture" do
# This test is included to prevent the following error:
# > The --only option was given to "mix test" but no test was executed
:ok
end
end
| 24.818182 | 74 | 0.70696 |
e8133b2277f06250b4db1a3460a14b90ce650f6b | 1,409 | exs | Elixir | config/config.exs | philcallister/ticker | 19d0b95785665ea888d1fb9a8c59d3e9dcb4fc79 | [
"MIT"
] | 1 | 2016-11-02T03:38:26.000Z | 2016-11-02T03:38:26.000Z | config/config.exs | philcallister/ticker | 19d0b95785665ea888d1fb9a8c59d3e9dcb4fc79 | [
"MIT"
] | null | null | null | config/config.exs | philcallister/ticker | 19d0b95785665ea888d1fb9a8c59d3e9dcb4fc79 | [
"MIT"
] | null | null | null | # This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :ticker, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:ticker, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
config :ticker,
frequency: 15_000,
processor: Ticker.Quote.Processor.HTTP,
historical: false,
symbols: ["TSLA", "GOOG", "AAPL", "TWTR", "FB", "MMM", "GLD", "VOO"],
url: "http://finance.google.com/finance/info?client=ig&q=NASDAQ%3A",
quote_notify: [notify_module: :none, notify_fn: :none]
# 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"
| 37.078947 | 73 | 0.737402 |
e81369d5afde5b29e90d87d1f0d596f9f88bcba3 | 1,985 | exs | Elixir | lib/mix/test/mix/utils_test.exs | ekosz/elixir | 62e375bc711b4072e1b68de776e96cc31f571d45 | [
"Apache-2.0"
] | 1 | 2017-10-29T16:37:08.000Z | 2017-10-29T16:37:08.000Z | lib/mix/test/mix/utils_test.exs | ekosz/elixir | 62e375bc711b4072e1b68de776e96cc31f571d45 | [
"Apache-2.0"
] | null | null | null | lib/mix/test/mix/utils_test.exs | ekosz/elixir | 62e375bc711b4072e1b68de776e96cc31f571d45 | [
"Apache-2.0"
] | null | null | null | Code.require_file "../../test_helper", __FILE__
defmodule Mix.UtilsTest do
use MixTest.Case
test :command_to_module do
assert Mix.Utils.command_to_module("hello", Mix.Tasks) == { :module, Mix.Tasks.Hello }
assert Mix.Utils.command_to_module("unknown", Mix.Tasks) == { :error, :nofile }
end
test :module_name_to_command do
assert Mix.Utils.module_name_to_command(Mix.Tasks.Foo, 2) == "foo"
assert Mix.Utils.module_name_to_command("Mix.Tasks.Foo", 2) == "foo"
assert Mix.Utils.module_name_to_command("Mix.Tasks.Foo.Bar", 2) == "foo.bar"
end
test :command_to_module_name do
assert Mix.Utils.command_to_module_name("foo") == "Foo"
assert Mix.Utils.command_to_module_name("foo.bar") == "Foo.Bar"
end
test :config_merge do
old = [
foo: "hello",
bar: [1,2],
baz: [some: "option"],
bat: "man"
]
new = [
foo: "bye",
bar: [3,4],
baz: [yet: "another"]
]
assert Mix.Utils.config_merge(old, new) == [
foo: "bye",
bar: [1,2,3,4],
baz: [some: "option", yet: "another"],
bat: "man"
]
end
test :source do
assert Mix.Utils.source(__MODULE__) == __FILE__
end
test :underscore do
assert Mix.Utils.underscore("foo") == "foo"
assert Mix.Utils.underscore("foo_bar") == "foo_bar"
assert Mix.Utils.underscore("Foo") == "foo"
assert Mix.Utils.underscore("FooBar") == "foo_bar"
assert Mix.Utils.underscore("FOOBar") == "foo_bar"
assert Mix.Utils.underscore("FooBAR") == "foo_bar"
assert Mix.Utils.underscore("FoBaZa") == "fo_ba_za"
end
test :camelize do
assert Mix.Utils.camelize("Foo") == "Foo"
assert Mix.Utils.camelize("FooBar") == "FooBar"
assert Mix.Utils.camelize("foo") == "Foo"
assert Mix.Utils.camelize("foo_bar") == "FooBar"
assert Mix.Utils.camelize("foo_") == "Foo"
assert Mix.Utils.camelize("_foo") == "Foo"
assert Mix.Utils.camelize("foo__bar") == "FooBar"
end
end | 29.626866 | 92 | 0.6267 |
e8139f2534e0cb4fa780cc70c2e54b4a11db9b46 | 112 | exs | Elixir | config/config.exs | brainlid/meetup_process_state | a429d6e5ff4e4bbfc2e243291292ea1f010abb9d | [
"MIT"
] | 2 | 2018-12-30T01:48:59.000Z | 2021-12-25T15:42:21.000Z | config/config.exs | brainlid/meetup_process_state | a429d6e5ff4e4bbfc2e243291292ea1f010abb9d | [
"MIT"
] | null | null | null | config/config.exs | brainlid/meetup_process_state | a429d6e5ff4e4bbfc2e243291292ea1f010abb9d | [
"MIT"
] | null | null | null | use Mix.Config
config :logger, :console,
metadata: [:pid, :state_1, :custom_1, :custom_2]
# metadata: :all
| 18.666667 | 50 | 0.678571 |
e813a83dcd862e9d4fb28c845c6a970e48bfa1a7 | 2,113 | ex | Elixir | clients/you_tube/lib/google_api/you_tube/v3/model/channel_conversion_ping.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | 1 | 2018-12-03T23:43:10.000Z | 2018-12-03T23:43:10.000Z | clients/you_tube/lib/google_api/you_tube/v3/model/channel_conversion_ping.ex | matehat/elixir-google-api | c1b2523c2c4cdc9e6ca4653ac078c94796b393c3 | [
"Apache-2.0"
] | null | null | null | clients/you_tube/lib/google_api/you_tube/v3/model/channel_conversion_ping.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.YouTube.V3.Model.ChannelConversionPing do
@moduledoc """
Pings that the app shall fire (authenticated by biscotti cookie). Each ping has a context, in which the app must fire the ping, and a url identifying the ping.
## Attributes
* `context` (*type:* `String.t`, *default:* `nil`) - Defines the context of the ping.
* `conversionUrl` (*type:* `String.t`, *default:* `nil`) - The url (without the schema) that the player shall send the ping to. It's at caller's descretion to decide which schema to use (http vs https) Example of a returned url: //googleads.g.doubleclick.net/pagead/ viewthroughconversion/962985656/?data=path%3DtHe_path%3Btype%3D cview%3Butuid%3DGISQtTNGYqaYl4sKxoVvKA&labe=default The caller must append biscotti authentication (ms param in case of mobile, for example) to this ping.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:context => String.t(),
:conversionUrl => String.t()
}
field(:context)
field(:conversionUrl)
end
defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.ChannelConversionPing do
def decode(value, options) do
GoogleApi.YouTube.V3.Model.ChannelConversionPing.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.ChannelConversionPing do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.26 | 489 | 0.744912 |
e813b0929566e902c985b269a2f62627f11901a4 | 2,044 | exs | Elixir | test/nucleotide_count_test.exs | jeremy-miller/exercism-elixir | c9bb3b086c7a2fc62e7e19c803de3827893be946 | [
"MIT"
] | null | null | null | test/nucleotide_count_test.exs | jeremy-miller/exercism-elixir | c9bb3b086c7a2fc62e7e19c803de3827893be946 | [
"MIT"
] | null | null | null | test/nucleotide_count_test.exs | jeremy-miller/exercism-elixir | c9bb3b086c7a2fc62e7e19c803de3827893be946 | [
"MIT"
] | null | null | null | defmodule NucleotideCountTest do
use ExUnit.Case, async: true
use Quixir
import Map, only: [has_key?: 2, keys: 1]
doctest NucleotideCount
describe "NucleotideCount.count/2" do
test "correctly counts valid nucleotides" do
ptest dna_string: string(chars: :upper, must_have: ["A", "T", "C", "G"]), nucleotide: string(min: 1, max: 1, chars: :upper, must_have: ["A", "T", "C", "G"]) do
assert NucleotideCount.count(dna_string, nucleotide) >= 0
end
end
test "correctly counts nucleotides with invalid input" do
ptest dna_string: string(chars: :upper), nucleotide: string(min: 1, max: 1, chars: :upper, must_have: ["A", "T", "C", "G"]) do
assert NucleotideCount.count(dna_string, nucleotide) >= 0
end
end
end
describe "NucleotideCount.histogram/1" do
test "NucleotideCount.histogram correctly counts valid nucleotides" do
ptest dna_string: string(chars: :upper, must_have: ["A", "T", "C", "G"]) do
histogram = NucleotideCount.histogram(dna_string)
histogram_keys_length = keys(histogram) |> length
assert histogram_keys_length === 4
assert has_key?(histogram, A)
assert has_key?(histogram, T)
assert has_key?(histogram, C)
assert has_key?(histogram, G)
assert histogram[A] >= 0
assert histogram[T] >= 0
assert histogram[C] >= 0
assert histogram[G] >= 0
end
end
test "NucleotideCount.histogram correctly counts nucleotides with invalid input" do
ptest dna_string: string(chars: :upper) do
histogram = NucleotideCount.histogram(dna_string)
histogram_keys_length = keys(histogram) |> length
assert histogram_keys_length === 4
assert has_key?(histogram, A)
assert has_key?(histogram, T)
assert has_key?(histogram, C)
assert has_key?(histogram, G)
assert histogram[A] >= 0
assert histogram[T] >= 0
assert histogram[C] >= 0
assert histogram[G] >= 0
end
end
end
end
| 37.163636 | 165 | 0.642857 |
e813b1105192b6827cb1ed59d39f599e854b4d6f | 2,610 | ex | Elixir | clients/drive/lib/google_api/drive/v3/model/file_list.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/drive/lib/google_api/drive/v3/model/file_list.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/drive/lib/google_api/drive/v3/model/file_list.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Drive.V3.Model.FileList do
@moduledoc """
A list of files.
## Attributes
* `files` (*type:* `list(GoogleApi.Drive.V3.Model.File.t)`, *default:* `nil`) - The list of files. If nextPageToken is populated, then this list may be incomplete and an additional page of results should be fetched.
* `incompleteSearch` (*type:* `boolean()`, *default:* `nil`) - Whether the search process was incomplete. If true, then some search results may be missing, since all documents were not searched. This may occur when searching multiple drives with the "allDrives" corpora, but all corpora could not be searched. When this happens, it is suggested that clients narrow their query by choosing a different corpus such as "user" or "drive".
* `kind` (*type:* `String.t`, *default:* `drive#fileList`) - Identifies what kind of resource this is. Value: the fixed string "drive#fileList".
* `nextPageToken` (*type:* `String.t`, *default:* `nil`) - The page token for the next page of files. This will be absent if the end of the files list has been reached. If the token is rejected for any reason, it should be discarded, and pagination should be restarted from the first page of results.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:files => list(GoogleApi.Drive.V3.Model.File.t()),
:incompleteSearch => boolean(),
:kind => String.t(),
:nextPageToken => String.t()
}
field(:files, as: GoogleApi.Drive.V3.Model.File, type: :list)
field(:incompleteSearch)
field(:kind)
field(:nextPageToken)
end
defimpl Poison.Decoder, for: GoogleApi.Drive.V3.Model.FileList do
def decode(value, options) do
GoogleApi.Drive.V3.Model.FileList.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Drive.V3.Model.FileList do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 46.607143 | 438 | 0.723372 |
e813b447264122059821f8355855a2477139c36c | 1,532 | ex | Elixir | installer/templates/phx_web/views/error_helpers.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | 1 | 2018-07-26T10:42:26.000Z | 2018-07-26T10:42:26.000Z | installer/templates/phx_web/views/error_helpers.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | null | null | null | installer/templates/phx_web/views/error_helpers.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | null | null | null | defmodule <%= web_namespace %>.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
<%= if html do %>
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag :span, translate_error(error), class: "help-block"
end)
end
<% end %>
@doc """
Translates an error message using gettext.
"""
def translate_error({msg, opts}) do
# When using gettext, we typically pass the strings we want
# to translate as a static argument:
#
# # Translate "is invalid" in the "errors" domain
# dgettext("errors", "is invalid")
#
# # Translate the number of files with plural rules
# dngettext("errors", "1 file", "%{count} files", count)
#
# Because the error messages we show in our forms and APIs
# are defined inside Ecto, we need to translate them dynamically.
# This requires us to call the Gettext module passing our gettext
# backend as first argument.
#
# Note we use the "errors" domain, which means translations
# should be written to the errors.po file. The :count option is
# set by Ecto and indicates we should also apply plural rules.
if count = opts[:count] do
Gettext.dngettext(<%= web_namespace %>.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(<%= web_namespace %>.Gettext, "errors", msg, opts)
end
end
end
| 34.044444 | 86 | 0.659269 |
e813c5bcae8a61236d1b12bdc1ef75c96aa7cc07 | 1,660 | exs | Elixir | test/serializer_test.exs | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | null | null | null | test/serializer_test.exs | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | null | null | null | test/serializer_test.exs | merchant-ly/ex_elasticlunr | b7d12f3e567f1ecad1bfb402a062edd4d58ef9fd | [
"MIT"
] | null | null | null | defmodule Elasticlunr.SerializerTest do
use ExUnit.Case
alias Elasticlunr.{Index, Serializer}
test "serialize index without documents" do
index = Index.new(name: "index")
structure = [
"settings#name:index|ref:id|pipeline:",
"field#name:id|pipeline:Elixir.Elasticlunr.Index.IdPipeline|store_documents:false|store_positions:false",
"documents#id|{}"
]
data = Serializer.serialize(index) |> Enum.into([])
assert structure == data
end
test "serialize index with documents" do
index =
Index.new(name: "index")
|> Index.add_field("body")
|> Index.add_documents([%{"id" => 1, "body" => "hello world"}])
structure = [
"settings#name:index|ref:id|pipeline:",
"field#name:body|pipeline:|store_documents:true|store_positions:true",
"field#name:id|pipeline:Elixir.Elasticlunr.Index.IdPipeline|store_documents:false|store_positions:false",
"documents#body|{\"1\":\"hello world\"}",
"documents#id|{}",
"token#field:body|{\"documents\":[1],\"idf\":0.6989700043360187,\"norm\":0.7071067811865475,\"term\":\"hello\",\"terms\":{\"1\":{\"positions\":[[0,5]],\"total\":1}},\"tf\":{\"1\":1.0}}",
"token#field:body|{\"documents\":[1],\"idf\":0.6989700043360187,\"norm\":0.7071067811865475,\"term\":\"world\",\"terms\":{\"1\":{\"positions\":[[6,5]],\"total\":1}},\"tf\":{\"1\":1.0}}",
"token#field:id|{\"documents\":[1],\"idf\":0.6989700043360187,\"norm\":1.0,\"term\":\"1\",\"terms\":{\"1\":{\"positions\":[[0,1]],\"total\":1}},\"tf\":{\"1\":1.0}}"
]
data = Serializer.serialize(index) |> Enum.into([])
assert structure == data
end
end
| 39.52381 | 192 | 0.611446 |
e8140db8d5147c697f4ccbea8691a02e2ce3fd6a | 4,476 | ex | Elixir | lib/web/views/export_view.ex | jennstein2017/Challenge_gov | e0820df8b124a32ff8b78cb827ae43551492988b | [
"CC0-1.0"
] | 9 | 2020-02-26T20:24:38.000Z | 2022-03-22T21:14:52.000Z | lib/web/views/export_view.ex | jennstein2017/Challenge_gov | e0820df8b124a32ff8b78cb827ae43551492988b | [
"CC0-1.0"
] | 15 | 2020-04-22T19:33:24.000Z | 2022-03-26T15:11:17.000Z | lib/web/views/export_view.ex | jennstein2017/Challenge_gov | e0820df8b124a32ff8b78cb827ae43551492988b | [
"CC0-1.0"
] | 4 | 2020-04-27T22:58:57.000Z | 2022-01-14T13:42:09.000Z | NimbleCSV.define(ChallengeGov.Export.CSV, separator: ",", escape: "\"")
defmodule Web.ExportView do
use Web, :view
alias ChallengeGov.Export.CSV
alias Web.Api.ChallengeView
def format_content(challenge, format) do
case format do
"json" ->
{:ok, challenge_json(challenge)}
"csv" ->
{:ok, challenge_csv(challenge)}
_ ->
{:error, :invalid_format}
end
end
def challenge_csv(challenge) do
CSV.dump_to_iodata([csv_headers(challenge), csv_content(challenge)])
end
defp csv_headers(challenge) do
[
"ID",
"UUID",
"Status",
"Managers",
"Challenge manager of record",
"Challenge manager email",
"Point of contact email",
"Lead agency",
"Federal partners",
"Non federal partners",
"Fiscal year",
"Title",
"Tagline",
"Types",
"Custom url",
"External url",
"Brief description",
"Description",
# "Supporting documents",
# "Uploading own logo",
# "Logo",
"Auto publish date",
"Multi phase challenge"
]
|> Enum.concat(phase_headers(challenge))
|> Enum.concat(timeline_headers(challenge))
|> Enum.concat([
"Prize type",
"Prize total",
"Non monetary prizes",
"Prize description",
"Eligibility requirements",
"Terms same as rules",
"Rules",
"Terms and conditions",
"Legal authority",
"Frequently asked questions"
])
end
defp csv_content(challenge) do
[
challenge.id,
challenge.uuid,
Web.ChallengeView.status_display_name(challenge),
Web.ChallengeView.challenge_managers_list(challenge),
challenge.challenge_manager,
challenge.challenge_manager_email,
challenge.poc_email,
Web.ChallengeView.agency_name(challenge),
Web.ChallengeView.federal_partners_list(challenge),
Web.ChallengeView.non_federal_partners_list(challenge),
challenge.fiscal_year,
challenge.title,
challenge.tagline,
Web.ChallengeView.types(challenge),
Web.ChallengeView.custom_url(challenge),
challenge.external_url,
challenge.brief_description,
challenge.description,
challenge.auto_publish_date,
challenge.is_multi_phase
]
|> Enum.concat(phase_data(challenge))
|> Enum.concat(timeline_data(challenge))
|> Enum.concat([
challenge.prize_type,
challenge.prize_total,
challenge.non_monetary_prizes,
challenge.prize_description,
challenge.eligibility_requirements,
challenge.terms_equal_rules,
challenge.rules,
challenge.terms_and_conditions,
challenge.legal_authority,
challenge.faq
])
end
defp phase_headers(challenge) do
phases = challenge.phases
if length(phases) > 0 do
Enum.reduce(1..length(phases), [], fn phase_number, headers ->
Enum.concat(headers, [
"Phase #{phase_number} title",
"Phase #{phase_number} start date",
"Phase #{phase_number} end date",
"Phase #{phase_number} open to submissions",
"Phase #{phase_number} judging criteria",
"Phase #{phase_number} how to enter"
])
end)
else
[]
end
end
defp phase_data(challenge) do
phases = challenge.phases
if length(phases) > 0 do
Enum.reduce(phases, [], fn phase, headers ->
Enum.concat(headers, [
phase.title,
phase.start_date,
phase.end_date,
phase.open_to_submissions,
phase.judging_criteria,
phase.how_to_enter
])
end)
else
[]
end
end
defp timeline_headers(challenge) do
events = challenge.timeline_events
if length(events) > 0 do
Enum.reduce(1..length(events), [], fn event_number, headers ->
Enum.concat(headers, [
"Timeline event #{event_number} title",
"Timeline event #{event_number} date"
])
end)
else
[]
end
end
defp timeline_data(challenge) do
events = challenge.timeline_events
if length(events) > 0 do
Enum.reduce(events, [], fn event, headers ->
Enum.concat(headers, [
event.title,
event.date
])
end)
else
[]
end
end
def challenge_json(challenge) do
{:ok, json} =
challenge
|> ChallengeView.to_json()
|> Jason.encode()
json
end
end
| 24.326087 | 72 | 0.613271 |
e8140dceda205344b8b0873ccabccdc51ad9c4b6 | 3,605 | ex | Elixir | clients/sheets/lib/google_api/sheets/v4/model/sort_spec.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/sheets/lib/google_api/sheets/v4/model/sort_spec.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/sheets/lib/google_api/sheets/v4/model/sort_spec.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.Sheets.V4.Model.SortSpec do
@moduledoc """
A sort order associated with a specific column or row.
## Attributes
* `backgroundColor` (*type:* `GoogleApi.Sheets.V4.Model.Color.t`, *default:* `nil`) - The background fill color to sort by; cells with this fill color are sorted to the top. Mutually exclusive with foreground_color.
* `backgroundColorStyle` (*type:* `GoogleApi.Sheets.V4.Model.ColorStyle.t`, *default:* `nil`) - The background fill color to sort by; cells with this fill color are sorted to the top. Mutually exclusive with foreground_color, and must be an RGB-type color. If background_color is also set, this field takes precedence.
* `dataSourceColumnReference` (*type:* `GoogleApi.Sheets.V4.Model.DataSourceColumnReference.t`, *default:* `nil`) - Reference to a data source column.
* `dimensionIndex` (*type:* `integer()`, *default:* `nil`) - The dimension the sort should be applied to.
* `foregroundColor` (*type:* `GoogleApi.Sheets.V4.Model.Color.t`, *default:* `nil`) - The foreground color to sort by; cells with this foreground color are sorted to the top. Mutually exclusive with background_color.
* `foregroundColorStyle` (*type:* `GoogleApi.Sheets.V4.Model.ColorStyle.t`, *default:* `nil`) - The foreground color to sort by; cells with this foreground color are sorted to the top. Mutually exclusive with background_color, and must be an RGB-type color. If foreground_color is also set, this field takes precedence.
* `sortOrder` (*type:* `String.t`, *default:* `nil`) - The order data should be sorted.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:backgroundColor => GoogleApi.Sheets.V4.Model.Color.t() | nil,
:backgroundColorStyle => GoogleApi.Sheets.V4.Model.ColorStyle.t() | nil,
:dataSourceColumnReference =>
GoogleApi.Sheets.V4.Model.DataSourceColumnReference.t() | nil,
:dimensionIndex => integer() | nil,
:foregroundColor => GoogleApi.Sheets.V4.Model.Color.t() | nil,
:foregroundColorStyle => GoogleApi.Sheets.V4.Model.ColorStyle.t() | nil,
:sortOrder => String.t() | nil
}
field(:backgroundColor, as: GoogleApi.Sheets.V4.Model.Color)
field(:backgroundColorStyle, as: GoogleApi.Sheets.V4.Model.ColorStyle)
field(:dataSourceColumnReference, as: GoogleApi.Sheets.V4.Model.DataSourceColumnReference)
field(:dimensionIndex)
field(:foregroundColor, as: GoogleApi.Sheets.V4.Model.Color)
field(:foregroundColorStyle, as: GoogleApi.Sheets.V4.Model.ColorStyle)
field(:sortOrder)
end
defimpl Poison.Decoder, for: GoogleApi.Sheets.V4.Model.SortSpec do
def decode(value, options) do
GoogleApi.Sheets.V4.Model.SortSpec.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Sheets.V4.Model.SortSpec do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 54.621212 | 323 | 0.732039 |
e814258c87de56c9c3339bc5d9ce79745e066f70 | 7,031 | ex | Elixir | farmbot_os/lib/farmbot_os/sys_calls.ex | EarthEngineering/facetop_os | c82a7f1e8098d3a03dddbd2f2cb46cda7b88b6fb | [
"MIT"
] | null | null | null | farmbot_os/lib/farmbot_os/sys_calls.ex | EarthEngineering/facetop_os | c82a7f1e8098d3a03dddbd2f2cb46cda7b88b6fb | [
"MIT"
] | null | null | null | farmbot_os/lib/farmbot_os/sys_calls.ex | EarthEngineering/facetop_os | c82a7f1e8098d3a03dddbd2f2cb46cda7b88b6fb | [
"MIT"
] | null | null | null | defmodule FarmbotOS.SysCalls do
@moduledoc """
Implementation for FarmbotCeleryScript.SysCalls
"""
require FarmbotCore.Logger
require FarmbotTelemetry
require Logger
alias FarmbotCeleryScript.AST
alias FarmbotFirmware
alias FarmbotCore.Asset.{
BoxLed,
Private
}
alias FarmbotOS.SysCalls.{
ChangeOwnership,
CheckUpdate,
Farmware,
FactoryReset,
FlashFirmware,
SendMessage,
SetPinIOMode,
PinControl,
ResourceUpdate,
Movement,
PointLookup
}
alias FarmbotOS.Lua
alias FarmbotCore.{Asset, Asset.Private, Asset.Sync, BotState, Leds}
alias FarmbotExt.{API, API.SyncGroup, API.Reconciler}
@behaviour FarmbotCeleryScript.SysCalls
@impl true
defdelegate send_message(level, message, channels), to: SendMessage
@impl true
defdelegate execute_script(name, env), to: Farmware
@impl true
defdelegate update_farmware(name), to: Farmware
@impl true
defdelegate flash_firmware(package), to: FlashFirmware
@impl true
defdelegate change_ownership(email, secret, server), to: ChangeOwnership
@impl true
defdelegate check_update(), to: CheckUpdate
@impl true
defdelegate read_status(), to: FarmbotExt.AMQP.BotStateChannel
@impl true
defdelegate factory_reset(package), to: FactoryReset
@impl true
defdelegate set_pin_io_mode(pin, mode), to: SetPinIOMode
@impl true
defdelegate eval_assertion(comment, expression), to: Lua
defdelegate log_assertion(passed?, type, message), to: Lua
@impl true
defdelegate read_pin(number, mode), to: PinControl
@impl true
defdelegate read_cached_pin(number), to: PinControl
@impl true
defdelegate write_pin(number, mode, value), to: PinControl
@impl true
defdelegate toggle_pin(number), to: PinControl
@impl true
defdelegate set_servo_angle(pin, angle), to: PinControl
@impl true
defdelegate resource_update(kind, id, params), to: ResourceUpdate
@impl true
defdelegate get_current_x(), to: Movement
@impl true
defdelegate get_current_y(), to: Movement
@impl true
defdelegate get_current_z(), to: Movement
@impl true
defdelegate get_cached_x(), to: Movement
@impl true
defdelegate get_cached_y(), to: Movement
@impl true
defdelegate get_cached_z(), to: Movement
@impl true
defdelegate zero(axis), to: Movement
defdelegate get_position(), to: Movement
defdelegate get_position(axis), to: Movement
defdelegate get_cached_position(), to: Movement
defdelegate get_cached_position(axis), to: Movement
@impl true
defdelegate move_absolute(x, y, z, speed), to: Movement
@impl true
defdelegate calibrate(axis), to: Movement
@impl true
defdelegate find_home(axis), to: Movement
@impl true
defdelegate home(axis, speed), to: Movement
@impl true
defdelegate point(kind, id), to: PointLookup
# TODO(RICK) This may not be used anymore by CSRT.
# @impl true
# defdelegate get_point_group(type_or_id), to: PointLookup
@impl true
defdelegate find_points_via_group(id), to: Asset
@impl true
defdelegate get_toolslot_for_tool(id), to: PointLookup
@impl true
def log(message, force?) do
if force? || FarmbotCore.Asset.fbos_config(:sequence_body_log) do
FarmbotCore.Logger.info(2, message)
:ok
else
:ok
end
end
@impl true
def sequence_init_log(message) do
if FarmbotCore.Asset.fbos_config(:sequence_init_log) do
FarmbotCore.Logger.info(2, message)
:ok
else
:ok
end
end
@impl true
def sequence_complete_log(message) do
if FarmbotCore.Asset.fbos_config(:sequence_complete_log) do
FarmbotCore.Logger.info(2, message)
:ok
else
:ok
end
end
@impl true
def reboot do
FarmbotOS.System.reboot("Reboot requested by Sequence or frontend")
:ok
end
@impl true
def power_off do
FarmbotOS.System.shutdown("Shut down requested by Sequence or frontend")
:ok
end
@impl true
def firmware_reboot do
GenServer.stop(FarmbotFirmware, :reboot)
end
@impl true
def set_user_env(key, value) do
with {:ok, fwe} <- Asset.new_farmware_env(%{key: key, value: value}),
_ <- Private.mark_dirty!(fwe) do
:ok
else
{:error, reason} ->
{:error, inspect(reason)}
error ->
{:error, inspect(error)}
end
end
@impl true
def emergency_lock do
_ = FarmbotFirmware.command({:command_emergency_lock, []})
:ok
end
@impl true
def emergency_unlock do
_ = FarmbotFirmware.command({:command_emergency_unlock, []})
:ok
end
@impl true
def wait(ms) do
Process.sleep(ms)
:ok
end
@impl true
def named_pin("Peripheral", id) do
case Asset.get_peripheral(id: id) do
%{} = peripheral -> peripheral
nil -> {:error, "Could not find peripheral by id: #{id}"}
end
end
def named_pin("Sensor", id) do
case Asset.get_sensor(id) do
%{} = sensor -> sensor
nil -> {:error, "Could not find peripheral by id: #{id}"}
end
end
def named_pin("BoxLed" <> id, _) do
%BoxLed{id: String.to_integer(id)}
end
def named_pin(kind, id) do
{:error, "unknown pin kind: #{kind} of id: #{id}"}
end
@impl true
def get_sequence(id) do
case Asset.get_sequence(id) do
nil ->
{:error, "sequence not found"}
%{} = sequence ->
ast = AST.decode(sequence)
args = Map.put(ast.args, :sequence_name, sequence.name)
%{%{ast | args: args} | meta: %{sequence_name: sequence.name}}
end
end
@impl true
def sync() do
FarmbotCore.Logger.busy(3, "Syncing")
with {:ok, sync_changeset} <- API.get_changeset(Sync),
:ok <- BotState.set_sync_status("syncing"),
_ <- Leds.green(:really_fast_blink),
sync_changeset <-
Reconciler.sync_group(sync_changeset, SyncGroup.group_0()),
sync_changeset <-
Reconciler.sync_group(sync_changeset, SyncGroup.group_1()),
sync_changeset <-
Reconciler.sync_group(sync_changeset, SyncGroup.group_2()),
sync_changeset <-
Reconciler.sync_group(sync_changeset, SyncGroup.group_3()),
_sync_changeset <-
Reconciler.sync_group(sync_changeset, SyncGroup.group_4()) do
FarmbotCore.Logger.success(3, "Synced")
:ok = BotState.set_sync_status("synced")
_ = Leds.green(:solid)
:ok
else
error ->
FarmbotTelemetry.event(:asset_sync, :sync_error, nil,
error: inspect(error)
)
:ok = BotState.set_sync_status("sync_error")
_ = Leds.green(:slow_blink)
{:error, inspect(error)}
end
end
@impl true
def coordinate(x, y, z) do
%{x: x, y: y, z: z}
end
@impl true
def install_first_party_farmware() do
{:error, "install_first_party_farmware not yet supported"}
end
@impl true
def nothing(), do: nil
def give_firmware_reason(where, reason) do
w = inspect(where)
r = inspect(reason)
{:error, "Firmware error @ #{w}: #{r}"}
end
end
| 22.680645 | 76 | 0.672735 |
e8143f79363a2a5d6f117f3fb1931f1c14e55a6d | 252 | ex | Elixir | lib/slax/projects/project_repo.ex | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | 11 | 2016-07-05T18:56:21.000Z | 2021-09-15T22:23:54.000Z | lib/slax/projects/project_repo.ex | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | 181 | 2016-06-23T00:47:13.000Z | 2022-03-10T11:23:44.000Z | lib/slax/projects/project_repo.ex | HoffsMH/slax | b91ee30b9fd71a4cb7826f50b605ce580b7c1651 | [
"MIT"
] | 7 | 2019-01-30T21:38:28.000Z | 2022-03-01T07:13:39.000Z | defmodule Slax.ProjectRepo do
@moduledoc false
use Slax.Schema
@type t :: %__MODULE__{}
schema "project_repos" do
belongs_to(:project, Slax.Project)
field(:org_name, :string)
field(:repo_name, :string)
timestamps()
end
end
| 16.8 | 38 | 0.68254 |
e81456101885516250fbd9c346aacd0b23f9c8e0 | 1,645 | ex | Elixir | lib/redix_clustered/clone.ex | PRX/redix-clustered | 46d5826fdcd877ba9794e083260b5bcc784b8a9e | [
"MIT"
] | null | null | null | lib/redix_clustered/clone.ex | PRX/redix-clustered | 46d5826fdcd877ba9794e083260b5bcc784b8a9e | [
"MIT"
] | null | null | null | lib/redix_clustered/clone.ex | PRX/redix-clustered | 46d5826fdcd877ba9794e083260b5bcc784b8a9e | [
"MIT"
] | null | null | null | defmodule RedixClustered.Clone do
@moduledoc """
Conditionally clone write requests to a separate RedixClustered
"""
alias RedixClustered.Options
@clone_commands [
"APPEND",
"DECR",
"DECRBY",
"DEL",
"EXPIRE",
"EXPIREAT",
"GETSET",
"HDEL",
"HINCRBY",
"HINCRBYFLOAT",
"HMSET",
"HSET",
"HSETNX",
"INCR",
"INCRBY",
"INCRBYFLOAT",
"MSET",
"MSETNX",
"PEXPIRE",
"PEXPIREAT",
"PSETEX",
"PTTL",
"SET",
"SETEX",
"SETNX",
"SETRANGE",
"UNLINK"
]
def needs_cloning?([command | rest]) when is_list(command) do
needs_cloning?(command) || needs_cloning?(rest)
end
def needs_cloning?(["" <> cmd | _args]) do
String.upcase(cmd) in @clone_commands
end
def needs_cloning?(_), do: false
def clone_alive?(cluster_name) do
Options.clone_cluster_name(cluster_name) |> RedixClustered.alive?()
end
def clone_command(cluster_name, cmd, opts \\ []) do
case {clone_alive?(cluster_name), needs_cloning?(cmd)} do
{false, _} ->
{:disabled}
{_, false} ->
{:readonly}
_ ->
clone_cluster_name = Options.clone_cluster_name(cluster_name)
RedixClustered.command(clone_cluster_name, cmd, opts)
end
end
def clone_pipeline(cluster_name, cmds, opts \\ []) do
case {clone_alive?(cluster_name), needs_cloning?(cmds)} do
{false, _} ->
{:disabled}
{_, false} ->
{:readonly}
_ ->
clone_cluster_name = Options.clone_cluster_name(cluster_name)
RedixClustered.pipeline(clone_cluster_name, cmds, opts)
end
end
end
| 20.5625 | 71 | 0.606687 |
e8149973cadcaae18bdb4fe1db495fd3b0347cd1 | 1,195 | exs | Elixir | test/level_web/graphql/subscriptions/space_joined_test.exs | mindriot101/level | 0a2cbae151869c2d9b79b3bfb388f5d00739ae12 | [
"Apache-2.0"
] | 928 | 2018-04-03T16:18:11.000Z | 2019-09-09T17:59:55.000Z | test/level_web/graphql/subscriptions/space_joined_test.exs | mindriot101/level | 0a2cbae151869c2d9b79b3bfb388f5d00739ae12 | [
"Apache-2.0"
] | 74 | 2018-04-03T00:46:50.000Z | 2019-03-10T18:57:27.000Z | test/level_web/graphql/subscriptions/space_joined_test.exs | mindriot101/level | 0a2cbae151869c2d9b79b3bfb388f5d00739ae12 | [
"Apache-2.0"
] | 89 | 2018-04-03T17:33:20.000Z | 2019-08-19T03:40:20.000Z | defmodule LevelWeb.GraphQL.SpaceJoinedTest do
use LevelWeb.ChannelCase
@operation """
subscription UserSubscription {
userSubscription {
__typename
... on SpaceJoinedPayload {
space {
id
name
}
spaceUser {
userId
}
}
}
}
"""
setup do
{:ok, user} = create_user()
{:ok, %{socket: build_socket(user), user: user}}
end
test "receives an event when a user creates a space", %{socket: socket, user: user} do
ref = push_subscription(socket, @operation, %{})
assert_reply(ref, :ok, %{subscriptionId: subscription_id}, 1000)
{:ok, %{space: space}} = create_space(user, %{name: "MySpace"})
push_data = %{
result: %{
data: %{
"userSubscription" => %{
"__typename" => "SpaceJoinedPayload",
"space" => %{
"id" => space.id,
"name" => "MySpace"
},
"spaceUser" => %{
"userId" => user.id
}
}
}
},
subscriptionId: subscription_id
}
assert_push("subscription:data", ^push_data)
end
end
| 22.54717 | 88 | 0.500418 |
e814a213e77c565dd0937fcb51582c86685d2106 | 14,699 | ex | Elixir | lib/scenic/component/input/dropdown.ex | tiger808/scenic | 77abc6d891b7a1a9262cdc47d7c5fac3c8609d1f | [
"Apache-2.0"
] | 1,716 | 2018-09-07T21:55:43.000Z | 2022-03-31T16:16:30.000Z | lib/scenic/component/input/dropdown.ex | tiger808/scenic | 77abc6d891b7a1a9262cdc47d7c5fac3c8609d1f | [
"Apache-2.0"
] | 220 | 2018-09-08T01:28:00.000Z | 2022-03-22T03:55:17.000Z | lib/scenic/component/input/dropdown.ex | tiger808/scenic | 77abc6d891b7a1a9262cdc47d7c5fac3c8609d1f | [
"Apache-2.0"
] | 137 | 2018-09-07T21:55:56.000Z | 2022-03-26T04:07:27.000Z | #
# Created by Boyd Multerer 2018-07-15.
# Copyright © 2018 Kry10 Industries. All rights reserved.
#
defmodule Scenic.Component.Input.Dropdown do
@moduledoc """
Add a dropdown to a graph
## Data
`{items, initial_item}`
* `items` - must be a list of items, each of which is: `{text, id}`. See below...
* `initial_item` - the `id` of the initial selected item. It can be any term
you want, however it must be an `item_id` in the `items` list. See below.
Per item data:
`{text, item_id}`
* `text` - a string that will be shown in the dropdown.
* `item_id` - any term you want. It will identify the item that is
currently selected in the dropdown and will be passed back to you during
event messages.
## Messages
When the state of the checkbox, it sends an event message to the host scene
in the form of:
`{:value_changed, id, selected_item_id}`
## Options
Dropdowns honor the following list of options.
## Styles
Buttons honor the following styles
* `:hidden` - If `false` the component is rendered. If `true`, it is skipped.
The default is `false`.
* `:theme` - The color set used to draw. See below. The default is `:dark`
## Additional Styles
Buttons honor the following list of additional styles.
* `:width` - pass in a number to set the width of the button.
* `:height` - pass in a number to set the height of the button.
* `:direction` - what direction should the menu drop. Can be either `:down`
or `:up`. The default is `:down`.
## Theme
Dropdowns work well with the following predefined themes: `:light`, `:dark`
To pass in a custom theme, supply a map with at least the following entries:
* `:text` - the color of the text
* `:background` - the background of the component
* `:border` - the border of the component
* `:active` - the background of selected item in the dropdown list
* `:thumb` - the color of the item being hovered over
## Usage
You should add/modify components via the helper functions in
[`Scenic.Components`](Scenic.Components.html#dropdown/3)
## Examples
The following example creates a dropdown and positions it on the screen.
graph
|> dropdown({[
{"Dashboard", :dashboard},
{"Controls", :controls},
{"Primitives", :primitives}
], :controls}, id: :dropdown_id, translate: {20, 20})
"""
use Scenic.Component, has_children: false
alias Scenic.Graph
alias Scenic.ViewPort
alias Scenic.Primitive.Style.Theme
import Scenic.Primitives
# import IEx
@default_direction :down
@default_font :roboto
@default_font_size 20
@drop_click_window_ms 400
@caret {{0, 0}, {12, 0}, {6, 6}}
@text_id :__dropbox_text__
@caret_id :__caret__
@dropbox_id :__dropbox__
@button_id :__dropbox_btn__
@rotate_neutral :math.pi() / 2
@rotate_down 0
@rotate_up :math.pi()
# --------------------------------------------------------
@doc false
def info(data) do
"""
#{IO.ANSI.red()}Dropdown data must be: {items, initial}
#{IO.ANSI.yellow()}Received: #{inspect(data)}
#{IO.ANSI.default_color()}
"""
end
# --------------------------------------------------------
@doc false
def verify({items, initial} = data) when is_list(items) do
(Enum.all?(items, &verify_item(&1)) &&
Enum.find_value(items, false, fn {_, id} -> id == initial end))
|> case do
true -> {:ok, data}
_ -> :invalid_data
end
end
def verify(_), do: :invalid_data
# --------------------------------------------------------
defp verify_item({text, _}) when is_bitstring(text), do: true
defp verify_item(_), do: false
# --------------------------------------------------------
@doc false
# credo:disable-for-next-line Credo.Check.Refactor.CyclomaticComplexity
def init({items, initial_id}, opts) do
id = opts[:id]
styles = opts[:styles]
# theme is passed in as an inherited style
theme =
(styles[:theme] || Theme.preset(:dark))
|> Theme.normalize()
# font related info
fm = Scenic.Cache.Static.FontMetrics.get!(@default_font)
ascent = FontMetrics.ascent(@default_font_size, fm)
descent = FontMetrics.descent(@default_font_size, fm)
# find the width of the widest item
fm_width =
Enum.reduce(items, 0, fn {text, _}, w ->
width = FontMetrics.width(text, @default_font_size, fm)
max(w, width)
end)
width =
case styles[:width] || opts[:w] do
nil -> fm_width + ascent * 3
:auto -> fm_width + ascent * 3
width when is_number(width) and width > 0 -> width
end
height =
case styles[:height] || opts[:h] do
nil -> @default_font_size + ascent
:auto -> @default_font_size + ascent
height when is_number(height) and height > 0 -> height
end
# get the initial text
initial_text =
Enum.find_value(items, "", fn
{text, ^initial_id} -> text
_ -> false
end)
# calculate the drop box measures
item_count = Enum.count(items)
drop_height = item_count * height
# get the drop direction
direction = styles[:direction] || @default_direction
# calculate the where to put the drop box. Depends on the direction
translate_menu =
case direction do
:down -> {0, height + 1}
:up -> {0, height * -item_count - 1}
end
# get the direction to rotate the caret
rotate_caret =
case direction do
:down -> @rotate_down
:up -> -@rotate_up
end
text_vpos = height / 2 + ascent / 2 + descent / 3
graph =
Graph.build(font: @default_font, font_size: @default_font_size)
|> rect({width, height}, fill: theme.background, stroke: {2, theme.border})
|> text(initial_text,
fill: theme.text,
translate: {8, text_vpos},
text_align: :left,
id: @text_id
)
|> triangle(@caret,
fill: theme.text,
translate: {width - 18, height * 0.5},
pin: {6, 0},
rotate: @rotate_neutral,
id: @caret_id
)
# an invisible rect for hit-test purposes
|> rect({width, height}, id: @button_id)
# the drop box itself
|> group(
fn g ->
g = rect(g, {width, drop_height}, fill: theme.background, stroke: {2, theme.border})
{g, _} =
Enum.reduce(items, {g, 0}, fn {text, id}, {g, i} ->
g =
group(
g,
# credo:disable-for-next-line Credo.Check.Refactor.Nesting
fn g ->
rect(
g,
{width, height},
fill:
if id == initial_id do
theme.active
else
theme.background
end,
id: id
)
|> text(text,
fill: theme.text,
text_align: :left,
translate: {8, text_vpos}
)
end,
translate: {0, height * i}
)
{g, i + 1}
end)
g
end,
translate: translate_menu,
id: @dropbox_id,
hidden: true
)
state = %{
graph: graph,
selected_id: initial_id,
theme: theme,
id: id,
down: false,
hover_id: nil,
items: items,
drop_time: 0,
rotate_caret: rotate_caret
}
{:ok, state, push: graph}
end
# ============================================================================
# tracking when the dropdown is UP
# --------------------------------------------------------
@doc false
def handle_input({:cursor_enter, _uid}, %{id: id}, %{down: false} = state) do
{:noreply, %{state | hover_id: id}}
end
# --------------------------------------------------------
def handle_input({:cursor_exit, _uid}, _context, %{down: false} = state) do
{:noreply, %{state | hover_id: nil}}
end
# --------------------------------------------------------
def handle_input(
{:cursor_button, {:left, :press, _, _}},
%{id: @button_id} = context,
%{down: false, graph: graph, rotate_caret: rotate_caret} = state
) do
# capture input
ViewPort.capture_input(context, [:cursor_button, :cursor_pos])
# drop the menu
graph =
graph
|> Graph.modify(@caret_id, &update_opts(&1, rotate: rotate_caret))
|> Graph.modify(@dropbox_id, &update_opts(&1, hidden: false))
state =
state
|> Map.put(:down, true)
|> Map.put(:drop_time, :os.system_time(:milli_seconds))
|> Map.put(:graph, graph)
{:noreply, state, push: graph}
end
# ============================================================================
# tracking when the dropdown is DOWN
# --------------------------------------------------------
def handle_input(
{:cursor_enter, _uid},
%{id: id},
%{down: true, items: items, graph: graph, selected_id: selected_id, theme: theme} = state
) do
# set the appropriate hilighting for each of the items
graph = update_highlighting(graph, items, selected_id, id, theme)
{:noreply, %{state | hover_id: id, graph: graph}, push: graph}
end
# --------------------------------------------------------
def handle_input(
{:cursor_exit, _uid},
_context,
%{down: true, items: items, graph: graph, selected_id: selected_id, theme: theme} = state
) do
# set the appropriate hilighting for each of the items
graph = update_highlighting(graph, items, selected_id, nil, theme)
{:noreply, %{state | hover_id: nil, graph: graph}, push: graph}
end
# --------------------------------------------------------
# the mouse is pressed outside of the dropdown when it is down.
# immediately close the dropdown and allow the event to continue
def handle_input(
{:cursor_button, {:left, :press, _, _}},
%{id: nil} = context,
%{
down: true,
items: items,
theme: theme,
selected_id: selected_id
} = state
) do
# release the input capture
ViewPort.release_input(context, [:cursor_button, :cursor_pos])
graph = handle_cursor_button(state.graph, items, selected_id, theme)
{:noreply, %{state | down: false, graph: graph}, push: graph}
end
# --------------------------------------------------------
# clicking the button when down, raises it back up without doing anything else
def handle_input(
{:cursor_button, {:left, :release, _, _}},
%{id: @button_id} = context,
%{
down: true,
drop_time: drop_time,
theme: theme,
items: items,
graph: graph,
selected_id: selected_id
} = state
) do
if :os.system_time(:milli_seconds) - drop_time <= @drop_click_window_ms do
# we are still in the click window, leave the menu down.
{:noreply, state}
else
# we are outside the window, raise it back up
graph =
graph
|> update_highlighting(items, selected_id, nil, theme)
|> Graph.modify(@caret_id, &update_opts(&1, rotate: @rotate_neutral))
|> Graph.modify(@dropbox_id, &update_opts(&1, hidden: true))
# release the input capture
ViewPort.release_input(context, [:cursor_button, :cursor_pos])
{:noreply, %{state | down: false, hover_id: nil, graph: graph}, push: graph}
end
end
# --------------------------------------------------------
# the button is released outside the dropdown space
def handle_input(
{:cursor_button, {:left, :release, _, _}},
%{id: nil} = context,
%{
down: true,
items: items,
theme: theme,
selected_id: selected_id
} = state
) do
# release the input capture
ViewPort.release_input(context, [:cursor_button, :cursor_pos])
graph = handle_cursor_button(state.graph, items, selected_id, theme)
{:noreply, %{state | down: false, graph: graph}, push: graph}
end
# --------------------------------------------------------
# the button is realeased over an item in dropdown
def handle_input(
{:cursor_button, {:left, :release, _, _}},
%{id: item_id} = context,
%{
down: true,
id: id,
items: items,
theme: theme
} = state
) do
# release the input capture
ViewPort.release_input(context, [:cursor_button, :cursor_pos])
# send the value_changed message
send_event({:value_changed, id, item_id})
# find the newly selected item's text
{text, _} = Enum.find(items, fn {_, id} -> id == item_id end)
graph =
state.graph
# update the main button text
|> Graph.modify(@text_id, &text(&1, text))
# restore standard highliting
|> update_highlighting(items, item_id, nil, theme)
# raise the dropdown
|> Graph.modify(@caret_id, &update_opts(&1, rotate: @rotate_neutral))
|> Graph.modify(@dropbox_id, &update_opts(&1, hidden: true))
{:noreply, %{state | down: false, graph: graph, selected_id: item_id}, push: graph}
end
# ============================================================================
# unhandled input
# --------------------------------------------------------
def handle_input(_event, _context, state) do
{:noreply, state}
end
# ============================================================================
# internal
defp update_highlighting(graph, items, selected_id, hover_id, theme) do
# set the appropriate hilighting for each of the items
Enum.reduce(items, graph, fn
# this is the item the user is hovering over
{_, ^hover_id}, g ->
Graph.modify(g, hover_id, &update_opts(&1, fill: theme.thumb))
# this is the currently selected item
{_, ^selected_id}, g ->
Graph.modify(g, selected_id, &update_opts(&1, fill: theme.active))
# not selected, not hovered over
{_, regular_id}, g ->
Graph.modify(g, regular_id, &update_opts(&1, fill: theme.background))
end)
end
defp handle_cursor_button(graph, items, selected_id, theme) do
graph
# restore standard highliting
|> update_highlighting(items, selected_id, nil, theme)
# raise the dropdown
|> Graph.modify(@caret_id, &update_opts(&1, rotate: @rotate_neutral))
|> Graph.modify(@dropbox_id, &update_opts(&1, hidden: true))
end
end
| 29.936864 | 97 | 0.549425 |
e814b883c5a6a3b3d67d54ea881bdd0c16a73798 | 1,455 | ex | Elixir | lib/potionx/auth/assent_azure_common_strategy.ex | shuv1824/potionx | a5888413b13a520d8ddf79fb26b7483e441737c3 | [
"MIT"
] | 31 | 2021-02-16T20:50:46.000Z | 2022-02-03T10:38:07.000Z | lib/potionx/auth/assent_azure_common_strategy.ex | shuv1824/potionx | a5888413b13a520d8ddf79fb26b7483e441737c3 | [
"MIT"
] | 6 | 2021-04-07T21:50:20.000Z | 2022-02-06T21:54:04.000Z | lib/potionx/auth/assent_azure_common_strategy.ex | shuv1824/potionx | a5888413b13a520d8ddf79fb26b7483e441737c3 | [
"MIT"
] | 4 | 2021-03-25T17:59:44.000Z | 2021-04-25T16:28:22.000Z | defmodule Potionx.Auth.Assent.AzureADCommonStrategy do
@moduledoc false
use Assent.Strategy.OIDC.Base
alias Assent.{Config, Strategy.OIDC}
@impl true
def default_config(config) do
Keyword.merge(
[
authorization_params: [scope: "email profile", response_mode: "form_post"],
client_auth_method: :client_secret_post,
site: "https://login.microsoftonline.com/common/v2.0"
],
config
)
end
@impl true
def normalize(_config, user), do: {:ok, user}
@impl true
def fetch_user(config, token) do
with {:ok, issuer} <- fetch_iss(token["id_token"], config),
{:ok, config} <- update_issuer_in_config(config, issuer),
{:ok, jwt} <- OIDC.validate_id_token(config, token["id_token"]) do
Helpers.normalize_userinfo(jwt.claims)
end
end
defp fetch_iss(encoded, config) do
with [_, encoded, _] <- String.split(encoded, "."),
{:ok, json} <- Base.url_decode64(encoded, padding: false),
{:ok, claims} <- Config.json_library(config).decode(json) do
Map.fetch(claims, "iss")
else
{:error, error} -> {:error, error}
_any -> {:error, "The ID Token is not a valid JWT"}
end
end
defp update_issuer_in_config(config, issuer) do
openid_configuration = Map.put(config[:openid_configuration], "issuer", issuer)
{:ok, Keyword.put(config, :openid_configuration, openid_configuration)}
end
end
| 30.957447 | 83 | 0.64811 |
e814c0e87572099f79de9406b507368efeefca71 | 616 | exs | Elixir | apps/tai/test/tai/new_orders/transitions/accept_cancel_test.exs | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | null | null | null | apps/tai/test/tai/new_orders/transitions/accept_cancel_test.exs | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | 78 | 2020-10-12T06:21:43.000Z | 2022-03-28T09:02:00.000Z | apps/tai/test/tai/new_orders/transitions/accept_cancel_test.exs | yurikoval/tai | 94254b45d22fa0307b01577ff7c629c7280c0295 | [
"MIT"
] | null | null | null | defmodule Tai.NewOrders.Transitions.AcceptCancelTest do
use ExUnit.Case, async: false
alias Tai.NewOrders.Transitions
test ".attrs/1 returns a list of updatable order attributes" do
last_received_at = DateTime.utc_now()
last_venue_timestamp = DateTime.utc_now()
transition = %Transitions.AcceptCancel{last_received_at: last_received_at, last_venue_timestamp: last_venue_timestamp}
attrs = Transitions.AcceptCancel.attrs(transition)
assert length(attrs) == 2
assert attrs[:last_received_at] == last_received_at
assert attrs[:last_venue_timestamp] == last_venue_timestamp
end
end
| 38.5 | 122 | 0.784091 |
e814d53810f2784c593153a363c1206459af73b7 | 1,023 | exs | Elixir | mix.exs | timCF/wanted | d3d5eba7f59b24f99a2b0aaa5d54854ed57c1d10 | [
"Apache-2.0"
] | 1 | 2016-11-25T22:32:44.000Z | 2016-11-25T22:32:44.000Z | mix.exs | timCF/wanted | d3d5eba7f59b24f99a2b0aaa5d54854ed57c1d10 | [
"Apache-2.0"
] | null | null | null | mix.exs | timCF/wanted | d3d5eba7f59b24f99a2b0aaa5d54854ed57c1d10 | [
"Apache-2.0"
] | null | null | null | defmodule Wanted.Mixfile do
use Mix.Project
def project do
[app: :wanted,
version: "0.1.0",
elixir: "~> 1.3",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps()]
end
# Configuration for the OTP application
#
# Type "mix help compile.app" for more information
def application do
[applications: [:logger]]
end
# Dependencies can be Hex packages:
#
# {:mydep, "~> 0.3.0"}
#
# Or git/path repositories:
#
# {:mydep, git: "https://github.com/elixir-lang/mydep.git", tag: "0.1.0"}
#
# Type "mix help deps" for more examples and options
defp deps do
[]
end
defp description do
"""
Mix tasks for fast creating elixir web apps.
"""
end
defp package do
[files: ["lib", "mix.exs", "README.md", "LICENSE"],
maintainers: ["timCF"],
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/timCF/wanted"}]
end
end
| 20.877551 | 77 | 0.595308 |
e814e4e28c51a95e83268fe130ac48beaba1c38b | 1,241 | ex | Elixir | memorex/test/support/conn_case.ex | at7heb/liveview_elixirconf_2021 | eee64f38ec8a7365e8b728d76cd795a5c23199a9 | [
"MIT"
] | null | null | null | memorex/test/support/conn_case.ex | at7heb/liveview_elixirconf_2021 | eee64f38ec8a7365e8b728d76cd795a5c23199a9 | [
"MIT"
] | null | null | null | memorex/test/support/conn_case.ex | at7heb/liveview_elixirconf_2021 | eee64f38ec8a7365e8b728d76cd795a5c23199a9 | [
"MIT"
] | 6 | 2021-10-07T14:50:48.000Z | 2021-10-08T14:50:09.000Z | defmodule MemorexWeb.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
import other functionality to make it easier
to build common data structures and query the data layer.
Finally, if the test case interacts with the database,
we enable the SQL sandbox, so changes done to the database
are reverted at the end of every test. If you are using
PostgreSQL, you can even run database tests asynchronously
by setting `use MemorexWeb.ConnCase, async: true`, although
this option is not recommended for other databases.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
import Plug.Conn
import Phoenix.ConnTest
import MemorexWeb.ConnCase
alias MemorexWeb.Router.Helpers, as: Routes
# The default endpoint for testing
@endpoint MemorexWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Memorex.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Memorex.Repo, {:shared, self()})
end
{:ok, conn: Phoenix.ConnTest.build_conn()}
end
end
| 28.204545 | 69 | 0.724416 |
e814f18ed8a118f37c2699d703271704db44f72a | 2,082 | ex | Elixir | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/option.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/option.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/service_consumer_management/lib/google_api/service_consumer_management/v1/model/option.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.ServiceConsumerManagement.V1.Model.Option do
@moduledoc """
A protocol buffer option, which can be attached to a message, field,
enumeration, etc.
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - The option's name. For protobuf built-in options (options defined in
descriptor.proto), this is the short name. For example, `"map_entry"`.
For custom options, it should be the fully-qualified name. For example,
`"google.api.http"`.
* `value` (*type:* `map()`, *default:* `nil`) - The option's value packed in an Any message. If the value is a primitive,
the corresponding wrapper type defined in google/protobuf/wrappers.proto
should be used. If the value is an enum, it should be stored as an int32
value using the google.protobuf.Int32Value type.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t(),
:value => map()
}
field(:name)
field(:value, type: :map)
end
defimpl Poison.Decoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Option do
def decode(value, options) do
GoogleApi.ServiceConsumerManagement.V1.Model.Option.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ServiceConsumerManagement.V1.Model.Option do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 36.526316 | 125 | 0.719981 |
e81520015ec844c0231d8bc9785458e68dd84bea | 1,736 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/price.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/price.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/price.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.Price do
@moduledoc """
Represents a price and a pricing type for a product / deal.
## Attributes
* `amount` (*type:* `GoogleApi.AdExchangeBuyer.V2beta1.Model.Money.t`, *default:* `nil`) - The actual price with currency specified.
* `pricingType` (*type:* `String.t`, *default:* `nil`) - The pricing type for the deal/product. (default: CPM)
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:amount => GoogleApi.AdExchangeBuyer.V2beta1.Model.Money.t(),
:pricingType => String.t()
}
field(:amount, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.Money)
field(:pricingType)
end
defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.Price do
def decode(value, options) do
GoogleApi.AdExchangeBuyer.V2beta1.Model.Price.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.Price do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.72 | 136 | 0.733871 |
e8154afcefbf0abadfaa535b9804540fe1cc251c | 2,197 | exs | Elixir | test/controllers/project_controller_test.exs | RFmind/scrumapi | 3bc2caf48e4e9b5b5448fe0724815609fc4bcee2 | [
"MIT"
] | null | null | null | test/controllers/project_controller_test.exs | RFmind/scrumapi | 3bc2caf48e4e9b5b5448fe0724815609fc4bcee2 | [
"MIT"
] | null | null | null | test/controllers/project_controller_test.exs | RFmind/scrumapi | 3bc2caf48e4e9b5b5448fe0724815609fc4bcee2 | [
"MIT"
] | null | null | null | defmodule Scrumapi.ProjectControllerTest do
use Scrumapi.ConnCase
alias Scrumapi.Project
@valid_attrs %{description: "some content", name: "some content"}
@invalid_attrs %{}
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
test "lists all entries on index", %{conn: conn} do
conn = get conn, project_path(conn, :index)
assert json_response(conn, 200)["data"] == []
end
test "shows chosen resource", %{conn: conn} do
project = Repo.insert! %Project{}
conn = get conn, project_path(conn, :show, project)
assert json_response(conn, 200)["data"] == %{"id" => project.id,
"name" => project.name,
"description" => project.description}
end
test "renders page not found when id is nonexistent", %{conn: conn} do
assert_error_sent 404, fn ->
get conn, project_path(conn, :show, -1)
end
end
test "creates and renders resource when data is valid", %{conn: conn} do
conn = post conn, project_path(conn, :create), project: @valid_attrs
assert json_response(conn, 201)["data"]["id"]
assert Repo.get_by(Project, @valid_attrs)
end
test "does not create resource and renders errors when data is invalid", %{conn: conn} do
conn = post conn, project_path(conn, :create), project: @invalid_attrs
assert json_response(conn, 422)["errors"] != %{}
end
test "updates and renders chosen resource when data is valid", %{conn: conn} do
project = Repo.insert! %Project{}
conn = put conn, project_path(conn, :update, project), project: @valid_attrs
assert json_response(conn, 200)["data"]["id"]
assert Repo.get_by(Project, @valid_attrs)
end
test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do
project = Repo.insert! %Project{}
conn = put conn, project_path(conn, :update, project), project: @invalid_attrs
assert json_response(conn, 422)["errors"] != %{}
end
test "deletes chosen resource", %{conn: conn} do
project = Repo.insert! %Project{}
conn = delete conn, project_path(conn, :delete, project)
assert response(conn, 204)
refute Repo.get(Project, project.id)
end
end
| 35.435484 | 98 | 0.677742 |
e8155d84bc923c0bcbb23bc987c2b5c8440edb3f | 51,203 | ex | Elixir | lib/phoenix/controller.ex | achalagarwal/phoenix | 6534f05beda6696c50ca007d02c922fa168083d7 | [
"MIT"
] | 1 | 2022-01-17T05:04:27.000Z | 2022-01-17T05:04:27.000Z | lib/phoenix/controller.ex | achalagarwal/phoenix | 6534f05beda6696c50ca007d02c922fa168083d7 | [
"MIT"
] | null | null | null | lib/phoenix/controller.ex | achalagarwal/phoenix | 6534f05beda6696c50ca007d02c922fa168083d7 | [
"MIT"
] | null | null | null | defmodule Phoenix.Controller do
import Plug.Conn
alias Plug.Conn.AlreadySentError
require Logger
require Phoenix.Endpoint
@unsent [:unset, :set, :set_chunked, :set_file]
@moduledoc """
Controllers are used to group common functionality in the same
(pluggable) module.
For example, the route:
get "/users/:id", MyAppWeb.UserController, :show
will invoke the `show/2` action in the `MyAppWeb.UserController`:
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
def show(conn, %{"id" => id}) do
user = Repo.get(User, id)
render(conn, "show.html", user: user)
end
end
An action is a regular function that receives the connection
and the request parameters as arguments. The connection is a
`Plug.Conn` struct, as specified by the Plug library.
## Options
When used, the controller supports the following options:
* `:namespace` - sets the namespace to properly inflect
the layout view. By default it uses the base alias
in your controller name
* `:put_default_views` - controls whether the default view
and layout should be set or not
## Connection
A controller by default provides many convenience functions for
manipulating the connection, rendering templates, and more.
Those functions are imported from two modules:
* `Plug.Conn` - a collection of low-level functions to work with
the connection
* `Phoenix.Controller` - functions provided by Phoenix
to support rendering, and other Phoenix specific behaviour
If you want to have functions that manipulate the connection
without fully implementing the controller, you can import both
modules directly instead of `use Phoenix.Controller`.
## Plug pipeline
As with routers, controllers also have their own plug pipeline.
However, different from routers, controllers have a single pipeline:
defmodule MyAppWeb.UserController do
use MyAppWeb, :controller
plug :authenticate, usernames: ["jose", "eric", "sonny"]
def show(conn, params) do
# authenticated users only
end
defp authenticate(conn, options) do
if get_session(conn, :username) in options[:usernames] do
conn
else
conn |> redirect(to: "/") |> halt()
end
end
end
The `:authenticate` plug will be invoked before the action. If the
plug calls `Plug.Conn.halt/1` (which is by default imported into
controllers), it will halt the pipeline and won't invoke the action.
### Guards
`plug/2` in controllers supports guards, allowing a developer to configure
a plug to only run in some particular action:
plug :authenticate, [usernames: ["jose", "eric", "sonny"]] when action in [:show, :edit]
plug :authenticate, [usernames: ["admin"]] when not action in [:index]
The first plug will run only when action is show or edit. The second plug will
always run, except for the index action.
Those guards work like regular Elixir guards and the only variables accessible
in the guard are `conn`, the `action` as an atom and the `controller` as an
alias.
## Controllers are plugs
Like routers, controllers are plugs, but they are wired to dispatch
to a particular function which is called an action.
For example, the route:
get "/users/:id", UserController, :show
will invoke `UserController` as a plug:
UserController.call(conn, :show)
which will trigger the plug pipeline and which will eventually
invoke the inner action plug that dispatches to the `show/2`
function in `UserController`.
As controllers are plugs, they implement both [`init/1`](`c:Plug.init/1`) and
[`call/2`](`c:Plug.call/2`), and it also provides a function named `action/2`
which is responsible for dispatching the appropriate action
after the plug stack (and is also overridable).
### Overriding `action/2` for custom arguments
Phoenix injects an `action/2` plug in your controller which calls the
function matched from the router. By default, it passes the conn and params.
In some cases, overriding the `action/2` plug in your controller is a
useful way to inject arguments into your actions that you would otherwise
need to repeatedly fetch off the connection. For example, imagine if you
stored a `conn.assigns.current_user` in the connection and wanted quick
access to the user for every action in your controller:
def action(conn, _) do
args = [conn, conn.params, conn.assigns.current_user]
apply(__MODULE__, action_name(conn), args)
end
def index(conn, _params, user) do
videos = Repo.all(user_videos(user))
# ...
end
def delete(conn, %{"id" => id}, user) do
video = Repo.get!(user_videos(user), id)
# ...
end
## Rendering and layouts
One of the main features provided by controllers is the ability
to perform content negotiation and render templates based on
information sent by the client. Read `render/3` to learn more.
It is also important not to confuse `Phoenix.Controller.render/3`
with `Phoenix.View.render/3`. The former expects
a connection and relies on content negotiation while the latter is
connection-agnostic and typically invoked from your views.
"""
defmacro __using__(opts) do
quote bind_quoted: [opts: opts] do
import Phoenix.Controller
# TODO v2: No longer automatically import dependencies
import Plug.Conn
use Phoenix.Controller.Pipeline
if Keyword.get(opts, :put_default_views, true) do
plug :put_new_layout, {Phoenix.Controller.__layout__(__MODULE__, opts), :app}
plug :put_new_view, Phoenix.Controller.__view__(__MODULE__)
end
end
end
@doc """
Registers the plug to call as a fallback to the controller action.
A fallback plug is useful to translate common domain data structures
into a valid `%Plug.Conn{}` response. If the controller action fails to
return a `%Plug.Conn{}`, the provided plug will be called and receive
the controller's `%Plug.Conn{}` as it was before the action was invoked
along with the value returned from the controller action.
## Examples
defmodule MyController do
use Phoenix.Controller
action_fallback MyFallbackController
def show(conn, %{"id" => id}, current_user) do
with {:ok, post} <- Blog.fetch_post(id),
:ok <- Authorizer.authorize(current_user, :view, post) do
render(conn, "show.json", post: post)
end
end
end
In the above example, `with` is used to match only a successful
post fetch, followed by valid authorization for the current user.
In the event either of those fail to match, `with` will not invoke
the render block and instead return the unmatched value. In this case,
imagine `Blog.fetch_post/2` returned `{:error, :not_found}` or
`Authorizer.authorize/3` returned `{:error, :unauthorized}`. For cases
where these data structures serve as return values across multiple
boundaries in our domain, a single fallback module can be used to
translate the value into a valid response. For example, you could
write the following fallback controller to handle the above values:
defmodule MyFallbackController do
use Phoenix.Controller
def call(conn, {:error, :not_found}) do
conn
|> put_status(:not_found)
|> put_view(MyErrorView)
|> render(:"404")
end
def call(conn, {:error, :unauthorized}) do
conn
|> put_status(403)
|> put_view(MyErrorView)
|> render(:"403")
end
end
"""
defmacro action_fallback(plug) do
Phoenix.Controller.Pipeline.__action_fallback__(plug, __CALLER__)
end
@doc """
Returns the action name as an atom, raises if unavailable.
"""
@spec action_name(Plug.Conn.t) :: atom
def action_name(conn), do: conn.private.phoenix_action
@doc """
Returns the controller module as an atom, raises if unavailable.
"""
@spec controller_module(Plug.Conn.t) :: atom
def controller_module(conn), do: conn.private.phoenix_controller
@doc """
Returns the router module as an atom, raises if unavailable.
"""
@spec router_module(Plug.Conn.t) :: atom
def router_module(conn), do: conn.private.phoenix_router
@doc """
Returns the endpoint module as an atom, raises if unavailable.
"""
@spec endpoint_module(Plug.Conn.t) :: atom
def endpoint_module(conn), do: conn.private.phoenix_endpoint
@doc """
Returns the template name rendered in the view as a string
(or nil if no template was rendered).
"""
@spec view_template(Plug.Conn.t) :: binary | nil
def view_template(conn) do
conn.private[:phoenix_template]
end
@doc """
Sends JSON response.
It uses the configured `:json_library` under the `:phoenix`
application for `:json` to pick up the encoder module.
## Examples
iex> json(conn, %{id: 123})
"""
@spec json(Plug.Conn.t, term) :: Plug.Conn.t
def json(conn, data) do
response = Phoenix.json_library().encode_to_iodata!(data)
send_resp(conn, conn.status || 200, "application/json", response)
end
@doc """
A plug that may convert a JSON response into a JSONP one.
In case a JSON response is returned, it will be converted
to a JSONP as long as the callback field is present in
the query string. The callback field itself defaults to
"callback", but may be configured with the callback option.
In case there is no callback or the response is not encoded
in JSON format, it is a no-op.
Only alphanumeric characters and underscore are allowed in the
callback name. Otherwise an exception is raised.
## Examples
# Will convert JSON to JSONP if callback=someFunction is given
plug :allow_jsonp
# Will convert JSON to JSONP if cb=someFunction is given
plug :allow_jsonp, callback: "cb"
"""
@spec allow_jsonp(Plug.Conn.t, Keyword.t) :: Plug.Conn.t
def allow_jsonp(conn, opts \\ []) do
callback = Keyword.get(opts, :callback, "callback")
case Map.fetch(conn.query_params, callback) do
:error -> conn
{:ok, ""} -> conn
{:ok, cb} ->
validate_jsonp_callback!(cb)
register_before_send(conn, fn conn ->
if json_response?(conn) do
conn
|> put_resp_header("content-type", "application/javascript")
|> resp(conn.status, jsonp_body(conn.resp_body, cb))
else
conn
end
end)
end
end
defp json_response?(conn) do
case get_resp_header(conn, "content-type") do
["application/json;" <> _] -> true
["application/json"] -> true
_ -> false
end
end
defp jsonp_body(data, callback) do
body =
data
|> IO.iodata_to_binary()
|> String.replace(<<0x2028::utf8>>, "\\u2028")
|> String.replace(<<0x2029::utf8>>, "\\u2029")
"/**/ typeof #{callback} === 'function' && #{callback}(#{body});"
end
defp validate_jsonp_callback!(<<h, t::binary>>)
when h in ?0..?9 or h in ?A..?Z or h in ?a..?z or h == ?_,
do: validate_jsonp_callback!(t)
defp validate_jsonp_callback!(<<>>), do: :ok
defp validate_jsonp_callback!(_),
do: raise(ArgumentError, "the JSONP callback name contains invalid characters")
@doc """
Sends text response.
## Examples
iex> text(conn, "hello")
iex> text(conn, :implements_to_string)
"""
@spec text(Plug.Conn.t, String.Chars.t) :: Plug.Conn.t
def text(conn, data) do
send_resp(conn, conn.status || 200, "text/plain", to_string(data))
end
@doc """
Sends html response.
## Examples
iex> html(conn, "<html><head>...")
"""
@spec html(Plug.Conn.t, iodata) :: Plug.Conn.t
def html(conn, data) do
send_resp(conn, conn.status || 200, "text/html", data)
end
@doc """
Sends redirect response to the given url.
For security, `:to` only accepts paths. Use the `:external`
option to redirect to any URL.
The response will be sent with the status code defined within
the connection, via `Plug.Conn.put_status/2`. If no status
code is set, a 302 response is sent.
## Examples
iex> redirect(conn, to: "/login")
iex> redirect(conn, external: "https://elixir-lang.org")
"""
def redirect(conn, opts) when is_list(opts) do
url = url(opts)
html = Plug.HTML.html_escape(url)
body = "<html><body>You are being <a href=\"#{html}\">redirected</a>.</body></html>"
conn
|> put_resp_header("location", url)
|> send_resp(conn.status || 302, "text/html", body)
end
defp url(opts) do
cond do
to = opts[:to] -> validate_local_url(to)
external = opts[:external] -> external
true -> raise ArgumentError, "expected :to or :external option in redirect/2"
end
end
@invalid_local_url_chars ["\\"]
defp validate_local_url("//" <> _ = to), do: raise_invalid_url(to)
defp validate_local_url("/" <> _ = to) do
if String.contains?(to, @invalid_local_url_chars) do
raise ArgumentError, "unsafe characters detected for local redirect in URL #{inspect to}"
else
to
end
end
defp validate_local_url(to), do: raise_invalid_url(to)
@spec raise_invalid_url(term()) :: no_return()
defp raise_invalid_url(url) do
raise ArgumentError, "the :to option in redirect expects a path but was #{inspect url}"
end
@doc """
Stores the view for rendering.
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_view(Plug.Conn.t, atom) :: Plug.Conn.t
def put_view(%Plug.Conn{state: state} = conn, module) when state in @unsent do
put_private(conn, :phoenix_view, module)
end
def put_view(%Plug.Conn{}, _module), do: raise AlreadySentError
@doc """
Stores the view for rendering if one was not stored yet.
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_new_view(Plug.Conn.t, atom) :: Plug.Conn.t
def put_new_view(%Plug.Conn{state: state} = conn, module)
when state in @unsent do
update_in conn.private, &Map.put_new(&1, :phoenix_view, module)
end
def put_new_view(%Plug.Conn{}, _module), do: raise AlreadySentError
@doc """
Retrieves the current view.
"""
@spec view_module(Plug.Conn.t) :: atom
def view_module(conn), do: conn.private.phoenix_view
@doc """
Stores the layout for rendering.
The layout must be a tuple, specifying the layout view and the layout
name, or false. In case a previous layout is set, `put_layout` also
accepts the layout name to be given as a string or as an atom. If a
string, it must contain the format. Passing an atom means the layout
format will be found at rendering time, similar to the template in
`render/3`. It can also be set to `false`. In this case, no layout
would be used.
## Examples
iex> layout(conn)
false
iex> conn = put_layout conn, {AppView, "application.html"}
iex> layout(conn)
{AppView, "application.html"}
iex> conn = put_layout conn, "print.html"
iex> layout(conn)
{AppView, "print.html"}
iex> conn = put_layout conn, :print
iex> layout(conn)
{AppView, :print}
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_layout(Plug.Conn.t, {atom, binary | atom} | atom | binary | false) :: Plug.Conn.t
def put_layout(%Plug.Conn{state: state} = conn, layout) do
if state in @unsent do
do_put_layout(conn, :phoenix_layout, layout)
else
raise AlreadySentError
end
end
defp do_put_layout(conn, private_key, false) do
put_private(conn, private_key, false)
end
defp do_put_layout(conn, private_key, {mod, layout}) when is_atom(mod) do
put_private(conn, private_key, {mod, layout})
end
defp do_put_layout(conn, private_key, layout) when is_binary(layout) or is_atom(layout) do
update_in conn.private, fn private ->
case Map.get(private, private_key, false) do
{mod, _} -> Map.put(private, private_key, {mod, layout})
false -> raise "cannot use put_layout/2 or put_root_layout/2 with atom/binary when layout is false, use a tuple instead"
end
end
end
@doc """
Stores the layout for rendering if one was not stored yet.
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_new_layout(Plug.Conn.t, {atom, binary | atom} | false) :: Plug.Conn.t
def put_new_layout(%Plug.Conn{state: state} = conn, layout)
when (is_tuple(layout) and tuple_size(layout) == 2) or layout == false do
if state in @unsent do
update_in conn.private, &Map.put_new(&1, :phoenix_layout, layout)
else
raise AlreadySentError
end
end
@doc """
Stores the root layout for rendering.
Like `put_layout/2`, the layout must be a tuple,
specifying the layout view and the layout name, or false.
In case a previous layout is set, `put_root_layout` also
accepts the layout name to be given as a string or as an atom. If a
string, it must contain the format. Passing an atom means the layout
format will be found at rendering time, similar to the template in
`render/3`. It can also be set to `false`. In this case, no layout
would be used.
## Examples
iex> root_layout(conn)
false
iex> conn = put_root_layout conn, {AppView, "root.html"}
iex> root_layout(conn)
{AppView, "root.html"}
iex> conn = put_root_layout conn, "bare.html"
iex> root_layout(conn)
{AppView, "bare.html"}
iex> conn = put_root_layout conn, :bare
iex> root_layout(conn)
{AppView, :bare}
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_root_layout(Plug.Conn.t, {atom, binary | atom} | atom | binary | false) :: Plug.Conn.t
def put_root_layout(%Plug.Conn{state: state} = conn, layout) do
if state in @unsent do
do_put_layout(conn, :phoenix_root_layout, layout)
else
raise AlreadySentError
end
end
@doc """
Sets which formats have a layout when rendering.
## Examples
iex> layout_formats(conn)
["html"]
iex> put_layout_formats(conn, ["html", "mobile"])
iex> layout_formats(conn)
["html", "mobile"]
Raises `Plug.Conn.AlreadySentError` if `conn` is already sent.
"""
@spec put_layout_formats(Plug.Conn.t, [String.t]) :: Plug.Conn.t
def put_layout_formats(%Plug.Conn{state: state} = conn, formats)
when state in @unsent and is_list(formats) do
put_private(conn, :phoenix_layout_formats, formats)
end
def put_layout_formats(%Plug.Conn{}, _formats), do: raise AlreadySentError
@doc """
Retrieves current layout formats.
"""
@spec layout_formats(Plug.Conn.t) :: [String.t]
def layout_formats(conn) do
Map.get(conn.private, :phoenix_layout_formats, ~w(html))
end
@doc """
Retrieves the current layout.
"""
@spec layout(Plug.Conn.t) :: {atom, String.t | atom} | false
def layout(conn), do: conn.private |> Map.get(:phoenix_layout, false)
@doc """
Retrieves the current root layout.
"""
@spec root_layout(Plug.Conn.t) :: {atom, String.t | atom} | false
def root_layout(conn), do: conn.private |> Map.get(:phoenix_root_layout, false)
@doc """
Render the given template or the default template
specified by the current action with the given assigns.
See `render/3` for more information.
"""
@spec render(Plug.Conn.t, Keyword.t | map | binary | atom) :: Plug.Conn.t
def render(conn, template_or_assigns \\ [])
def render(conn, template) when is_binary(template) or is_atom(template) do
render(conn, template, [])
end
def render(conn, assigns) do
render(conn, action_name(conn), assigns)
end
@doc """
Renders the given `template` and `assigns` based on the `conn` information.
Once the template is rendered, the template format is set as the response
content type (for example, an HTML template will set "text/html" as response
content type) and the data is sent to the client with default status of 200.
## Arguments
* `conn` - the `Plug.Conn` struct
* `template` - which may be an atom or a string. If an atom, like `:index`,
it will render a template with the same format as the one returned by
`get_format/1`. For example, for an HTML request, it will render
the "index.html" template. If the template is a string, it must contain
the extension too, like "index.json"
* `assigns` - a dictionary with the assigns to be used in the view. Those
assigns are merged and have higher precedence than the connection assigns
(`conn.assigns`)
## Examples
defmodule MyAppWeb.UserController do
use Phoenix.Controller
def show(conn, _params) do
render(conn, "show.html", message: "Hello")
end
end
The example above renders a template "show.html" from the `MyAppWeb.UserView`
and sets the response content type to "text/html".
In many cases, you may want the template format to be set dynamically based
on the request. To do so, you can pass the template name as an atom (without
the extension):
def show(conn, _params) do
render(conn, :show, message: "Hello")
end
In order for the example above to work, we need to do content negotiation with
the accepts plug before rendering. You can do so by adding the following to your
pipeline (in the router):
plug :accepts, ["html"]
## Views
By default, Controllers render templates in a view with a similar name to the
controller. For example, `MyAppWeb.UserController` will render templates inside
the `MyAppWeb.UserView`. This information can be changed any time by using the
`put_view/2` function:
def show(conn, _params) do
conn
|> put_view(MyAppWeb.SpecialView)
|> render(:show, message: "Hello")
end
`put_view/2` can also be used as a plug:
defmodule MyAppWeb.UserController do
use Phoenix.Controller
plug :put_view, MyAppWeb.SpecialView
def show(conn, _params) do
render(conn, :show, message: "Hello")
end
end
## Layouts
Templates are often rendered inside layouts. By default, Phoenix
will render layouts for html requests. For example:
defmodule MyAppWeb.UserController do
use Phoenix.Controller
def show(conn, _params) do
render(conn, "show.html", message: "Hello")
end
end
will render the "show.html" template inside an "app.html"
template specified in `MyAppWeb.LayoutView`. `put_layout/2` can be used
to change the layout, similar to how `put_view/2` can be used to change
the view.
`layout_formats/1` and `put_layout_formats/2` can be used to configure
which formats support/require layout rendering (defaults to "html" only).
"""
@spec render(Plug.Conn.t, binary | atom, Keyword.t | map | binary | atom) :: Plug.Conn.t
def render(conn, template, assigns)
when is_atom(template) and (is_map(assigns) or is_list(assigns)) do
format =
get_format(conn) ||
raise "cannot render template #{inspect template} because conn.params[\"_format\"] is not set. " <>
"Please set `plug :accepts, ~w(html json ...)` in your pipeline."
render_and_send(conn, format, template, assigns)
end
def render(conn, template, assigns)
when is_binary(template) and (is_map(assigns) or is_list(assigns)) do
case Path.extname(template) do
"." <> format ->
render_and_send(conn, format, template, assigns)
"" ->
raise "cannot render template #{inspect template} without format. Use an atom if the " <>
"template format is meant to be set dynamically based on the request format"
end
end
def render(conn, view, template)
when is_atom(view) and (is_binary(template) or is_atom(template)) do
IO.warn "#{__MODULE__}.render/3 with a view is deprecated, see the documentation for render/3 for an alternative"
render(conn, view, template, [])
end
@doc false
def render(conn, view, template, assigns)
when is_atom(view) and (is_binary(template) or is_atom(template)) do
IO.warn "#{__MODULE__}.render/4 with a view is deprecated, see the documentation for render/3 for an alternative"
conn
|> put_view(view)
|> render(template, assigns)
end
defp render_and_send(conn, format, template, assigns) do
template = template_name(template, format)
view =
Map.get(conn.private, :phoenix_view) ||
raise "a view module was not specified, set one with put_view/2"
layout_format? = format in layout_formats(conn)
conn = prepare_assigns(conn, assigns, template, format, layout_format?)
data = render_with_layouts(conn, view, template, format, layout_format?)
conn
|> ensure_resp_content_type(MIME.type(format))
|> send_resp(conn.status || 200, data)
end
defp render_with_layouts(conn, view, template, format, layout_format?) do
render_assigns = Map.put(conn.assigns, :conn, conn)
case layout_format? and root_layout(conn) do
{layout_mod, layout_tpl} ->
inner = Phoenix.View.render(view, template, render_assigns)
root_assigns = render_assigns |> Map.put(:inner_content, inner) |> Map.delete(:layout)
Phoenix.View.render_to_iodata(layout_mod, template_name(layout_tpl, format), root_assigns)
false ->
Phoenix.View.render_to_iodata(view, template, render_assigns)
end
end
defp prepare_assigns(conn, assigns, template, format, layout_format?) do
assigns = to_map(assigns)
layout =
case layout_format? and assigns_layout(conn, assigns) do
{mod, layout} -> {mod, template_name(layout, format)}
false -> false
end
conn
|> put_private(:phoenix_template, template)
|> Map.update!(:assigns, fn prev ->
prev
|> Map.merge(assigns)
|> Map.put(:layout, layout)
end)
end
defp assigns_layout(conn, assigns) do
case Map.fetch(assigns, :layout) do
{:ok, layout} -> layout
:error -> layout(conn)
end
end
defp to_map(assigns) when is_map(assigns), do: assigns
defp to_map(assigns) when is_list(assigns), do: :maps.from_list(assigns)
defp template_name(name, format) when is_atom(name), do:
Atom.to_string(name) <> "." <> format
defp template_name(name, _format) when is_binary(name), do:
name
defp send_resp(conn, default_status, default_content_type, body) do
conn
|> ensure_resp_content_type(default_content_type)
|> send_resp(conn.status || default_status, body)
end
defp ensure_resp_content_type(%Plug.Conn{resp_headers: resp_headers} = conn, content_type) do
if List.keyfind(resp_headers, "content-type", 0) do
conn
else
content_type = content_type <> "; charset=utf-8"
%Plug.Conn{conn | resp_headers: [{"content-type", content_type}|resp_headers]}
end
end
@doc """
Puts the url string or `%URI{}` to be used for route generation.
This function overrides the default URL generation pulled
from the `%Plug.Conn{}`'s endpoint configuration.
## Examples
Imagine your application is configured to run on "example.com"
but after the user signs in, you want all links to use
"some_user.example.com". You can do so by setting the proper
router url configuration:
def put_router_url_by_user(conn) do
put_router_url(conn, get_user_from_conn(conn).account_name <> ".example.com")
end
Now when you call `Routes.some_route_url(conn, ...)`, it will use
the router url set above. Keep in mind that, if you want to generate
routes to the *current* domain, it is preferred to use
`Routes.some_route_path` helpers, as those are always relative.
"""
def put_router_url(conn, %URI{} = uri) do
put_private(conn, :phoenix_router_url, URI.to_string(uri))
end
def put_router_url(conn, url) when is_binary(url) do
put_private(conn, :phoenix_router_url, url)
end
@doc """
Puts the URL or `%URI{}` to be used for the static url generation.
Using this function on a `%Plug.Conn{}` struct tells `static_url/2` to use
the given information for URL generation instead of the the `%Plug.Conn{}`'s
endpoint configuration (much like `put_router_url/2` but for static URLs).
"""
def put_static_url(conn, %URI{} = uri) do
put_private(conn, :phoenix_static_url, URI.to_string(uri))
end
def put_static_url(conn, url) when is_binary(url) do
put_private(conn, :phoenix_static_url, url)
end
@doc """
Puts the format in the connection.
This format is used when rendering a template as an atom.
For example, `render(conn, :foo)` will render `"foo.FORMAT"`
where the format is the one set here. The default format
is typically set from the negotiation done in `accepts/2`.
See `get_format/1` for retrieval.
"""
def put_format(conn, format), do: put_private(conn, :phoenix_format, format)
@doc """
Returns the request format, such as "json", "html".
This format is used when rendering a template as an atom.
For example, `render(conn, :foo)` will render `"foo.FORMAT"`
where the format is the one set here. The default format
is typically set from the negotiation done in `accepts/2`.
"""
def get_format(conn) do
conn.private[:phoenix_format] || conn.params["_format"]
end
@doc """
Sends the given file or binary as a download.
The second argument must be `{:binary, contents}`, where
`contents` will be sent as download, or`{:file, path}`,
where `path` is the filesystem location of the file to
be sent. Be careful to not interpolate the path from
external parameters, as it could allow traversal of the
filesystem.
The download is achieved by setting "content-disposition"
to attachment. The "content-type" will also be set based
on the extension of the given filename but can be customized
via the `:content_type` and `:charset` options.
## Options
* `:filename` - the filename to be presented to the user
as download
* `:content_type` - the content type of the file or binary
sent as download. It is automatically inferred from the
filename extension
* `:disposition` - specifies disposition type
(`:attachment` or `:inline`). If `:attachment` was used,
user will be prompted to save the file. If `:inline` was used,
the browser will attempt to open the file.
Defaults to `:attachment`.
* `:charset` - the charset of the file, such as "utf-8".
Defaults to none
* `:offset` - the bytes to offset when reading. Defaults to `0`
* `:length` - the total bytes to read. Defaults to `:all`
* `:encode` - encodes the filename using `URI.encode_www_form/1`.
Defaults to `true`. When `false`, disables encoding. If you
disable encoding, you need to guarantee there are no special
characters in the filename, such as quotes, newlines, etc.
Otherwise you can expose your application to security attacks
## Examples
To send a file that is stored inside your application priv
directory:
path = Application.app_dir(:my_app, "priv/prospectus.pdf")
send_download(conn, {:file, path})
When using `{:file, path}`, the filename is inferred from the
given path but may also be set explicitly.
To allow the user to download contents that are in memory as
a binary or string:
send_download(conn, {:binary, "world"}, filename: "hello.txt")
See `Plug.Conn.send_file/3` and `Plug.Conn.send_resp/3` if you
would like to access the low-level functions used to send files
and responses via Plug.
"""
def send_download(conn, kind, opts \\ [])
def send_download(conn, {:file, path}, opts) do
filename = opts[:filename] || Path.basename(path)
offset = opts[:offset] || 0
length = opts[:length] || :all
conn
|> prepare_send_download(filename, opts)
|> send_file(conn.status || 200, path, offset, length)
end
def send_download(conn, {:binary, contents}, opts) do
filename = opts[:filename] || raise ":filename option is required when sending binary download"
conn
|> prepare_send_download(filename, opts)
|> send_resp(conn.status || 200, contents)
end
defp prepare_send_download(conn, filename, opts) do
content_type = opts[:content_type] || MIME.from_path(filename)
encoded_filename = encode_filename(filename, Keyword.get(opts, :encode, true))
disposition_type = get_disposition_type(Keyword.get(opts, :disposition, :attachment))
warn_if_ajax(conn)
conn
|> put_resp_content_type(content_type, opts[:charset])
|> put_resp_header("content-disposition", ~s[#{disposition_type}; filename="#{encoded_filename}"])
end
defp encode_filename(filename, false), do: filename
defp encode_filename(filename, true), do: URI.encode_www_form(filename)
defp get_disposition_type(:attachment), do: "attachment"
defp get_disposition_type(:inline), do: "inline"
defp get_disposition_type(other), do: raise ArgumentError, "expected :disposition to be :attachment or :inline, got: #{inspect(other)}"
defp ajax?(conn) do
case get_req_header(conn, "x-requested-with") do
[value] -> value in ["XMLHttpRequest", "xmlhttprequest"]
[] -> false
end
end
defp warn_if_ajax(conn) do
if ajax?(conn) do
Logger.warn "send_download/3 has been invoked during an AJAX request. " <>
"The download may not work as expected under XMLHttpRequest"
end
end
@doc """
Scrubs the parameters from the request.
This process is two-fold:
* Checks to see if the `required_key` is present
* Changes empty parameters of `required_key` (recursively) to nils
This function is useful for removing empty strings sent
via HTML forms. If you are providing an API, there
is likely no need to invoke `scrub_params/2`.
If the `required_key` is not present, it will
raise `Phoenix.MissingParamError`.
## Examples
iex> scrub_params(conn, "user")
"""
@spec scrub_params(Plug.Conn.t, String.t) :: Plug.Conn.t
def scrub_params(conn, required_key) when is_binary(required_key) do
param = Map.get(conn.params, required_key) |> scrub_param()
unless param do
raise Phoenix.MissingParamError, key: required_key
end
params = Map.put(conn.params, required_key, param)
%Plug.Conn{conn | params: params}
end
defp scrub_param(%{__struct__: mod} = struct) when is_atom(mod) do
struct
end
defp scrub_param(%{} = param) do
Enum.reduce(param, %{}, fn({k, v}, acc) ->
Map.put(acc, k, scrub_param(v))
end)
end
defp scrub_param(param) when is_list(param) do
Enum.map(param, &scrub_param/1)
end
defp scrub_param(param) do
if scrub?(param), do: nil, else: param
end
defp scrub?(" " <> rest), do: scrub?(rest)
defp scrub?(""), do: true
defp scrub?(_), do: false
@doc """
Enables CSRF protection.
Currently used as a wrapper function for `Plug.CSRFProtection`
and mainly serves as a function plug in `YourApp.Router`.
Check `get_csrf_token/0` and `delete_csrf_token/0` for
retrieving and deleting CSRF tokens.
"""
def protect_from_forgery(conn, opts \\ []) do
Plug.CSRFProtection.call(conn, Plug.CSRFProtection.init(opts))
end
@doc """
Put headers that improve browser security.
It sets the following headers:
* `x-frame-options` - set to SAMEORIGIN to avoid clickjacking
through iframes unless in the same origin
* `x-content-type-options` - set to nosniff. This requires
script and style tags to be sent with proper content type
* `x-xss-protection` - set to "1; mode=block" to improve XSS
protection on both Chrome and IE
* `x-download-options` - set to noopen to instruct the browser
not to open a download directly in the browser, to avoid
HTML files rendering inline and accessing the security
context of the application (like critical domain cookies)
* `x-permitted-cross-domain-policies` - set to none to restrict
Adobe Flash Player’s access to data
* `cross-origin-window-policy` - set to deny to avoid window
control attacks
A custom headers map may also be given to be merged with defaults.
It is recommended for custom header keys to be in lowercase, to avoid sending
duplicate keys in a request.
Additionally, responses with mixed-case headers served over HTTP/2 are not
considered valid by common clients, resulting in dropped responses.
"""
def put_secure_browser_headers(conn, headers \\ %{})
def put_secure_browser_headers(conn, []) do
put_secure_defaults(conn)
end
def put_secure_browser_headers(conn, headers) when is_map(headers) do
conn
|> put_secure_defaults()
|> merge_resp_headers(headers)
end
defp put_secure_defaults(conn) do
merge_resp_headers(conn, [
{"x-frame-options", "SAMEORIGIN"},
{"x-xss-protection", "1; mode=block"},
{"x-content-type-options", "nosniff"},
{"x-download-options", "noopen"},
{"x-permitted-cross-domain-policies", "none"},
{"cross-origin-window-policy", "deny"}
])
end
@doc """
Gets or generates a CSRF token.
If a token exists, it is returned, otherwise it is generated and stored
in the process dictionary.
"""
defdelegate get_csrf_token(), to: Plug.CSRFProtection
@doc """
Deletes the CSRF token from the process dictionary.
*Note*: The token is deleted only after a response has been sent.
"""
defdelegate delete_csrf_token(), to: Plug.CSRFProtection
@doc """
Performs content negotiation based on the available formats.
It receives a connection, a list of formats that the server
is capable of rendering and then proceeds to perform content
negotiation based on the request information. If the client
accepts any of the given formats, the request proceeds.
If the request contains a "_format" parameter, it is
considered to be the format desired by the client. If no
"_format" parameter is available, this function will parse
the "accept" header and find a matching format accordingly.
This function is useful when you may want to serve different
content-types (such as JSON and HTML) from the same routes.
However, if you always have distinct routes, you can also
disable content negotiation and simply hardcode your format
of choice in your route pipelines:
plug :put_format, "html"
It is important to notice that browsers have historically
sent bad accept headers. For this reason, this function will
default to "html" format whenever:
* the accepted list of arguments contains the "html" format
* the accept header specified more than one media type preceded
or followed by the wildcard media type "`*/*`"
This function raises `Phoenix.NotAcceptableError`, which is rendered
with status 406, whenever the server cannot serve a response in any
of the formats expected by the client.
## Examples
`accepts/2` can be invoked as a function:
iex> accepts(conn, ["html", "json"])
or used as a plug:
plug :accepts, ["html", "json"]
plug :accepts, ~w(html json)
## Custom media types
It is possible to add custom media types to your Phoenix application.
The first step is to teach Plug about those new media types in
your `config/config.exs` file:
config :mime, :types, %{
"application/vnd.api+json" => ["json-api"]
}
The key is the media type, the value is a list of formats the
media type can be identified with. For example, by using
"json-api", you will be able to use templates with extension
"index.json-api" or to force a particular format in a given
URL by sending "?_format=json-api".
After this change, you must recompile plug:
$ mix deps.clean mime --build
$ mix deps.get
And now you can use it in accepts too:
plug :accepts, ["html", "json-api"]
"""
@spec accepts(Plug.Conn.t, [binary]) :: Plug.Conn.t | no_return()
def accepts(conn, [_|_] = accepted) do
case Map.fetch(conn.params, "_format") do
{:ok, format} ->
handle_params_accept(conn, format, accepted)
:error ->
handle_header_accept(conn, get_req_header(conn, "accept"), accepted)
end
end
defp handle_params_accept(conn, format, accepted) do
if format in accepted do
put_format(conn, format)
else
raise Phoenix.NotAcceptableError,
message: "unknown format #{inspect format}, expected one of #{inspect accepted}",
accepts: accepted
end
end
# In case there is no accept header or the header is */*
# we use the first format specified in the accepts list.
defp handle_header_accept(conn, header, [first|_]) when header == [] or header == ["*/*"] do
put_format(conn, first)
end
# In case there is a header, we need to parse it.
# But before we check for */* because if one exists and we serve html,
# we unfortunately need to assume it is a browser sending us a request.
defp handle_header_accept(conn, [header|_], accepted) do
if header =~ "*/*" and "html" in accepted do
put_format(conn, "html")
else
parse_header_accept(conn, String.split(header, ","), [], accepted)
end
end
defp parse_header_accept(conn, [h|t], acc, accepted) do
case Plug.Conn.Utils.media_type(h) do
{:ok, type, subtype, args} ->
exts = parse_exts(type, subtype)
q = parse_q(args)
if format = (q === 1.0 && find_format(exts, accepted)) do
put_format(conn, format)
else
parse_header_accept(conn, t, [{-q, h, exts}|acc], accepted)
end
:error ->
parse_header_accept(conn, t, acc, accepted)
end
end
defp parse_header_accept(conn, [], acc, accepted) do
acc
|> Enum.sort()
|> Enum.find_value(&parse_header_accept(conn, &1, accepted))
|> Kernel.||(refuse(conn, acc, accepted))
end
defp parse_header_accept(conn, {_, _, exts}, accepted) do
if format = find_format(exts, accepted) do
put_format(conn, format)
end
end
defp parse_q(args) do
case Map.fetch(args, "q") do
{:ok, float} ->
case Float.parse(float) do
{float, _} -> float
:error -> 1.0
end
:error ->
1.0
end
end
defp parse_exts("*", "*"), do: "*/*"
defp parse_exts(type, "*"), do: type
defp parse_exts(type, subtype), do: MIME.extensions(type <> "/" <> subtype)
defp find_format("*/*", accepted), do: Enum.fetch!(accepted, 0)
defp find_format(exts, accepted) when is_list(exts), do: Enum.find(exts, &(&1 in accepted))
defp find_format(_type_range, []), do: nil
defp find_format(type_range, [h|t]) do
mime_type = MIME.type(h)
case Plug.Conn.Utils.media_type(mime_type) do
{:ok, accepted_type, _subtype, _args} when type_range === accepted_type -> h
_ -> find_format(type_range, t)
end
end
@spec refuse(term(), [tuple], [binary]) :: no_return()
defp refuse(_conn, given, accepted) do
raise Phoenix.NotAcceptableError,
accepts: accepted,
message: """
no supported media type in accept header.
Expected one of #{inspect accepted} but got the following formats:
* #{Enum.map_join(given, "\n ", fn {_, header, exts} ->
inspect(header) <> " with extensions: " <> inspect(exts)
end)}
To accept custom formats, register them under the :mime library
in your config/config.exs file:
config :mime, :types, %{
"application/xml" => ["xml"]
}
And then run `mix deps.clean --build mime` to force it to be recompiled.
"""
end
@doc """
Fetches the flash storage.
"""
def fetch_flash(conn, _opts \\ []) do
if Map.get(conn.private, :phoenix_flash) do
conn
else
session_flash = get_session(conn, "phoenix_flash")
conn = persist_flash(conn, session_flash || %{})
register_before_send conn, fn conn ->
flash = conn.private.phoenix_flash
flash_size = map_size(flash)
cond do
is_nil(session_flash) and flash_size == 0 ->
conn
flash_size > 0 and conn.status in 300..308 ->
put_session(conn, "phoenix_flash", flash)
true ->
delete_session(conn, "phoenix_flash")
end
end
end
end
@doc """
Merges a map into the flash.
Returns the updated connection.
## Examples
iex> conn = merge_flash(conn, info: "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
"""
def merge_flash(conn, enumerable) do
map = for {k, v} <- enumerable, into: %{}, do: {flash_key(k), v}
persist_flash(conn, Map.merge(get_flash(conn), map))
end
@doc """
Persists a value in flash.
Returns the updated connection.
## Examples
iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
"""
def put_flash(conn, key, message) do
persist_flash(conn, Map.put(get_flash(conn), flash_key(key), message))
end
@doc """
Returns a map of previously set flash messages or an empty map.
## Examples
iex> get_flash(conn)
%{}
iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn)
%{"info" => "Welcome Back!"}
"""
def get_flash(conn) do
Map.get(conn.private, :phoenix_flash) ||
raise ArgumentError, message: "flash not fetched, call fetch_flash/2"
end
@doc """
Returns a message from flash by `key` (or `nil` if no message is available for `key`).
## Examples
iex> conn = put_flash(conn, :info, "Welcome Back!")
iex> get_flash(conn, :info)
"Welcome Back!"
"""
def get_flash(conn, key) do
get_flash(conn)[flash_key(key)]
end
@doc """
Generates a status message from the template name.
## Examples
iex> status_message_from_template("404.html")
"Not Found"
iex> status_message_from_template("whatever.html")
"Internal Server Error"
"""
def status_message_from_template(template) do
template
|> String.split(".")
|> hd()
|> String.to_integer()
|> Plug.Conn.Status.reason_phrase()
rescue
_ -> "Internal Server Error"
end
@doc """
Clears all flash messages.
"""
def clear_flash(conn) do
persist_flash(conn, %{})
end
defp flash_key(binary) when is_binary(binary), do: binary
defp flash_key(atom) when is_atom(atom), do: Atom.to_string(atom)
defp persist_flash(conn, value) do
put_private(conn, :phoenix_flash, value)
end
@doc """
Returns the current request path with its default query parameters:
iex> current_path(conn)
"/users/123?existing=param"
See `current_path/2` to override the default parameters.
The path is normalized based on the `conn.script_name` and
`conn.path_info`. For example, "/foo//bar/" will become "/foo/bar".
If you want the original path, use `conn.request_path` instead.
"""
def current_path(%Plug.Conn{query_string: ""} = conn) do
normalized_request_path(conn)
end
def current_path(%Plug.Conn{query_string: query_string} = conn) do
normalized_request_path(conn) <> "?" <> query_string
end
@doc """
Returns the current path with the given query parameters.
You may also retrieve only the request path by passing an
empty map of params.
## Examples
iex> current_path(conn)
"/users/123?existing=param"
iex> current_path(conn, %{new: "param"})
"/users/123?new=param"
iex> current_path(conn, %{filter: %{status: ["draft", "published"]}})
"/users/123?filter[status][]=draft&filter[status][]=published"
iex> current_path(conn, %{})
"/users/123"
The path is normalized based on the `conn.script_name` and
`conn.path_info`. For example, "/foo//bar/" will become "/foo/bar".
If you want the original path, use `conn.request_path` instead.
"""
def current_path(%Plug.Conn{} = conn, params) when params == %{} do
normalized_request_path(conn)
end
def current_path(%Plug.Conn{} = conn, params) do
normalized_request_path(conn) <> "?" <> Plug.Conn.Query.encode(params)
end
defp normalized_request_path(%{path_info: info, script_name: script}) do
"/" <> Enum.join(script ++ info, "/")
end
@doc """
Returns the current request url with its default query parameters:
iex> current_url(conn)
"https://www.example.com/users/123?existing=param"
See `current_url/2` to override the default parameters.
"""
def current_url(%Plug.Conn{} = conn) do
Phoenix.Router.Helpers.url(router_module(conn), conn) <> current_path(conn)
end
@doc ~S"""
Returns the current request URL with query params.
The path will be retrieved from the currently requested path via
`current_path/1`. The scheme, host and others will be received from
the URL configuration in your Phoenix endpoint. The reason we don't
use the host and scheme information in the request is because most
applications are behind proxies and the host and scheme may not
actually reflect the host and scheme accessed by the client. If you
want to access the url precisely as requested by the client, see
`Plug.Conn.request_url/1`.
## Examples
iex> current_url(conn)
"https://www.example.com/users/123?existing=param"
iex> current_url(conn, %{new: "param"})
"https://www.example.com/users/123?new=param"
iex> current_url(conn, %{})
"https://www.example.com/users/123"
## Custom URL Generation
In some cases, you'll need to generate a request's URL, but using a
different scheme, different host, etc. This can be accomplished in
two ways.
If you want to do so in a case-by-case basis, you can define a custom
function that gets the endpoint URI configuration and changes it accordingly.
For example, to get the current URL always in HTTPS format:
def current_secure_url(conn, params \\ %{}) do
cur_uri = MyAppWeb.Endpoint.struct_url()
cur_path = Phoenix.Controller.current_path(conn, params)
MyAppWeb.Router.Helpers.url(%URI{cur_uri | scheme: "https"}) <> cur_path
end
However, if you want all generated URLs to always have a certain schema,
host, etc, you may use `put_router_url/2`.
"""
def current_url(%Plug.Conn{} = conn, %{} = params) do
Phoenix.Router.Helpers.url(router_module(conn), conn) <> current_path(conn, params)
end
@doc false
def __view__(controller_module) do
controller_module
|> Phoenix.Naming.unsuffix("Controller")
|> Kernel.<>("View")
|> String.to_atom()
end
@doc false
def __layout__(controller_module, opts) do
namespace =
if given = Keyword.get(opts, :namespace) do
given
else
controller_module
|> Atom.to_string()
|> String.split(".")
|> Enum.drop(-1)
|> Enum.take(2)
|> Module.concat()
end
Module.concat(namespace, "LayoutView")
end
end
| 32.162688 | 137 | 0.675996 |
e815a0c679d250fbcc1a06c20d0b239e79b2c9db | 1,811 | ex | Elixir | lib/brando_admin/components/form/input/toggle.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 4 | 2020-10-30T08:40:38.000Z | 2022-01-07T22:21:37.000Z | lib/brando_admin/components/form/input/toggle.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | 1,162 | 2020-07-05T11:20:15.000Z | 2022-03-31T06:01:49.000Z | lib/brando_admin/components/form/input/toggle.ex | brandocms/brando | 4198e0c0920031bd909969055064e4e2b7230d21 | [
"MIT"
] | null | null | null | defmodule BrandoAdmin.Components.Form.Input.Toggle do
use Surface.Component
use Phoenix.HTML
alias BrandoAdmin.Components.Form.FieldBase
alias BrandoAdmin.Components.Form.Label
prop form, :form
prop field, :any
prop blueprint, :any
prop input, :any
prop name, :any
prop label, :string
prop placeholder, :string
prop instructions, :string
prop class, :any
prop small, :boolean
data field_name, :any
data classes, :string
data text, :string
data small?, :boolean
slot default
def update(%{input: %{name: name, opts: opts}} = assigns, socket) do
{:ok,
socket
|> assign(:classes, opts[:class])
|> assign(:small?, Keyword.get(opts, :small, false))
|> assign(:field_name, name)
|> assign(assigns)}
end
def update(assigns, socket) do
{:ok,
socket
|> assign(assigns)}
end
def render(%{blueprint: nil} = assigns) do
~F"""
<FieldBase
label={@label}
placeholder={@placeholder}
instructions={@instructions}
field={@field}
form={@form}>
<Label form={@form} field={@field} class={"switch", small: @small}>
{#if slot_assigned?(:default)}
<#slot />
{#else}
{checkbox @form, @field}
{/if}
<div class="slider round"></div>
</Label>
</FieldBase>
"""
end
def render(%{blueprint: _} = assigns) do
~F"""
<FieldBase
blueprint={@blueprint}
field={@field_name}
class={@classes}
form={@form}>
<Label form={@form} field={@field_name} class={"switch", small: @small?}>
{#if slot_assigned?(:default)}
<#slot />
{#else}
{checkbox @form, @field_name}
{/if}
<div class="slider round"></div>
</Label>
</FieldBase>
"""
end
end
| 22.924051 | 79 | 0.581999 |
e815b679209131b03ceb605049017aff3215d695 | 450 | ex | Elixir | lib/elixero/core_api/currencies.ex | philals/elixero | fd75fe4a6f0a93b1d2ff94adbb307d20f014d458 | [
"MIT"
] | 84 | 2016-11-09T01:15:17.000Z | 2022-01-06T02:55:35.000Z | lib/elixero/core_api/currencies.ex | philals/elixero | fd75fe4a6f0a93b1d2ff94adbb307d20f014d458 | [
"MIT"
] | 14 | 2017-03-10T04:16:07.000Z | 2021-11-10T16:39:19.000Z | lib/elixero/core_api/currencies.ex | philals/elixero | fd75fe4a6f0a93b1d2ff94adbb307d20f014d458 | [
"MIT"
] | 18 | 2017-03-11T21:12:15.000Z | 2022-02-22T20:07:10.000Z | defmodule EliXero.CoreApi.Currencies do
@resource "currencies"
@model_module EliXero.CoreApi.Models.Currencies
def find(client) do
EliXero.CoreApi.Common.find(client, @resource)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
def filter(client, filter) do
EliXero.CoreApi.Common.filter(client, @resource, filter)
|> EliXero.CoreApi.Utils.ResponseHandler.handle_response(@model_module)
end
end | 32.142857 | 75 | 0.773333 |
e815b8cad4cf2a6d0a4e2c54af33522ecbe5b348 | 565 | ex | Elixir | priv/catalogue/button/example02.ex | devilcoders/facade | 6aca8aaaf643b83ec275344436049c162d3a3b9a | [
"MIT"
] | null | null | null | priv/catalogue/button/example02.ex | devilcoders/facade | 6aca8aaaf643b83ec275344436049c162d3a3b9a | [
"MIT"
] | null | null | null | priv/catalogue/button/example02.ex | devilcoders/facade | 6aca8aaaf643b83ec275344436049c162d3a3b9a | [
"MIT"
] | null | null | null | defmodule Facade.Catalogue.Button.Example02 do
use Surface.Catalogue.Example,
subject: Facade.Button,
catalogue: Facade.Catalogue,
title: "Colors & Sizes",
direction: "vertical",
height: "110px",
container: {:div, class: "buttons"}
def render(assigns) do
~F"""
<Button>Default</Button>
<Button size="small" color="info">Small</Button>
<Button size="normal" color="primary">Normal</Button>
<Button size="medium" color="warning">Medium</Button>
<Button size="large" color="danger">Large</Button>
"""
end
end
| 28.25 | 57 | 0.661947 |
e8160397527a63559d331c047fdd1e20eb2a512b | 474 | ex | Elixir | test/support/test_setup/country.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 356 | 2016-03-16T12:37:28.000Z | 2021-12-18T03:22:39.000Z | test/support/test_setup/country.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 30 | 2016-03-16T09:19:10.000Z | 2021-01-12T08:10:52.000Z | test/support/test_setup/country.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 72 | 2016-03-16T13:32:14.000Z | 2021-03-23T11:27:43.000Z | defmodule Nectar.TestSetup.Country do
alias Nectar.Repo
def valid_attrs, do: %{"name" => "Country", "iso" => "Co", "iso3" => "Con", "numcode" => "123"}
def invalid_attrs, do: %{}
def create_country!(country_attrs \\ nil) do
attrs = country_attrs || valid_attrs
Nectar.Command.Country.insert!(Repo, attrs)
end
def create_country(country_attrs \\ nil) do
attrs = country_attrs || valid_attrs
Nectar.Command.Country.insert(Repo, attrs)
end
end
| 27.882353 | 97 | 0.679325 |
e81658029fac7c39130a2e425276decacef06b14 | 2,660 | exs | Elixir | mix.exs | kf8a/custom_rpi3a | b859a809b0a6e71fc81c2498cc66ca6cca978835 | [
"Apache-2.0"
] | null | null | null | mix.exs | kf8a/custom_rpi3a | b859a809b0a6e71fc81c2498cc66ca6cca978835 | [
"Apache-2.0"
] | null | null | null | mix.exs | kf8a/custom_rpi3a | b859a809b0a6e71fc81c2498cc66ca6cca978835 | [
"Apache-2.0"
] | null | null | null | defmodule NervesSystemRpi3a.MixProject do
use Mix.Project
@github_organization "nerves-project"
@app :nerves_system_rpi3a
@version Path.join(__DIR__, "VERSION")
|> File.read!()
|> String.trim()
def project do
[
app: @app,
version: @version,
elixir: "~> 1.6",
compilers: Mix.compilers() ++ [:nerves_package],
nerves_package: nerves_package(),
description: description(),
package: package(),
deps: deps(),
aliases: [loadconfig: [&bootstrap/1], docs: ["docs", ©_images/1]],
docs: [extras: ["README.md"], main: "readme"]
]
end
def application do
[]
end
defp bootstrap(args) do
set_target()
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
defp nerves_package do
[
type: :system,
artifact_sites: [
{:github_releases, "#{@github_organization}/#{@app}"}
],
build_runner_opts: build_runner_opts(),
platform: Nerves.System.BR,
platform_config: [
defconfig: "nerves_defconfig"
],
checksum: package_files()
]
end
defp deps do
[
{:nerves, "~> 1.5.4 or ~> 1.6.0", runtime: false},
{:nerves_system_br, "1.12.0", runtime: false},
{:nerves_toolchain_arm_unknown_linux_gnueabihf, "~> 1.3.0", runtime: false},
{:nerves_system_linter, "~> 0.4", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.18", only: [:dev, :test], runtime: false}
]
end
defp description do
"""
Nerves System - Raspberry Pi 3 A+
"""
end
defp package do
[
files: package_files(),
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/#{@github_organization}/#{@app}"}
]
end
defp package_files do
[
"fwup_include",
"rootfs_overlay",
"CHANGELOG.md",
"cmdline.txt",
"config.txt",
"fwup-revert.conf",
"fwup.conf",
"LICENSE",
"linux-4.19.defconfig",
"mix.exs",
"nerves_defconfig",
"post-build.sh",
"post-createfs.sh",
"ramoops.dts",
"README.md",
"VERSION"
]
end
# Copy the images referenced by docs, since ex_doc doesn't do this.
defp copy_images(_) do
File.cp_r("assets", "doc/assets")
end
defp build_runner_opts() do
if primary_site = System.get_env("BR2_PRIMARY_SITE") do
[make_args: ["BR2_PRIMARY_SITE=#{primary_site}"]]
else
[]
end
end
defp set_target() do
if function_exported?(Mix, :target, 1) do
apply(Mix, :target, [:target])
else
System.put_env("MIX_TARGET", "target")
end
end
end
| 22.931034 | 82 | 0.582707 |
e816979c628e2bb400ec003dfda0258b2808462d | 2,533 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/bqml_iteration_result.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/bqml_iteration_result.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/bqml_iteration_result.ex | linjunpop/elixir-google-api | 444cb2b2fb02726894535461a474beddd8b86db4 | [
"Apache-2.0"
] | null | null | null | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "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.BigQuery.V2.Model.BqmlIterationResult do
@moduledoc """
## Attributes
- durationMs (String.t): [Output-only, Beta] Time taken to run the training iteration in milliseconds. Defaults to: `null`.
- evalLoss (float()): [Output-only, Beta] Eval loss computed on the eval data at the end of the iteration. The eval loss is used for early stopping to avoid overfitting. No eval loss if eval_split_method option is specified as no_split or auto_split with input data size less than 500 rows. Defaults to: `null`.
- index (integer()): [Output-only, Beta] Index of the ML training iteration, starting from zero for each training run. Defaults to: `null`.
- learnRate (float()): [Output-only, Beta] Learning rate used for this iteration, it varies for different training iterations if learn_rate_strategy option is not constant. Defaults to: `null`.
- trainingLoss (float()): [Output-only, Beta] Training loss computed on the training data at the end of the iteration. The training loss function is defined by model type. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:durationMs => any(),
:evalLoss => any(),
:index => any(),
:learnRate => any(),
:trainingLoss => any()
}
field(:durationMs)
field(:evalLoss)
field(:index)
field(:learnRate)
field(:trainingLoss)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.BqmlIterationResult do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.BqmlIterationResult.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.BqmlIterationResult do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 42.216667 | 313 | 0.732333 |
e816b0982f050fe73af9aee06d5384d2e453b176 | 2,720 | exs | Elixir | phoenix158/my-phoenix-json-api/test/my_app_web/controllers/employee_controller_test.exs | salbador/oldphp7_vs_laravel7_vs_phoenix1.5.8_vs_phalcon4 | 294b8668dc4940c07d6dde198f02b38100a1dc00 | [
"MIT"
] | null | null | null | phoenix158/my-phoenix-json-api/test/my_app_web/controllers/employee_controller_test.exs | salbador/oldphp7_vs_laravel7_vs_phoenix1.5.8_vs_phalcon4 | 294b8668dc4940c07d6dde198f02b38100a1dc00 | [
"MIT"
] | null | null | null | phoenix158/my-phoenix-json-api/test/my_app_web/controllers/employee_controller_test.exs | salbador/oldphp7_vs_laravel7_vs_phoenix1.5.8_vs_phalcon4 | 294b8668dc4940c07d6dde198f02b38100a1dc00 | [
"MIT"
] | null | null | null | defmodule MyAppWeb.EmployeeControllerTest do
use MyAppWeb.ConnCase
alias MyApp.Account
alias MyApp.Account.Employee
@create_attrs %{
interests: [],
name: "some name"
}
@update_attrs %{
interests: [],
name: "some updated name"
}
@invalid_attrs %{interests: nil, name: nil}
def fixture(:employee) do
{:ok, employee} = Account.create_employee(@create_attrs)
employee
end
setup %{conn: conn} do
{:ok, conn: put_req_header(conn, "accept", "application/json")}
end
describe "index" do
test "lists all employees", %{conn: conn} do
conn = get(conn, Routes.employee_path(conn, :index))
assert json_response(conn, 200)["data"] == []
end
end
describe "create employee" do
test "renders employee when data is valid", %{conn: conn} do
conn = post(conn, Routes.employee_path(conn, :create), employee: @create_attrs)
assert %{"id" => id} = json_response(conn, 201)["data"]
conn = get(conn, Routes.employee_path(conn, :show, id))
assert %{
"id" => id,
"interests" => [],
"name" => "some name"
} = json_response(conn, 200)["data"]
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.employee_path(conn, :create), employee: @invalid_attrs)
assert json_response(conn, 422)["errors"] != %{}
end
end
describe "update employee" do
setup [:create_employee]
test "renders employee when data is valid", %{
conn: conn,
employee: %Employee{id: id} = employee
} do
conn = put(conn, Routes.employee_path(conn, :update, employee), employee: @update_attrs)
assert %{"id" => ^id} = json_response(conn, 200)["data"]
conn = get(conn, Routes.employee_path(conn, :show, id))
assert %{
"id" => id,
"interests" => [],
"name" => "some updated name"
} = json_response(conn, 200)["data"]
end
test "renders errors when data is invalid", %{conn: conn, employee: employee} do
conn = put(conn, Routes.employee_path(conn, :update, employee), employee: @invalid_attrs)
assert json_response(conn, 422)["errors"] != %{}
end
end
describe "delete employee" do
setup [:create_employee]
test "deletes chosen employee", %{conn: conn, employee: employee} do
conn = delete(conn, Routes.employee_path(conn, :delete, employee))
assert response(conn, 204)
assert_error_sent 404, fn ->
get(conn, Routes.employee_path(conn, :show, employee))
end
end
end
defp create_employee(_) do
employee = fixture(:employee)
%{employee: employee}
end
end
| 28.333333 | 95 | 0.613235 |
e816d85466eef6fdce824a29f8b83c65154bfa19 | 1,391 | ex | Elixir | apps/ewallet/lib/ewallet/policies/transaction_policy.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 322 | 2018-02-28T07:38:44.000Z | 2020-05-27T23:09:55.000Z | apps/ewallet/lib/ewallet/policies/transaction_policy.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 643 | 2018-02-28T12:05:20.000Z | 2020-05-22T08:34:38.000Z | apps/ewallet/lib/ewallet/policies/transaction_policy.ex | AndonMitev/EWallet | 898cde38933d6f134734528b3e594eedf5fa50f3 | [
"Apache-2.0"
] | 63 | 2018-02-28T10:57:06.000Z | 2020-05-27T23:10:38.000Z | # Copyright 2018-2019 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 EWallet.TransactionPolicy do
@moduledoc """
The authorization policy for accounts.
"""
alias EWallet.{PolicyHelper, TransactionSourceFetcher}
alias EWallet.{Bouncer, Bouncer.Permission}
alias EWalletDB.Transaction
def authorize(:create, attrs, tx_attrs) do
with {:ok, from} <- TransactionSourceFetcher.fetch_from(tx_attrs) do
Bouncer.bounce(attrs, %Permission{
action: :create,
target: %Transaction{
from: from[:from_wallet_address],
from_account_uuid: from[:from_account_uuid],
from_user_uuid: from[:from_user_uuid]
}
})
else
_ -> {:error, :unauthorized}
end
end
def authorize(action, attrs, target) do
PolicyHelper.authorize(action, attrs, :transactions, Transaction, target)
end
end
| 33.119048 | 77 | 0.718188 |
e817047a488c4ca2d8529ad7749917bcf3119533 | 384 | ex | Elixir | lib/protox/json_enum_encoder.ex | moogle19/protox | b0efbce60efd7c38725b74575f7ff0074efd6c65 | [
"MIT"
] | 176 | 2017-02-01T13:09:25.000Z | 2022-03-18T02:36:17.000Z | lib/protox/json_enum_encoder.ex | moogle19/protox | b0efbce60efd7c38725b74575f7ff0074efd6c65 | [
"MIT"
] | 94 | 2020-07-20T05:54:51.000Z | 2022-03-09T04:13:03.000Z | lib/protox/json_enum_encoder.ex | moogle19/protox | b0efbce60efd7c38725b74575f7ff0074efd6c65 | [
"MIT"
] | 19 | 2017-02-13T09:17:14.000Z | 2022-02-22T09:29:18.000Z | defprotocol Protox.JsonEnumEncoder do
@moduledoc false
@doc since: "1.6.0"
@fallback_to_any true
@spec encode_enum(struct(), any(), (any() -> iodata())) :: iodata()
def encode_enum(enum, value, json_encode)
end
defimpl Protox.JsonEnumEncoder, for: Any do
def encode_enum(enum, value, json_encode) do
Protox.JsonEncode.encode_enum(enum, value, json_encode)
end
end
| 25.6 | 69 | 0.726563 |
e8171e1a56f0d51e951e869fa113e674d553e939 | 4,626 | exs | Elixir | backend/test/edgehog_web/schema/query/system_models_test.exs | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 14 | 2021-12-02T16:31:16.000Z | 2022-03-18T17:40:44.000Z | backend/test/edgehog_web/schema/query/system_models_test.exs | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 77 | 2021-11-03T15:14:41.000Z | 2022-03-30T14:13:32.000Z | backend/test/edgehog_web/schema/query/system_models_test.exs | szakhlypa/edgehog | b1193c26f403132dead6964c1c052e5dcae533af | [
"Apache-2.0"
] | 7 | 2021-11-03T10:58:37.000Z | 2022-02-28T14:00:03.000Z | #
# This file is part of Edgehog.
#
# Copyright 2021 SECO Mind Srl
#
# 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.
#
# SPDX-License-Identifier: Apache-2.0
#
defmodule EdgehogWeb.Schema.Query.SystemModelsTest do
use EdgehogWeb.ConnCase
import Edgehog.DevicesFixtures
alias Edgehog.Devices.{
SystemModel,
SystemModelPartNumber
}
describe "systemModels field" do
@query """
{
systemModels {
name
handle
partNumbers
hardwareType {
name
}
description {
locale
text
}
}
}
"""
test "returns empty system models", %{conn: conn, api_path: api_path} do
conn = get(conn, api_path, query: @query)
assert json_response(conn, 200) == %{
"data" => %{
"systemModels" => []
}
}
end
test "returns system models if they're present", %{conn: conn, api_path: api_path} do
hardware_type = hardware_type_fixture()
%SystemModel{
name: name,
handle: handle,
part_numbers: [%SystemModelPartNumber{part_number: part_number}]
} = system_model_fixture(hardware_type)
conn = get(conn, api_path, query: @query)
assert %{
"data" => %{
"systemModels" => [system_model]
}
} = json_response(conn, 200)
assert system_model["name"] == name
assert system_model["handle"] == handle
assert system_model["partNumbers"] == [part_number]
assert system_model["hardwareType"]["name"] == hardware_type.name
end
test "returns the default locale description", %{
conn: conn,
api_path: api_path,
tenant: tenant
} do
hardware_type = hardware_type_fixture()
default_locale = tenant.default_locale
descriptions = [
%{locale: default_locale, text: "A system model"},
%{locale: "it-IT", text: "Un modello di sistema"}
]
_system_model = system_model_fixture(hardware_type, descriptions: descriptions)
conn = get(conn, api_path, query: @query)
assert %{
"data" => %{
"systemModels" => [system_model]
}
} = json_response(conn, 200)
assert system_model["description"]["locale"] == default_locale
assert system_model["description"]["text"] == "A system model"
end
test "returns an explicit locale description", %{
conn: conn,
api_path: api_path,
tenant: tenant
} do
hardware_type = hardware_type_fixture()
default_locale = tenant.default_locale
descriptions = [
%{locale: default_locale, text: "A system model"},
%{locale: "it-IT", text: "Un modello di sistema"}
]
_system_model = system_model_fixture(hardware_type, descriptions: descriptions)
conn =
conn
|> put_req_header("accept-language", "it-IT")
|> get(api_path, query: @query)
assert %{
"data" => %{
"systemModels" => [system_model]
}
} = json_response(conn, 200)
assert system_model["description"]["locale"] == "it-IT"
assert system_model["description"]["text"] == "Un modello di sistema"
end
test "returns empty description for non existing locale", %{
conn: conn,
api_path: api_path,
tenant: tenant
} do
hardware_type = hardware_type_fixture()
default_locale = tenant.default_locale
descriptions = [
%{locale: default_locale, text: "A system model"},
%{locale: "it-IT", text: "Un modello di sistema"}
]
_system_model = system_model_fixture(hardware_type, descriptions: descriptions)
conn =
conn
|> put_req_header("accept-language", "fr-FR")
|> get(api_path, query: @query)
assert %{
"data" => %{
"systemModels" => [system_model]
}
} = json_response(conn, 200)
assert system_model["description"] == nil
end
end
end
| 27.052632 | 89 | 0.595547 |
e8176e3b407742b0a65b02913792476da6d11b3c | 706 | ex | Elixir | lib/web/services/file_service.ex | yknx4/opencov | dc961a41e29b41b0657bc2a64bb67350a65477b8 | [
"MIT"
] | 8 | 2021-08-22T10:37:57.000Z | 2022-01-10T11:27:06.000Z | lib/web/services/file_service.ex | yknx4/librecov | dc961a41e29b41b0657bc2a64bb67350a65477b8 | [
"MIT"
] | 109 | 2021-08-20T04:08:04.000Z | 2022-01-03T07:39:18.000Z | lib/web/services/file_service.ex | Librecov/librecov | dc961a41e29b41b0657bc2a64bb67350a65477b8 | [
"MIT"
] | null | null | null | defmodule Librecov.FileService do
use Librecov.Web, :service
alias Librecov.File
def files_with_filter([job | _], params), do: files_with_filter(job, params)
def files_with_filter(job, params) do
filters = Map.get(params, "filters", [])
order_field = Map.get(params, "order_field", "diff")
order_direction = Map.get(params, "order_direction", :desc)
query =
File.for_job(job)
|> File.with_filters(filters)
|> File.sort_by(order_field, order_direction)
paginator = query |> Librecov.Repo.paginate(params)
[
filters: filters,
paginator: paginator,
files: paginator.entries,
order: {order_field, order_direction}
]
end
end
| 25.214286 | 78 | 0.674221 |
e8177d9ca61498e5f5a87e1114bbe68946493df1 | 3,295 | exs | Elixir | test/nerves/utils_test.exs | TheEndIsNear/nerves | 04eebbc725d74fa291d6b4844fc98850b0486ac9 | [
"Apache-2.0"
] | null | null | null | test/nerves/utils_test.exs | TheEndIsNear/nerves | 04eebbc725d74fa291d6b4844fc98850b0486ac9 | [
"Apache-2.0"
] | null | null | null | test/nerves/utils_test.exs | TheEndIsNear/nerves | 04eebbc725d74fa291d6b4844fc98850b0486ac9 | [
"Apache-2.0"
] | null | null | null | defmodule Nerves.UtilsTest do
use NervesTest.Case, async: false
# Special thanks to Hex
alias Nerves.Utils
test "proxy_config returns no credentials when no proxy supplied" do
assert Utils.Proxy.config("http://nerves-project.org") == []
end
test "proxy_config returns http_proxy credentials when supplied" do
System.put_env("HTTP_PROXY", "http://nerves:test@example.com")
assert Utils.Proxy.config("http://nerves-project.org") == [proxy_auth: {'nerves', 'test'}]
System.delete_env("HTTP_PROXY")
end
test "proxy_config returns http_proxy credentials when only username supplied" do
System.put_env("HTTP_PROXY", "http://nopass@example.com")
assert Utils.Proxy.config("http://nerves-project.org") == [proxy_auth: {'nopass', ''}]
System.delete_env("HTTP_PROXY")
end
test "proxy_config returns credentials when the protocol is https" do
System.put_env("HTTPS_PROXY", "https://test:nerves@example.com")
assert Utils.Proxy.config("https://nerves-project.org") == [proxy_auth: {'test', 'nerves'}]
System.delete_env("HTTPS_PROXY")
end
test "proxy_config returns empty list when no credentials supplied" do
System.put_env("HTTP_PROXY", "http://example.com")
assert Utils.Proxy.config("http://nerves-project.org") == []
System.delete_env("HTTP_PROXY")
end
test "create tar archives", context do
in_tmp(context.test, fn ->
cwd = File.cwd!()
content_path = Path.join(cwd, "content")
File.mkdir(content_path)
contents = Path.join(content_path, "file")
File.touch(contents)
archive = create_archive(content_path, cwd)
assert File.exists?(archive)
end)
end
test "decompress tar archives", context do
in_tmp(context.test, fn ->
cwd = File.cwd!()
content_path = Path.join(cwd, "content")
File.mkdir(content_path)
contents = Path.join(content_path, "file")
File.touch(contents)
archive = create_archive(content_path, cwd)
assert File.exists?(archive)
File.rm_rf!(content_path)
File.mkdir(content_path)
Utils.File.untar(archive, content_path)
assert File.exists?(contents)
end)
end
test "validate tar archives", context do
in_tmp(context.test, fn ->
cwd = File.cwd!()
archive_path = Path.join(cwd, "archive.tar.gz")
:os.cmd('dd if=/dev/urandom bs=1024 count=1 of=#{archive_path}')
assert {:error, _} = Utils.File.validate(archive_path)
end)
end
test "validate extension programs" do
assert String.equivalent?("gzip", Utils.File.ext_cmd(".gz"))
assert String.equivalent?("xz", Utils.File.ext_cmd(".xz"))
assert String.equivalent?("tar", Utils.File.ext_cmd(".tar"))
end
test "parse otp compiler versions" do
assert {:ok, %Version{major: 1, minor: 2, patch: 3}} = Mix.Nerves.Utils.parse_version("1.2.3")
assert {:ok, %Version{major: 1, minor: 2, patch: 0}} = Mix.Nerves.Utils.parse_version("1.2")
assert {:ok, %Version{major: 1, minor: 2, patch: 3}} =
Mix.Nerves.Utils.parse_version("1.2.3.4")
assert {:error, _} = Mix.Nerves.Utils.parse_version("invalid")
end
defp create_archive(content_path, cwd) do
file = "archive.tar.gz"
Utils.File.tar(content_path, file)
Path.join(cwd, file)
end
end
| 34.322917 | 98 | 0.674659 |
e81780f410ccaaec73694669ec12494a28532d5d | 102 | ex | Elixir | lib/smile/repo.ex | reagan-chita/smile | c1c80679b4e14fd77f7fdc00bc7e368c514baedf | [
"MIT"
] | null | null | null | lib/smile/repo.ex | reagan-chita/smile | c1c80679b4e14fd77f7fdc00bc7e368c514baedf | [
"MIT"
] | 1 | 2021-05-11T13:24:22.000Z | 2021-05-11T13:24:22.000Z | lib/smile/repo.ex | reagan-chita/smile | c1c80679b4e14fd77f7fdc00bc7e368c514baedf | [
"MIT"
] | null | null | null | defmodule Smile.Repo do
use Ecto.Repo,
otp_app: :smile,
adapter: Ecto.Adapters.Postgres
end
| 17 | 35 | 0.715686 |
e81787c8798a57069f5c044d09265955f9d2038c | 32 | ex | Elixir | testData/org/elixir_lang/reference/module/as/suffix1.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/reference/module/as/suffix1.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/reference/module/as/suffix1.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | defmodule Prefix.Suffix1 do
end
| 10.666667 | 27 | 0.84375 |
e817bbbf0099f143fb007c2386878abe3aad4df9 | 1,520 | ex | Elixir | lib/bitcoin_simulator/simulation/tracker.ex | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | 1 | 2021-12-16T08:31:24.000Z | 2021-12-16T08:31:24.000Z | lib/bitcoin_simulator/simulation/tracker.ex | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | null | null | null | lib/bitcoin_simulator/simulation/tracker.ex | hojason117/BitcoinSimulator | f85e623eec1923a2c0d418388f440cc06b6a5283 | [
"MIT"
] | null | null | null | defmodule BitcoinSimulator.Simulation.Tracker do
use GenServer
require Logger
alias BitcoinSimulator.Const
# Client
def start_link(_) do
GenServer.start_link(__MODULE__, nil, name: BitcoinSimulator.Simulation.Tracker)
end
# Server (callbacks)
def init(_) do
state = %{
total_peers: 0,
peer_ids: MapSet.new(),
distributed_ids: MapSet.new()
}
{:ok, state}
end
def handle_call(:random_id, _from, state) do
id = get_random_id(state.distributed_ids)
{:reply, id, %{state | distributed_ids: MapSet.put(state.distributed_ids, id)}}
end
def handle_call({:peer_join, id}, _from, state) do
neighbors = Enum.take_random(MapSet.to_list(state.peer_ids), Const.decode(:neighbor_count)) |> MapSet.new()
new_state = %{state | total_peers: state.total_peers + 1, peer_ids: MapSet.put(state.peer_ids, id)}
Logger.info("Peer joined [id: #{id}]")
{:reply, neighbors, new_state}
end
def handle_call({:peer_leave, id}, _from, state) do
new_state = %{
total_peers: state.total_peers - 1,
peer_ids: MapSet.delete(state.peer_ids, id),
distributed_ids: MapSet.delete(state.distributed_ids, id)
}
Logger.info("Peer left [id: #{id}]")
{:reply, :ok, new_state}
end
def terminate(reason, _state), do: if reason != :normal, do: Logger.error(reason)
# Aux
defp get_random_id(set) do
id = :rand.uniform(Const.decode(:peer_id_range))
if MapSet.member?(set, id), do: get_random_id(set), else: id
end
end
| 26.666667 | 111 | 0.676316 |
e817d6b569cb333a93c504a0db86f8d101ff19c2 | 2,485 | ex | Elixir | apps/neoscan_web/lib/neoscan_web/views/transaction_view.ex | cc1776/neo-scan | 49fc9256f5c7ed4e0a7cd43513b27ba5d9d4f287 | [
"MIT"
] | null | null | null | apps/neoscan_web/lib/neoscan_web/views/transaction_view.ex | cc1776/neo-scan | 49fc9256f5c7ed4e0a7cd43513b27ba5d9d4f287 | [
"MIT"
] | null | null | null | apps/neoscan_web/lib/neoscan_web/views/transaction_view.ex | cc1776/neo-scan | 49fc9256f5c7ed4e0a7cd43513b27ba5d9d4f287 | [
"MIT"
] | null | null | null | defmodule NeoscanWeb.TransactionView do
use NeoscanWeb, :view
use Timex
import Number.Delimit
alias NeoscanMonitor.Api
alias Neoscan.Vm.Disassembler
alias Neoscan.Helpers
alias Neoscan.Explanations
alias NeoscanWeb.ViewHelper
alias Neoscan.ChainAssets
def get_type(type) do
cond do
type == "MinerTransaction" ->
'Miner'
type == "ContractTransaction" ->
'Contract'
type == "ClaimTransaction" ->
'GAS Claim'
type == "IssueTransaction" ->
'Asset Issue'
type == "RegisterTransaction" ->
'Asset Register'
type == "InvocationTransaction" ->
'Contract Invocation'
type == "PublishTransaction" ->
'Contract Publish'
type == "EnrollmentTransaction" ->
'Enrollment'
type == "StateTransaction" ->
'State'
end
end
def get_icon(type) do
cond do
type == "MinerTransaction" ->
'fa-user-circle-o'
type == "ContractTransaction" ->
'fa-cube'
type == "ClaimTransaction" ->
'fa-cubes'
type == "IssueTransaction" ->
'fa-handshake-o'
type == "RegisterTransaction" ->
'fa-list-alt'
type == "InvocationTransaction" ->
'fa-paper-plane'
type == "EnrollmentTransaction" ->
'fa-paper-plane'
type == "StateTransaction" ->
'fa-paper-plane'
type == "PublishTransaction" ->
'Contract Publish'
end
end
def compare_time_and_get_minutes(time) do
ViewHelper.compare_time_and_get_minutes(time)
end
def parse_invocation(nil) do
"No Invocation Script"
end
def parse_invocation(script) do
%{"invocation" => inv} = script
Disassembler.parse_script(inv)
end
def parse_verification(nil) do
"No Verification Script"
end
def parse_verification(script) do
%{"verification" => ver} = script
Disassembler.parse_script(ver)
end
def get_inv(nil) do
"No Invocation Script"
end
def get_inv(%{"invocation" => inv}) do
inv
end
def get_ver(nil) do
"No Verification Script"
end
def get_ver(%{"verification" => ver}) do
ver
end
def get_explanation(topic) do
Explanations.get(topic)
end
def get_tooltips(conn) do
ViewHelper.get_tooltips(conn)
end
def apply_precision(asset, amount) do
precision = ChainAssets.get_asset_precision_by_hash(asset)
amount
|> Helpers.apply_precision(asset, precision)
end
end
| 19.263566 | 62 | 0.628571 |
e817f2263108ea6c4a48762d0aba5a86f7bf84b1 | 4,542 | ex | Elixir | apps/gitrekt/lib/gitrekt/wire_protocol.ex | joshnuss/gitgud | ea32d9d254cfd10a09c988763e03589c401d9875 | [
"MIT"
] | null | null | null | apps/gitrekt/lib/gitrekt/wire_protocol.ex | joshnuss/gitgud | ea32d9d254cfd10a09c988763e03589c401d9875 | [
"MIT"
] | null | null | null | apps/gitrekt/lib/gitrekt/wire_protocol.ex | joshnuss/gitgud | ea32d9d254cfd10a09c988763e03589c401d9875 | [
"MIT"
] | null | null | null | defmodule GitRekt.WireProtocol do
@moduledoc """
Conveniences for Git transport protocol and server side commands.
"""
alias GitRekt.Git
alias GitRekt.Packfile
alias GitRekt.WireProtocol.{Service, ReceivePack, UploadPack}
@upload_caps ~w(multi_ack multi_ack_detailed)
@receive_caps ~w(report-status delete-refs)
@doc """
Returns a stream describing each ref and it current value.
"""
@spec reference_discovery(Git.repo, binary) :: iolist
def reference_discovery(repo, service) do
[reference_head(repo), reference_list(repo), reference_tags(repo)]
|> List.flatten()
|> Enum.map(&format_ref_line/1)
|> List.update_at(0, &(&1 <> "\0" <> server_capabilities(service)))
|> Enum.concat([:flush])
end
@doc """
Executes a *git-receive-pack* command on the given `repo`.
"""
@spec receive_pack(Git.repo, binary | :discovery, keyword) :: {ReceivePack.t, iolist}
def receive_pack(repo, data \\:discovery, opts \\ []) do
Service.run(struct(ReceivePack, repo: repo), data, opts)
end
@doc """
Executes a *git-upload-pack* command on the given `repo`.
"""
@spec upload_pack(Git.repo, binary | :discovery, keyword) :: {UploadPack.t, iolist}
def upload_pack(repo, data \\:discovery, opts \\ []) do
Service.run(struct(UploadPack, repo: repo), data, opts)
end
@doc """
Returns an *PKT-LINE* encoded representation of the given `lines`.
"""
@spec encode(Enumerable.t) :: iolist
def encode(lines) do
Enum.map(lines, &pkt_line/1)
end
@doc """
Returns a stream of decoded *PKT-LINE*s for the given `pkt`.
"""
@spec decode(binary) :: Stream.t
def decode(pkt) do
Stream.map(pkt_stream(pkt), &pkt_decode/1)
end
@doc """
Returns the given `data` formatted as *PKT-LINE*
"""
@spec pkt_line(binary|:flush) :: binary
def pkt_line(data \\ :flush)
def pkt_line(:flush), do: "0000"
def pkt_line({:ack, oid}), do: pkt_line("ACK #{Git.oid_fmt(oid)}")
def pkt_line({:ack, oid, status}), do: pkt_line("ACK #{Git.oid_fmt(oid)} #{status}")
def pkt_line(:nak), do: pkt_line("NAK")
def pkt_line(<<"PACK", _rest::binary>> = pack), do: pack
def pkt_line(data) when is_binary(data) do
data
|> byte_size()
|> Kernel.+(5)
|> Integer.to_string(16)
|> String.downcase()
|> String.pad_leading(4, "0")
|> Kernel.<>(data)
|> Kernel.<>("\n")
end
#
# Helpers
#
defp server_capabilities("git-upload-pack"), do: Enum.join(@upload_caps, " ")
defp server_capabilities("git-receive-pack"), do: Enum.join(@receive_caps, " ")
defp format_ref_line({oid, refname}), do: "#{Git.oid_fmt(oid)} #{refname}"
defp reference_head(repo) do
case Git.reference_resolve(repo, "HEAD") do
{:ok, _refname, _shorthand, oid} -> {oid, "HEAD"}
{:error, _reason} -> []
end
end
defp reference_list(repo) do
case Git.reference_stream(repo, "refs/heads/*") do
{:ok, stream} -> Enum.map(stream, fn {refname, _shortand, :oid, oid} -> {oid, refname} end)
{:error, _reason} -> []
end
end
defp reference_tags(repo) do
case Git.reference_stream(repo, "refs/tags/*") do
{:ok, stream} -> Enum.map(stream, &peel_tag_ref(repo, &1))
{:error, _reason} -> []
end
end
defp peel_tag_ref(repo, {refname, _shorthand, :oid, oid}) do
with {:ok, :tag, tag} <- Git.object_lookup(repo, oid),
{:ok, :commit, ^oid, commit} <- Git.tag_peel(tag),
{:ok, tag_oid} <- Git.object_id(commit) do
[{tag_oid, refname}, {oid, refname <> "^{}"}]
else
{:ok, :commit, _commit} -> {oid, refname}
end
end
defp pkt_stream(data) do
Stream.resource(fn -> data end, &pkt_next/1, fn _ -> :ok end)
end
defp pkt_next(""), do: {:halt, nil}
defp pkt_next("0000" <> rest), do: {[:flush], rest}
defp pkt_next("PACK" <> rest), do: Packfile.parse(rest)
defp pkt_next(<<hex::bytes-size(4), payload::binary>>) do
{payload_size, ""} = Integer.parse(hex, 16)
data_size = payload_size - 4
data_size_skip_lf = data_size - 1
case payload do
<<data::bytes-size(data_size_skip_lf), "\n", rest::binary>> ->
{[data], rest}
<<data::bytes-size(data_size), rest::binary>> ->
{[data], rest}
<<data::bytes-size(data_size)>> ->
{[data], ""}
end
end
defp pkt_decode("done"), do: :done
defp pkt_decode("want " <> hash), do: {:want, hash}
defp pkt_decode("have " <> hash), do: {:have, hash}
defp pkt_decode("shallow " <> hash), do: {:shallow, hash}
defp pkt_decode(pkt_line), do: pkt_line
end
| 31.324138 | 97 | 0.628798 |
e8183a0934154596c2a4d9d642bf5f50a91405ff | 2,403 | exs | Elixir | test/controllers/user_controller_test.exs | cjen07/social_network | 91011db115c2e7c9806652c1fff197049c9d62eb | [
"MIT"
] | 17 | 2017-01-02T10:38:28.000Z | 2021-02-28T22:16:54.000Z | test/controllers/user_controller_test.exs | cjen07/social_network | 91011db115c2e7c9806652c1fff197049c9d62eb | [
"MIT"
] | null | null | null | test/controllers/user_controller_test.exs | cjen07/social_network | 91011db115c2e7c9806652c1fff197049c9d62eb | [
"MIT"
] | 2 | 2017-01-09T13:02:13.000Z | 2018-06-16T22:01:53.000Z | defmodule SocialNetwork.UserControllerTest do
use SocialNetwork.ConnCase
# alias SocialNetwork.User
# @valid_attrs %{}
# @invalid_attrs %{}
# test "lists all entries on index", %{conn: conn} do
# conn = get conn, user_path(conn, :index)
# assert html_response(conn, 200) =~ "Listing users"
# end
# test "renders form for new resources", %{conn: conn} do
# conn = get conn, user_path(conn, :new)
# assert html_response(conn, 200) =~ "New user"
# end
# test "creates resource and redirects when data is valid", %{conn: conn} do
# conn = post conn, user_path(conn, :create), user: @valid_attrs
# assert redirected_to(conn) == user_path(conn, :index)
# assert Repo.get_by(User, @valid_attrs)
# end
# test "does not create resource and renders errors when data is invalid", %{conn: conn} do
# conn = post conn, user_path(conn, :create), user: @invalid_attrs
# assert html_response(conn, 200) =~ "New user"
# end
# test "shows chosen resource", %{conn: conn} do
# user = Repo.insert! %User{}
# conn = get conn, user_path(conn, :show, user)
# assert html_response(conn, 200) =~ "Show user"
# end
# test "renders page not found when id is nonexistent", %{conn: conn} do
# assert_error_sent 404, fn ->
# get conn, user_path(conn, :show, -1)
# end
# end
# test "renders form for editing chosen resource", %{conn: conn} do
# user = Repo.insert! %User{}
# conn = get conn, user_path(conn, :edit, user)
# assert html_response(conn, 200) =~ "Edit user"
# end
# test "updates chosen resource and redirects when data is valid", %{conn: conn} do
# user = Repo.insert! %User{}
# conn = put conn, user_path(conn, :update, user), user: @valid_attrs
# assert redirected_to(conn) == user_path(conn, :show, user)
# assert Repo.get_by(User, @valid_attrs)
# end
# test "does not update chosen resource and renders errors when data is invalid", %{conn: conn} do
# user = Repo.insert! %User{}
# conn = put conn, user_path(conn, :update, user), user: @invalid_attrs
# assert html_response(conn, 200) =~ "Edit user"
# end
# test "deletes chosen resource", %{conn: conn} do
# user = Repo.insert! %User{}
# conn = delete conn, user_path(conn, :delete, user)
# assert redirected_to(conn) == user_path(conn, :index)
# refute Repo.get(User, user.id)
# end
end
| 35.865672 | 100 | 0.648356 |
e8183ee88ba70b7a2e06da6c1fdae775c5bcdd18 | 1,430 | ex | Elixir | lib/taex/points/bollinger.ex | benyblack/Taex | a98bb1523497c455ce626cadd345185ecc03cea8 | [
"MIT"
] | 20 | 2017-07-17T13:08:21.000Z | 2021-07-15T05:58:19.000Z | lib/taex/points/bollinger.ex | benyblack/Taex | a98bb1523497c455ce626cadd345185ecc03cea8 | [
"MIT"
] | 3 | 2017-09-06T12:23:45.000Z | 2021-05-25T07:11:06.000Z | lib/taex/points/bollinger.ex | benyblack/Taex | a98bb1523497c455ce626cadd345185ecc03cea8 | [
"MIT"
] | 6 | 2017-09-01T15:43:17.000Z | 2019-12-30T07:58:25.000Z | defmodule Taex.Points.Bollinger do
alias Statistics
alias Taex.MovingAverage
@moduledoc """
The calculation for this was taken from http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:bollinger_bands
Bollinger Band is a registered trademark of John Bollinger.
"""
@type t :: %{upper: float, middle: float, lower: float}
defstruct [:upper, :middle, :lower]
def calculate(prices) do
last_twenty = prices |> Enum.reverse |> Enum.take(20)
%Taex.Points.Bollinger {
upper: bollinger_band(last_twenty, fn x, y -> x + y end),
middle: bollinger_middle_band(last_twenty),
lower: bollinger_band(last_twenty, fn x, y -> x - y end)
}
end
@doc """
The middle band is the 20 simple moving average of the prices
"""
@spec bollinger_middle_band([float]) :: float
defp bollinger_middle_band(prices) do
MovingAverage.simple(20, prices)
end
@doc """
Calculates the band for bollinger. The function that is provided is the basis of which band this is calculating.
If fn x y -> x + y end is passed in then it will calculate the upper band
If fn x y -> x - y end is passed in then it will calculate the lower band
"""
@spec bollinger_band([float], function) :: float
defp bollinger_band(prices, f) when is_function(f) and is_list(prices) do
stdev = Statistics.stdev(prices)
f.(MovingAverage.simple(20, prices), (stdev * 2))
end
end | 34.878049 | 133 | 0.704196 |
e818b525e727f27d11caabc8ee7569206844f321 | 373 | ex | Elixir | apps/route_patterns/lib/repo_api.ex | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 42 | 2019-05-29T16:05:30.000Z | 2021-08-09T16:03:37.000Z | apps/route_patterns/lib/repo_api.ex | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 872 | 2019-05-29T17:55:50.000Z | 2022-03-30T09:28:43.000Z | apps/route_patterns/lib/repo_api.ex | noisecapella/dotcom | d5ef869412102d2230fac3dcc216f01a29726227 | [
"MIT"
] | 12 | 2019-07-01T18:33:21.000Z | 2022-03-10T02:13:57.000Z | defmodule RoutePatterns.RepoApi do
@moduledoc """
Behavior for an API client for fetching route pattern data.
"""
alias RoutePatterns.RoutePattern
alias Routes.Route
@doc """
Return all route patterns for a route ID
"""
@callback by_route_id(Route.id_t()) :: [RoutePattern.t()]
@callback by_route_id(Route.id_t(), keyword()) :: [RoutePattern.t()]
end
| 24.866667 | 70 | 0.705094 |
e818cad49d0afd8ad02e03f5fc4aec2d307cf369 | 386 | ex | Elixir | lib/osm_points_web/router.ex | OSM-Browser/points-api | 7022d4e61318fc8da507809302a57bf38223207a | [
"MIT"
] | 2 | 2018-01-18T20:38:08.000Z | 2020-01-19T17:44:20.000Z | lib/osm_points_web/router.ex | OSM-Browser/points-api | 7022d4e61318fc8da507809302a57bf38223207a | [
"MIT"
] | 85 | 2018-02-26T05:30:01.000Z | 2021-07-26T06:22:02.000Z | lib/osm_points_web/router.ex | OSM-Browser/points-api | 7022d4e61318fc8da507809302a57bf38223207a | [
"MIT"
] | 1 | 2018-10-07T06:57:34.000Z | 2018-10-07T06:57:34.000Z | defmodule OsmPointsWeb.Router do
use OsmPointsWeb, :router
use Plugsnag
pipeline :api do
plug :accepts, ["json"]
end
scope "/" do
pipe_through :api
get "/points", OsmPointsWeb.PointController, :index
forward "/graphiql", Absinthe.Plug.GraphiQL,
schema: OsmPointsWeb.Schema
forward "/", Absinthe.Plug,
schema: OsmPointsWeb.Schema
end
end
| 18.380952 | 55 | 0.681347 |
e818ce69c3897267ae1fc754ebd3109a70115e08 | 3,419 | exs | Elixir | mix.exs | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | mix.exs | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | mix.exs | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | defmodule Cizen.MixProject do
use Mix.Project
def project do
[
app: :cizen,
version: "0.18.1",
package: package(),
elixir: "~> 1.7",
elixirc_paths: elixirc_paths(Mix.env()),
start_permanent: Mix.env() == :prod,
deps: deps(),
name: "Cizen",
docs: docs(),
source_url: "https://github.com/Hihaheho-Studios/Cizen",
description: """
Build highly concurrent, monitorable, and extensible applications with a collection of automata.
""",
aliases: aliases(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [
coveralls: :test,
"coveralls.detail": :test,
"coveralls.post": :test,
"coveralls.html": :test
]
]
end
def application do
[
start_phases: [start_children: [], start_daemons: []],
extra_applications: [:logger],
mod: {Cizen.Application, []},
env: [event_router: Cizen.DefaultEventRouter]
]
end
defp package do
[
links: %{gitlab: "https://gitlab.com/cizen/cizen"},
licenses: ["MIT"]
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
defp deps do
[
{:recon, "~> 2.5", only: :test},
{:uuid, "~> 1.1"},
{:poison, "~> 4.0", only: :test, runtime: false},
{:credo, "~> 0.10.0", only: [:dev, :test], runtime: false},
{:dialyxir, "~> 1.0.0-rc.3", only: [:dev, :test], runtime: false},
{:excoveralls, "~> 0.8", only: [:dev, :test], runtime: false},
{:ex_doc, "~> 0.23.0", only: :dev},
{:mock, "~> 0.3", only: :test}
]
end
defp docs do
[
main: "readme",
extra_section: "GUIDES",
groups_for_modules: groups_for_modules(),
extras: extras(),
groups_for_extras: groups_for_extras()
]
end
defp extras do
[
"README.md",
"guides/getting_started.md",
"guides/basic_concepts/event.md",
"guides/basic_concepts/pattern.md",
"guides/basic_concepts/saga.md",
"guides/basic_concepts/effect.md",
"guides/basic_concepts/test.md",
]
end
defp groups_for_extras do
[
Guides: ~r/guides\/[^\/]+\.md/,
"Basic Concepts": ~r/guides\/basic_concepts\/.?/,
]
end
defp groups_for_modules do
[
Automaton: [
Cizen.Automaton
],
Dispatchers: [
Cizen.Dispatcher,
Cizen.Event,
Cizen.Pattern
],
Effects: [
Cizen.Effects,
Cizen.Effects.All,
Cizen.Effects.Chain,
Cizen.Effects.Dispatch,
Cizen.Effects.End,
Cizen.Effects.Fork,
Cizen.Effects.Map,
Cizen.Effects.Monitor,
Cizen.Effects.Race,
Cizen.Effects.Receive,
Cizen.Effects.Resume,
Cizen.Effects.Start,
Cizen.Effects.Subscribe
],
Effectful: [
Cizen.Effectful
],
Saga: [
Cizen.Saga,
Cizen.Saga.Crashed,
Cizen.Saga.Finish,
Cizen.Saga.Finished,
Cizen.Saga.Started,
Cizen.SagaRegistry,
],
Test: [
Cizen.Test
]
]
end
defp aliases do
[
credo: ["credo --strict"],
check: [
"compile --warnings-as-errors",
"format --check-formatted --check-equivalent",
"credo --strict",
"dialyzer --no-compile --halt-exit-status"
]
]
end
end
| 23.57931 | 102 | 0.548113 |
e818d287e4b6dfeb9c3d9df8658e0d2abd0c78a9 | 1,439 | exs | Elixir | config/dev.exs | infinitered/phoenix_base | 8c8ddd63ff1412f9f90cbe7cf24278618bcb2e11 | [
"MIT"
] | 71 | 2016-01-07T18:36:47.000Z | 2021-02-26T00:21:58.000Z | config/dev.exs | infinitered/phoenix_base | 8c8ddd63ff1412f9f90cbe7cf24278618bcb2e11 | [
"MIT"
] | 15 | 2016-01-15T17:48:07.000Z | 2017-07-18T16:00:03.000Z | config/dev.exs | infinitered/phoenix_base | 8c8ddd63ff1412f9f90cbe7cf24278618bcb2e11 | [
"MIT"
] | 22 | 2016-02-02T23:49:21.000Z | 2019-08-08T12:53:49.000Z | use Mix.Config
# For development, we disable any cache and enable
# debugging and code reloading.
#
# The watchers configuration can be used to run external
# watchers to your application. For example, we use it
# with brunch.io to recompile .js and .css sources.
config :phoenix_base, PhoenixBase.Endpoint,
http: [port: 4000],
debug_errors: true,
code_reloader: true,
cache_static_lookup: false,
check_origin: false,
watchers: [
node: ["node_modules/webpack/bin/webpack.js",
"--watch-stdin", "--color", "--progress"]
]
# Watch static and templates for browser reloading.
config :phoenix_base, PhoenixBase.Endpoint,
live_reload: [
patterns: [
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{priv/gettext/.*(po)$},
~r{web/views/.*(ex)$},
~r{web/templates/.*(eex|slim)$}
]
]
# Do not include metadata nor timestamps in development logs
config :logger, :console, format: "[$level] $message\n"
# Set a higher stacktrace during development.
# Do not configure such in production as keeping
# and calculating stacktraces is usually expensive.
config :phoenix, :stacktrace_depth, 20
# Configure your database
config :phoenix_base, PhoenixBase.Repo,
adapter: Ecto.Adapters.Postgres,
database: "phoenix_base_dev",
hostname: "localhost",
pool_size: 10
# Configure mailer for local previews
config :phoenix_base, PhoenixBase.Mailer,
adapter: Swoosh.Adapters.Local
| 29.367347 | 60 | 0.715775 |
e81917a183f43dd391c51945e618de9e8de08d58 | 3,332 | exs | Elixir | test/task_bunny/status/worker_test.exs | spencerdcarlson/task_bunny | 2a4b1be32110858f1466d945e5b3248862ef60a2 | [
"MIT"
] | null | null | null | test/task_bunny/status/worker_test.exs | spencerdcarlson/task_bunny | 2a4b1be32110858f1466d945e5b3248862ef60a2 | [
"MIT"
] | 55 | 2020-05-12T05:18:41.000Z | 2022-03-24T04:04:17.000Z | test/task_bunny/status/worker_test.exs | jnylen/task_bunny | 72f014960b71b3e4b2685f9296c28819cd85929f | [
"MIT"
] | 2 | 2018-12-14T23:35:00.000Z | 2019-05-17T20:40:53.000Z | defmodule TaskBunny.Status.WorkerTest do
use ExUnit.Case, async: false
import TaskBunny.QueueTestHelper
alias TaskBunny.{Config, Queue, JobTestHelper}
alias JobTestHelper.TestJob
@host :worker_test
@supervisor :worker_test_supervisor
@worker_supervisor :worker_test_worker_supervisor
@publisher :workert_test_publisher
@queue1 "task_bunny.status.worker_test1"
@queue2 "task_bunny.status.worker_test2"
defmodule RejectJob do
use TaskBunny.Job
def perform(payload) do
JobTestHelper.Tracer.performed(payload)
:error
end
def retry_interval, do: 1
def max_retry, do: 0
end
defp find_worker(workers, queue) do
Enum.find(workers, fn %{queue: w_queue} -> queue == w_queue end)
end
defp all_queues do
Queue.queue_with_subqueues(@queue1) ++ Queue.queue_with_subqueues(@queue2)
end
defp mock_config do
workers = [
[host: @host, queue: @queue1, concurrency: 3],
[host: @host, queue: @queue2, concurrency: 3]
]
:meck.new(Config, [:passthrough])
:meck.expect(Config, :hosts, fn -> [@host] end)
:meck.expect(Config, :connect_options, fn @host -> "amqp://localhost" end)
:meck.expect(Config, :workers, fn(_any) -> workers end)
end
setup do
clean(all_queues())
mock_config()
JobTestHelper.setup()
TaskBunny.Supervisor.start_link(@supervisor, @worker_supervisor, @publisher)
JobTestHelper.wait_for_connection(@host)
Queue.declare_with_subqueues(:default, @queue1)
Queue.declare_with_subqueues(:default, @queue2)
on_exit(fn ->
:meck.unload()
JobTestHelper.teardown()
end)
:ok
end
describe "runners" do
test "running with no jobs being performed" do
%{workers: workers} = TaskBunny.Status.overview(@supervisor)
%{runners: runner_count} = List.first(workers)
assert runner_count == 0
end
test "running with jobs being performed" do
payload = %{"sleep" => 10_000}
TestJob.enqueue(payload, host: @host, queue: @queue1)
TestJob.enqueue(payload, host: @host, queue: @queue1)
JobTestHelper.wait_for_perform(2)
%{workers: workers} = TaskBunny.Status.overview(@supervisor)
%{runners: runner_count} = find_worker(workers, @queue1)
assert runner_count == 2
end
end
describe "job stats" do
test "jobs succeeded" do
payload = %{"hello" => "world1"}
TestJob.enqueue(payload, host: @host, queue: @queue1)
JobTestHelper.wait_for_perform()
%{workers: workers} = TaskBunny.Status.overview(@supervisor)
%{stats: stats} = find_worker(workers, @queue1)
assert stats.succeeded == 1
end
test "jobs failed" do
payload = %{"fail" => "fail"}
TestJob.enqueue(payload, host: @host, queue: @queue1)
JobTestHelper.wait_for_perform()
%{workers: workers} = TaskBunny.Status.overview(@supervisor)
%{stats: stats} = find_worker(workers, @queue1)
assert stats.failed == 1
end
test "jobs rejected" do
payload = %{"fail" => "fail"}
RejectJob.enqueue(payload, host: @host, queue: @queue2)
JobTestHelper.wait_for_perform()
%{workers: workers} = TaskBunny.Status.overview(@supervisor)
%{stats: stats} = find_worker(workers, @queue2)
assert stats.rejected == 1
end
end
end
| 25.829457 | 80 | 0.669868 |
e8191b78e3251b3ac58b60c484a38c1007cfb630 | 319 | exs | Elixir | 01_test.exs | ivanrosolen/how-to-elixir | 46386a1316a39ac083cb4efa96eaf4641b2ac3ac | [
"MIT"
] | null | null | null | 01_test.exs | ivanrosolen/how-to-elixir | 46386a1316a39ac083cb4efa96eaf4641b2ac3ac | [
"MIT"
] | null | null | null | 01_test.exs | ivanrosolen/how-to-elixir | 46386a1316a39ac083cb4efa96eaf4641b2ac3ac | [
"MIT"
] | null | null | null | #IO.puts("Ivan")
#IO.puts "Rosolen"
#IO.puts "Ivan" <> "Rosolen"
ExUnit.start
defmodule IvanTest do
use ExUnit.Case
test "sucesso" do
assert 1 + 1 == 2
end
test 'erro' do
refute 1 + 1 == 3
end
test :atom_assert_raise do
assert_raise ArithmeticError, fn ->
1 + "x"
end
end
end | 13.291667 | 39 | 0.605016 |
e8192f1fd9197199bf8c739d58ce583d71077a4f | 158 | ex | Elixir | lib/excoveralls_linter/coverage_tool.ex | miros/excoveralls_linter | 661e9d4019d9f8842340c172d78341e8822d4d6c | [
"Apache-2.0"
] | 4 | 2019-11-25T15:32:45.000Z | 2020-01-29T23:27:45.000Z | lib/excoveralls_linter/coverage_tool.ex | miros/excoveralls_linter | 661e9d4019d9f8842340c172d78341e8822d4d6c | [
"Apache-2.0"
] | null | null | null | lib/excoveralls_linter/coverage_tool.ex | miros/excoveralls_linter | 661e9d4019d9f8842340c172d78341e8822d4d6c | [
"Apache-2.0"
] | null | null | null | defmodule ExCoverallsLinter.CoverageTool do
alias ExCoverallsLinter.SourceFile
@type t :: module
@callback get_coverage() :: list(SourceFile.t())
end
| 19.75 | 50 | 0.765823 |
e8193ec609d1348b24faf4c1b0090a7bee3570e4 | 5,595 | exs | Elixir | lib/elixir/test/elixir/map_set_test.exs | oskarkook/elixir | 2ddd291c533cdc2b1b1f02153d94c0b248cb9836 | [
"Apache-2.0"
] | 1 | 2019-06-27T08:47:13.000Z | 2019-06-27T08:47:13.000Z | lib/elixir/test/elixir/map_set_test.exs | oskarkook/elixir | 2ddd291c533cdc2b1b1f02153d94c0b248cb9836 | [
"Apache-2.0"
] | null | null | null | lib/elixir/test/elixir/map_set_test.exs | oskarkook/elixir | 2ddd291c533cdc2b1b1f02153d94c0b248cb9836 | [
"Apache-2.0"
] | null | null | null | Code.require_file("test_helper.exs", __DIR__)
defmodule MapSetTest do
use ExUnit.Case, async: true
doctest MapSet
test "new/1" do
result = MapSet.new(1..5)
assert MapSet.equal?(result, Enum.into(1..5, MapSet.new()))
end
test "new/2" do
result = MapSet.new(1..5, &(&1 + 2))
assert MapSet.equal?(result, Enum.into(3..7, MapSet.new()))
end
test "put/2" do
result = MapSet.put(MapSet.new(), 1)
assert MapSet.equal?(result, MapSet.new([1]))
result = MapSet.put(MapSet.new([1, 3, 4]), 2)
assert MapSet.equal?(result, MapSet.new(1..4))
result = MapSet.put(MapSet.new(5..100), 10)
assert MapSet.equal?(result, MapSet.new(5..100))
end
test "union/2" do
result = MapSet.union(MapSet.new([1, 3, 4]), MapSet.new())
assert MapSet.equal?(result, MapSet.new([1, 3, 4]))
result = MapSet.union(MapSet.new(5..15), MapSet.new(10..25))
assert MapSet.equal?(result, MapSet.new(5..25))
result = MapSet.union(MapSet.new(1..120), MapSet.new(1..100))
assert MapSet.equal?(result, MapSet.new(1..120))
end
test "intersection/2" do
result = MapSet.intersection(MapSet.new(), MapSet.new(1..21))
assert MapSet.equal?(result, MapSet.new())
result = MapSet.intersection(MapSet.new(1..21), MapSet.new(4..24))
assert MapSet.equal?(result, MapSet.new(4..21))
result = MapSet.intersection(MapSet.new(2..100), MapSet.new(1..120))
assert MapSet.equal?(result, MapSet.new(2..100))
end
test "difference/2" do
result = MapSet.difference(MapSet.new(2..20), MapSet.new())
assert MapSet.equal?(result, MapSet.new(2..20))
result = MapSet.difference(MapSet.new(2..20), MapSet.new(1..21))
assert MapSet.equal?(result, MapSet.new())
result = MapSet.difference(MapSet.new(1..101), MapSet.new(2..100))
assert MapSet.equal?(result, MapSet.new([1, 101]))
end
test "disjoint?/2" do
assert MapSet.disjoint?(MapSet.new(), MapSet.new())
assert MapSet.disjoint?(MapSet.new(1..6), MapSet.new(8..20))
refute MapSet.disjoint?(MapSet.new(1..6), MapSet.new(5..15))
refute MapSet.disjoint?(MapSet.new(1..120), MapSet.new(1..6))
end
test "subset?/2" do
assert MapSet.subset?(MapSet.new(), MapSet.new())
assert MapSet.subset?(MapSet.new(1..6), MapSet.new(1..10))
assert MapSet.subset?(MapSet.new(1..6), MapSet.new(1..120))
refute MapSet.subset?(MapSet.new(1..120), MapSet.new(1..6))
end
test "equal?/2" do
assert MapSet.equal?(MapSet.new(), MapSet.new())
refute MapSet.equal?(MapSet.new(1..20), MapSet.new(2..21))
assert MapSet.equal?(MapSet.new(1..120), MapSet.new(1..120))
end
test "delete/2" do
result = MapSet.delete(MapSet.new(), 1)
assert MapSet.equal?(result, MapSet.new())
result = MapSet.delete(MapSet.new(1..4), 5)
assert MapSet.equal?(result, MapSet.new(1..4))
result = MapSet.delete(MapSet.new(1..4), 1)
assert MapSet.equal?(result, MapSet.new(2..4))
result = MapSet.delete(MapSet.new(1..4), 2)
assert MapSet.equal?(result, MapSet.new([1, 3, 4]))
end
test "size/1" do
assert MapSet.size(MapSet.new()) == 0
assert MapSet.size(MapSet.new(5..15)) == 11
assert MapSet.size(MapSet.new(2..100)) == 99
end
test "to_list/1" do
assert MapSet.to_list(MapSet.new()) == []
list = MapSet.to_list(MapSet.new(1..20))
assert Enum.sort(list) == Enum.to_list(1..20)
list = MapSet.to_list(MapSet.new(5..120))
assert Enum.sort(list) == Enum.to_list(5..120)
end
test "filter/2" do
result = MapSet.filter(MapSet.new([1, nil, 2, false]), & &1)
assert MapSet.equal?(result, MapSet.new(1..2))
result = MapSet.filter(MapSet.new(1..10), &(&1 < 2 or &1 > 9))
assert MapSet.equal?(result, MapSet.new([1, 10]))
result = MapSet.filter(MapSet.new(~w(A a B b)), fn x -> String.downcase(x) == x end)
assert MapSet.equal?(result, MapSet.new(~w(a b)))
end
test "reject/2" do
result = MapSet.reject(MapSet.new(1..10), &(&1 < 8))
assert MapSet.equal?(result, MapSet.new(8..10))
result = MapSet.reject(MapSet.new(["a", :b, 1, 1.0]), &is_integer/1)
assert MapSet.equal?(result, MapSet.new(["a", :b, 1.0]))
result = MapSet.reject(MapSet.new(1..3), fn x -> rem(x, 2) == 0 end)
assert MapSet.equal?(result, MapSet.new([1, 3]))
end
test "MapSet v1 compatibility" do
result = 1..5 |> map_set_v1() |> MapSet.new()
assert MapSet.equal?(result, MapSet.new(1..5))
result = MapSet.put(map_set_v1(1..5), 6)
assert MapSet.equal?(result, MapSet.new(1..6))
result = MapSet.union(map_set_v1(1..5), MapSet.new(6..10))
assert MapSet.equal?(result, MapSet.new(1..10))
result = MapSet.intersection(map_set_v1(1..10), MapSet.new(6..15))
assert MapSet.equal?(result, MapSet.new(6..10))
result = MapSet.difference(map_set_v1(1..10), MapSet.new(6..50))
assert MapSet.equal?(result, MapSet.new(1..5))
result = MapSet.delete(map_set_v1(1..10), 1)
assert MapSet.equal?(result, MapSet.new(2..10))
assert MapSet.size(map_set_v1(1..5)) == 5
assert MapSet.to_list(map_set_v1(1..5)) == Enum.to_list(1..5)
assert MapSet.disjoint?(map_set_v1(1..5), MapSet.new(10..15))
refute MapSet.disjoint?(map_set_v1(1..5), MapSet.new(5..10))
assert MapSet.subset?(map_set_v1(3..7), MapSet.new(1..10))
refute MapSet.subset?(map_set_v1(7..12), MapSet.new(1..10))
end
test "inspect" do
assert inspect(MapSet.new([?a])) == "MapSet.new([97])"
end
defp map_set_v1(enumerable) do
map = Map.from_keys(Enum.to_list(enumerable), true)
%{__struct__: MapSet, map: map}
end
end
| 32.52907 | 88 | 0.640393 |
e8194515e46ab5a5a2d85e9372a6692124452ac1 | 1,371 | ex | Elixir | test/support/data_case.ex | no0x9d/chankins | b4fd37d3145a001e4ebbe86eea91742d5a812858 | [
"MIT"
] | null | null | null | test/support/data_case.ex | no0x9d/chankins | b4fd37d3145a001e4ebbe86eea91742d5a812858 | [
"MIT"
] | null | null | null | test/support/data_case.ex | no0x9d/chankins | b4fd37d3145a001e4ebbe86eea91742d5a812858 | [
"MIT"
] | null | null | null | defmodule Chankins.DataCase do
@moduledoc """
This module defines the setup for tests requiring
access to the application's data layer.
You may define functions here to be used as helpers in
your tests.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
alias Chankins.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query
import Chankins.DataCase
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Chankins.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Chankins.Repo, {:shared, self()})
end
:ok
end
@doc """
A helper that transform changeset errors to a map of messages.
changeset = Accounts.create_user(%{password: "short"})
assert "password is too short" in errors_on(changeset).password
assert %{password: ["password is too short"]} = errors_on(changeset)
"""
def errors_on(changeset) do
Ecto.Changeset.traverse_errors(changeset, fn {message, opts} ->
Enum.reduce(opts, message, fn {key, value}, acc ->
String.replace(acc, "%{#{key}}", to_string(value))
end)
end)
end
end
| 25.388889 | 74 | 0.681255 |
e81965bf6e4ad693f639e7d3c414a233f4a5b21a | 2,203 | ex | Elixir | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/dns/lib/google_api/dns/v1/model/resource_record_sets_list_response.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
@moduledoc """
## Attributes
- kind (String): Type of resource. Defaults to: `null`.
- nextPageToken (String): The presence of this field indicates that there exist more results following your last page of results in pagination order. To fetch them, make another list request using this value as your pagination token. In this way you can retrieve the complete contents of even very large collections one page at a time. However, if the contents of the collection change between the first and last paginated list request, the set of all elements returned will be an inconsistent view of the collection. There is no way to retrieve a consistent snapshot of a collection larger than the maximum page size. Defaults to: `null`.
- rrsets (List[ResourceRecordSet]): The resource record set resources. Defaults to: `null`.
"""
defstruct [
:"kind",
:"nextPageToken",
:"rrsets"
]
end
defimpl Poison.Decoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
import GoogleApi.DNS.V1.Deserializer
def decode(value, options) do
value
|> deserialize(:"rrsets", :list, GoogleApi.DNS.V1.Model.ResourceRecordSet, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.DNS.V1.Model.ResourceRecordSetsListResponse do
def encode(value, options) do
GoogleApi.DNS.V1.Deserializer.serialize_non_nil(value, options)
end
end
| 42.365385 | 642 | 0.76305 |
e819ab63d7015432f11d668a673e78aa828ae231 | 1,495 | ex | Elixir | clients/access_approval/lib/google_api/access_approval/v1/model/dismiss_decision.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/access_approval/lib/google_api/access_approval/v1/model/dismiss_decision.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/access_approval/lib/google_api/access_approval/v1/model/dismiss_decision.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.AccessApproval.V1.Model.DismissDecision do
@moduledoc """
A decision that has been made to dismiss an approval request.
## Attributes
* `dismissTime` (*type:* `DateTime.t`, *default:* `nil`) - The time at which the approval request was dismissed.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:dismissTime => DateTime.t()
}
field(:dismissTime, as: DateTime)
end
defimpl Poison.Decoder, for: GoogleApi.AccessApproval.V1.Model.DismissDecision do
def decode(value, options) do
GoogleApi.AccessApproval.V1.Model.DismissDecision.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AccessApproval.V1.Model.DismissDecision do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.808511 | 116 | 0.743813 |
e819b5afd6398bddc101fa5dc75c5c4bea8c7b11 | 571 | ex | Elixir | lib/zaryn/p2p/endpoint/supervisor.ex | ambareesha7/node-zaryn | 136e542801bf9b6fa4a015d3464609fdf3dacee8 | [
"Apache-2.0"
] | 1 | 2021-07-06T19:47:14.000Z | 2021-07-06T19:47:14.000Z | lib/zaryn/p2p/endpoint/supervisor.ex | ambareesha7/node-zaryn | 136e542801bf9b6fa4a015d3464609fdf3dacee8 | [
"Apache-2.0"
] | null | null | null | lib/zaryn/p2p/endpoint/supervisor.ex | ambareesha7/node-zaryn | 136e542801bf9b6fa4a015d3464609fdf3dacee8 | [
"Apache-2.0"
] | null | null | null | defmodule Zaryn.P2P.Endpoint.Supervisor do
@moduledoc false
use Supervisor
alias Zaryn.P2P.Endpoint.Listener
alias Zaryn.Utils
def start_link(args) do
Supervisor.start_link(__MODULE__, args, name: __MODULE__)
end
def init(args) do
static_children = [
{Task.Supervisor, strategy: :one_for_one, name: Zaryn.P2P.Endpoint.ConnectionSupervisor}
]
optional_children = [
{Listener, args, []}
]
Supervisor.init(static_children ++ Utils.configurable_children(optional_children),
strategy: :one_for_one
)
end
end
| 21.148148 | 94 | 0.709282 |
e819ce0acfb8a956281930557307e2049864aeae | 4,535 | exs | Elixir | test/magnemite/accounts/account_opening_requests_test.exs | andsleonardo/magnemite | 2a06c1520defeb193d718313ad3fc6a50349bc8d | [
"MIT"
] | null | null | null | test/magnemite/accounts/account_opening_requests_test.exs | andsleonardo/magnemite | 2a06c1520defeb193d718313ad3fc6a50349bc8d | [
"MIT"
] | null | null | null | test/magnemite/accounts/account_opening_requests_test.exs | andsleonardo/magnemite | 2a06c1520defeb193d718313ad3fc6a50349bc8d | [
"MIT"
] | null | null | null | defmodule Magnemite.Accounts.AccountOpeningRequestsTest do
use Magnemite.DataCase, async: true
alias Magnemite.Accounts.{
Account,
AccountOpeningRequest,
AccountOpeningRequests
}
describe "list_done_by_referrer_id/1" do
test "lists complete requests matching referrer_id" do
%{id: account_opening_request_id, referrer_id: referrer_id} =
insert(:complete_account_opening_request)
assert [%{id: ^account_opening_request_id}] =
AccountOpeningRequests.list_done_by_referrer_id(referrer_id)
end
test "returns an empty list when all requests matching referrer_id are pending" do
%{referrer_id: referrer_id} = insert(:pending_account_opening_request)
assert [] = AccountOpeningRequests.list_done_by_referrer_id(referrer_id)
end
test "returns an empty array when no request matches referrer_id" do
insert(:complete_account_opening_request)
another_referrer_id = Ecto.UUID.generate()
assert [] = AccountOpeningRequests.list_done_by_referrer_id(another_referrer_id)
end
end
describe "get_by_profile_id/1" do
test "gets the account opening request matching profile_id" do
%{id: account_opening_request_id, profile: profile} = insert(:account_opening_request)
assert {:ok, %AccountOpeningRequest{id: ^account_opening_request_id}} =
AccountOpeningRequests.get_by_profile_id(profile.id)
end
test "returns an error when no account opening request matches profile_id" do
assert {:error, :account_opening_request_not_found} =
AccountOpeningRequests.get_by_profile_id(Ecto.UUID.generate())
end
end
describe "get_or_create/2" do
test "gets an account opening request matching profile_id when it exists" do
%{id: account_opening_request, profile: %{id: profile_id}} =
insert(:account_opening_request)
assert {:ok, %AccountOpeningRequest{id: ^account_opening_request}} =
AccountOpeningRequests.get_or_create(profile_id)
end
test "creates a pending account opening request for a profile with a referrer" do
%{id: profile_id} = insert(:profile)
assert {:ok, %AccountOpeningRequest{status: :pending}} =
AccountOpeningRequests.get_or_create(profile_id)
end
test "creates an account opening request for a profile with a referrer" do
%{id: profile_id} = insert(:profile)
%{id: referrer_id} = insert(:profile)
assert {:ok, %AccountOpeningRequest{profile_id: ^profile_id, referrer_id: ^referrer_id}} =
AccountOpeningRequests.get_or_create(profile_id, referrer_id)
end
test "creates an account opening request for a profile without a referrer" do
%{id: profile_id} = insert(:profile)
assert {:ok, %AccountOpeningRequest{profile_id: ^profile_id, referrer_id: nil}} =
AccountOpeningRequests.get_or_create(profile_id)
end
end
describe "complete?/1" do
test "returns true when account opening request's status is :done" do
assert AccountOpeningRequests.complete?(%AccountOpeningRequest{status: :done})
end
test "returns false when account opening request's status is :pending" do
refute AccountOpeningRequests.complete?(%AccountOpeningRequest{status: :pending})
end
end
describe "complete/1" do
test "changes the status of an account opening request to :done" do
account_opening_request = insert(:pending_account_opening_request)
assert {:ok, %AccountOpeningRequest{status: :done}} =
AccountOpeningRequests.complete(account_opening_request)
end
test "leaves a complete account opening request unchanged" do
%{status: :done} = account_opening_request = insert(:complete_account_opening_request)
assert {:ok, %AccountOpeningRequest{status: :done}} =
AccountOpeningRequests.complete(account_opening_request)
end
end
describe "to_account/1" do
test "transforms an account opening request into an account" do
%{profile: profile} = referral_code = insert(:referral_code)
account_opening_request = insert(:complete_account_opening_request, profile: profile)
account = AccountOpeningRequests.to_account(account_opening_request)
assert account == %Account{
id: account_opening_request.id,
name: profile.name,
referral_code: referral_code.number,
status: account_opening_request.status
}
end
end
end
| 37.479339 | 96 | 0.716869 |
e819de097462cd44ec8c5d4c66b142b218df5684 | 7,032 | ex | Elixir | lib/ex_twilio/url_generator.ex | mirego/ex_twilio | 0b4b9c530c151fd5748520ac95a3a9d54f15720b | [
"MIT"
] | null | null | null | lib/ex_twilio/url_generator.ex | mirego/ex_twilio | 0b4b9c530c151fd5748520ac95a3a9d54f15720b | [
"MIT"
] | null | null | null | lib/ex_twilio/url_generator.ex | mirego/ex_twilio | 0b4b9c530c151fd5748520ac95a3a9d54f15720b | [
"MIT"
] | 1 | 2021-11-09T07:56:11.000Z | 2021-11-09T07:56:11.000Z | defmodule ExTwilio.UrlGenerator do
@moduledoc """
Generates Twilio URLs for modules. See `build_url/3` for more information.
"""
alias ExTwilio.Config
@doc """
Infers the proper Twilio URL for a resource when given a module, an optional
SID, and a list of options.
Note that the module should have the following two functions:
- `resource_name/0`
- `resource_collection_name/0`
# Examples
iex> build_url(Resource)
"#{Config.base_url()}/Accounts/#{Config.account_sid()}/Resources.json"
iex> build_url(Resource, nil, account: 2)
"#{Config.base_url()}/Accounts/2/Resources.json"
iex> build_url(Resource, 1, account: 2)
"#{Config.base_url()}/Accounts/2/Resources/1.json"
iex> build_url(Resource, 1)
"#{Config.base_url()}/Accounts/#{Config.account_sid()}/Resources/1.json"
iex> build_url(Resource, nil, page: 20)
"#{Config.base_url()}/Accounts/#{Config.account_sid()}/Resources.json?Page=20"
iex> build_url(Resource, nil, iso_country_code: "US", type: "Mobile", page: 20)
"#{Config.base_url()}/Accounts/#{Config.account_sid()}/Resources/US/Mobile.json?Page=20"
iex> build_url(Resource, 1, sip_ip_access_control_list: "list", account: "account_sid")
"#{Config.base_url()}/Accounts/account_sid/SIP/IpAccessControlLists/list/Resources/1.json"
"""
@spec build_url(atom, String.t() | nil, list) :: String.t()
def build_url(module, id \\ nil, options \\ []) do
{url, options} =
case Module.split(module) do
["ExTwilio", "TaskRouter" | _] ->
options = add_workspace_to_options(module, options)
url = add_segments(Config.task_router_url(), module, id, options)
{url, options}
["ExTwilio", "ProgrammableChat" | _] ->
url = add_segments(Config.programmable_chat_url(), module, id, options)
{url, options}
["ExTwilio", "Notify" | _] ->
url = add_segments(Config.notify_url(), module, id, options)
{url, options}
["ExTwilio", "Fax" | _] ->
url = add_segments(Config.fax_url(), module, id, options)
{url, options}
["ExTwilio", "Studio" | _] ->
options = add_flow_to_options(module, options)
url = add_segments(Config.studio_url(), module, id, options)
{url, options}
_ ->
# Add Account SID segment if not already present
options = add_account_to_options(module, options)
url = add_segments(Config.base_url(), module, id, options) <> ".json"
{url, options}
end
# Append querystring
if Keyword.has_key?(options, :query) do
url <> options[:query]
else
url <> build_query(module, options)
end
end
defp add_segments(url, module, id, options) do
# Append parents
url = url <> build_segments(:parent, normalize_parents(module.parents), options)
# Append module segment
url = url <> segment(:main, {module.resource_name, id})
# Append any child segments
url <> build_segments(:child, module.children, options)
end
@doc """
Generate a list of querystring parameters for a url from an Elixir list.
## Examples
iex> ExTwilio.UrlGenerator.to_query_string([hello: "world", how_are: "you"])
"Hello=world&HowAre=you"
"""
@spec to_query_string(list) :: String.t()
def to_query_string(list) do
list
|> Enum.flat_map(fn
{key, value} when is_list(value) -> Enum.map(value, &{camelize(key), &1})
{key, value} -> [{camelize(key), value}]
end)
|> URI.encode_query()
end
@doc """
Converts a module name into a pluralized Twilio-compatible resource name.
## Examples
iex> ExTwilio.UrlGenerator.resource_name(:"Elixir.ExTwilio.Call")
"Calls"
# Uses only the last segment of the module name
iex> ExTwilio.UrlGenerator.resource_name(:"ExTwilio.Resources.Call")
"Calls"
"""
@spec resource_name(atom | String.t()) :: String.t()
def resource_name(module) do
name = to_string(module)
[[name]] = Regex.scan(~r/[a-z]+$/i, name)
Inflex.pluralize(name)
end
@doc """
Infer a lowercase and underscore collection name for a module.
## Examples
iex> ExTwilio.UrlGenerator.resource_collection_name(Resource)
"resources"
"""
@spec resource_collection_name(atom) :: String.t()
def resource_collection_name(module) do
module
|> resource_name
|> Macro.underscore()
end
@spec add_account_to_options(atom, list) :: list
defp add_account_to_options(module, options) do
if module == ExTwilio.Account and options[:account] == nil do
options
else
Keyword.put_new(options, :account, Config.account_sid())
end
end
@spec add_flow_to_options(atom, list) :: list
defp add_flow_to_options(_module, options) do
Keyword.put_new(options, :flow, Keyword.get(options, :flow_sid))
end
@spec add_workspace_to_options(atom, list) :: list
defp add_workspace_to_options(_module, options) do
Keyword.put_new(options, :workspace, Config.workspace_sid())
end
@spec normalize_parents(list) :: list
defp normalize_parents(parents) do
parents
|> Enum.map(fn
key when is_atom(key) ->
%ExTwilio.Parent{module: Module.concat(ExTwilio, camelize(key)), key: key}
key ->
key
end)
end
@spec build_query(atom, list) :: String.t()
defp build_query(module, options) do
special =
module.parents
|> normalize_parents()
|> Enum.map(fn parent -> parent.key end)
|> Enum.concat(module.children)
|> Enum.concat([:token])
query =
options
|> Enum.reject(fn {key, _val} -> key in special end)
|> to_query_string
if String.length(query) > 0, do: "?" <> query, else: ""
end
@spec build_segments(atom, list, list) :: String.t()
defp build_segments(:parent, allowed_keys, list) do
for %ExTwilio.Parent{module: module, key: key} <- allowed_keys,
into: "",
do: segment(:parent, {%ExTwilio.Parent{module: module, key: key}, list[key]})
end
defp build_segments(type, allowed_keys, list) do
for key <- allowed_keys, into: "", do: segment(type, {key, list[key]})
end
@spec segment(atom, {any, any}) :: String.t()
defp segment(type, segment)
defp segment(type, {_key, nil}) when type in [:parent, :child], do: ""
defp segment(:child, {_key, value}), do: "/" <> to_string(value)
defp segment(:main, {key, nil}), do: "/" <> inflect(key)
defp segment(:main, {key, value}), do: "/#{inflect(key)}/#{value}"
defp segment(:parent, {%ExTwilio.Parent{module: module, key: _key}, value}) do
"/#{module.resource_name}/#{value}"
end
@spec inflect(String.t() | atom) :: String.t()
defp inflect(string) when is_binary(string), do: string
defp inflect(atom) when is_atom(atom) do
atom |> camelize |> Inflex.pluralize()
end
@spec camelize(String.t() | atom) :: String.t()
defp camelize(name) do
name |> to_string |> Macro.camelize()
end
end
| 30.977974 | 96 | 0.64434 |
e819e356b4589d446c2c5e4f8f244b81e832ec58 | 1,097 | ex | Elixir | lib/mix/bonny.ex | happycodrz/bonny | 1c54fadc883be4dac6d25800f74a6d4058319507 | [
"MIT"
] | null | null | null | lib/mix/bonny.ex | happycodrz/bonny | 1c54fadc883be4dac6d25800f74a6d4058319507 | [
"MIT"
] | null | null | null | lib/mix/bonny.ex | happycodrz/bonny | 1c54fadc883be4dac6d25800f74a6d4058319507 | [
"MIT"
] | null | null | null | defmodule Mix.Bonny do
@moduledoc """
Mix task helpers
"""
@doc "Parse CLI input"
def parse_args(args, defaults, cli_opts \\ []) do
{opts, parsed, invalid} = OptionParser.parse(args, cli_opts)
merged_opts = Keyword.merge(defaults, opts)
{merged_opts, parsed, invalid}
end
@doc """
Render text to a file.
Special handling for the path "-" will render to STDOUT
"""
def render(source, "-"), do: IO.puts(source)
def render(source, target) do
Mix.Generator.create_file(target, source)
end
@doc "Get the OTP app name"
def app_name() do
otp_app()
|> Atom.to_string()
|> Macro.camelize()
end
def app_dir_name() do
Macro.underscore(app_name())
end
def template(name) do
template_dir = Application.app_dir(:bonny, ["priv", "templates", "bonny.gen"])
Path.join(template_dir, name)
end
def no_umbrella! do
if Mix.Project.umbrella?() do
Mix.raise("mix bonny.gen.* can only be run inside an application directory")
end
end
defp otp_app() do
Mix.Project.config() |> Keyword.fetch!(:app)
end
end
| 21.509804 | 82 | 0.654512 |
e81a19bc2280f045b22a97c4576728042aa1d647 | 3,117 | exs | Elixir | apps/game_services_web/test/game_services_web/controllers/ticket_controller_test.exs | Alezrik/game_services_umbrella | 9b9dd6707c200b10c5a73568913deb4d5d8320be | [
"MIT"
] | 4 | 2018-11-09T16:57:06.000Z | 2021-03-02T22:57:17.000Z | apps/game_services_web/test/game_services_web/controllers/ticket_controller_test.exs | Alezrik/game_services_umbrella | 9b9dd6707c200b10c5a73568913deb4d5d8320be | [
"MIT"
] | 29 | 2018-10-26T08:29:37.000Z | 2018-12-09T21:02:05.000Z | apps/game_services_web/test/game_services_web/controllers/ticket_controller_test.exs | Alezrik/game_services_umbrella | 9b9dd6707c200b10c5a73568913deb4d5d8320be | [
"MIT"
] | null | null | null | defmodule GameServicesWeb.TicketControllerTest do
use GameServicesWeb.ConnCase
alias GameServices.Authentication
@create_attrs %{
client_token: "some client_token",
salt: "some salt",
server_token: "some server_token",
username: "some username"
}
@update_attrs %{
client_token: "some updated client_token",
salt: "some updated salt",
server_token: "some updated server_token",
username: "some updated username"
}
@invalid_attrs %{client_token: nil, salt: nil, server_token: nil, username: nil}
def fixture(:ticket) do
{:ok, ticket} = Authentication.create_ticket(@create_attrs)
ticket
end
describe "index" do
test "lists all tickets", %{conn: conn} do
conn = get(conn, Routes.ticket_path(conn, :index))
assert html_response(conn, 200) =~ "Listing Tickets"
end
end
describe "new ticket" do
test "renders form", %{conn: conn} do
conn = get(conn, Routes.ticket_path(conn, :new))
assert html_response(conn, 200) =~ "New Ticket"
end
end
describe "create ticket" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post(conn, Routes.ticket_path(conn, :create), ticket: @create_attrs)
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == Routes.ticket_path(conn, :show, id)
conn = get(conn, Routes.ticket_path(conn, :show, id))
assert html_response(conn, 200) =~ "Show Ticket"
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post(conn, Routes.ticket_path(conn, :create), ticket: @invalid_attrs)
assert html_response(conn, 200) =~ "New Ticket"
end
end
describe "edit ticket" do
setup [:create_ticket]
test "renders form for editing chosen ticket", %{conn: conn, ticket: ticket} do
conn = get(conn, Routes.ticket_path(conn, :edit, ticket))
assert html_response(conn, 200) =~ "Edit Ticket"
end
end
describe "update ticket" do
setup [:create_ticket]
test "redirects when data is valid", %{conn: conn, ticket: ticket} do
conn = put(conn, Routes.ticket_path(conn, :update, ticket), ticket: @update_attrs)
assert redirected_to(conn) == Routes.ticket_path(conn, :show, ticket)
conn = get(conn, Routes.ticket_path(conn, :show, ticket))
assert html_response(conn, 200) =~ "some updated client_token"
end
test "renders errors when data is invalid", %{conn: conn, ticket: ticket} do
conn = put(conn, Routes.ticket_path(conn, :update, ticket), ticket: @invalid_attrs)
assert html_response(conn, 200) =~ "Edit Ticket"
end
end
describe "delete ticket" do
setup [:create_ticket]
test "deletes chosen ticket", %{conn: conn, ticket: ticket} do
conn = delete(conn, Routes.ticket_path(conn, :delete, ticket))
assert redirected_to(conn) == Routes.ticket_path(conn, :index)
assert_error_sent 404, fn ->
get(conn, Routes.ticket_path(conn, :show, ticket))
end
end
end
defp create_ticket(_) do
ticket = fixture(:ticket)
{:ok, ticket: ticket}
end
end
| 31.17 | 89 | 0.669875 |
e81a45b8ddfd28f61a76ddaad042b41a47ce4140 | 2,589 | exs | Elixir | deps/earmark/tasks/readme.exs | robot-overlord/starter_kit | 254153221d0a3a06324c65ad8e89d610de2429c3 | [
"MIT"
] | 1 | 2020-01-31T10:23:37.000Z | 2020-01-31T10:23:37.000Z | deps/earmark/tasks/readme.exs | robot-overlord/starter_kit | 254153221d0a3a06324c65ad8e89d610de2429c3 | [
"MIT"
] | null | null | null | deps/earmark/tasks/readme.exs | robot-overlord/starter_kit | 254153221d0a3a06324c65ad8e89d610de2429c3 | [
"MIT"
] | 1 | 2020-09-15T17:47:35.000Z | 2020-09-15T17:47:35.000Z | defmodule Mix.Tasks.Readme do
use Mix.Task
@shortdoc "Build README.md by including module docs"
@moduledoc """
Imagine a README.md that contains
# Overview
<!-- moduledoc: Earmark -->
# Typical calling sequence
<!-- doc: Earmark.to_html -->
Run this task, and the README will be updated with the appropriate
documentation. Markers are also added, so running it again
will update the doc in place.
"""
def run([]) do
Mix.Task.run "compile", []
File.read!("README.md")
|> remove_old_doc
|> add_updated_doc
|> write_back
end
@new_doc ~R/(\s* <!-- \s+ (module)?doc: \s* (\S+?) \s+ -->).*\n/x
@existing_doc ~R/
(?:^|\n+)(\s* <!-- \s+ (module)?doc: \s* (\S+?) \s+ -->).*\n
(?: .*?\n )+?
\s* <!-- \s end(?:module)?doc: \s+ \3 \s+ --> \s*?
/x
defp remove_old_doc(readme) do
Regex.replace(@existing_doc, readme, fn (_, hdr, _, _) ->
hdr
end)
end
defp add_updated_doc(readme) do
Regex.replace(@new_doc, readme, fn (_, hdr, type, name) ->
"\n" <> hdr <> "\n" <>
doc_for(type, name) <>
Regex.replace(~r/!-- /, hdr, "!-- end") <> "\n"
end)
end
defp doc_for("module", name) do
module = String.to_atom("Elixir." <> name)
docs = case Code.ensure_loaded(module) do
{:module, _} ->
if function_exported?(module, :__info__, 1) do
case Code.get_docs(module, :moduledoc) do
{_, docs} when is_binary(docs) ->
docs
_ -> nil
end
else
nil
end
_ -> nil
end
docs # || "No module documentation available for #{name}\n"
end
defp doc_for("", name) do
names = String.split(name, ".")
[ func | modules ] = Enum.reverse(names)
module = Enum.reverse(modules) |> Enum.join(".")
module = String.to_atom("Elixir." <> module)
func = String.to_atom(func)
markdown = case Code.ensure_loaded(module) do
{:module, _} ->
if function_exported?(module, :__info__, 1) do
docs = Code.get_docs(module, :docs)
Enum.find_value(docs, fn ({{fun, _}, _line, _kind, _args, doc}) ->
fun == func && doc
end)
else
nil
end
_ -> nil
end
markdown || "No function documentation available for #{name}\n"
end
defp write_back(readme) do
IO.puts :stderr,
(case File.write("README.md", readme) do
:ok -> "README.md updated"
{:error, reason} ->
"README.md: #{:file.explain_error(reason)}"
end)
end
end
| 24.196262 | 76 | 0.543453 |
e81a50525d8aad9e02e26f58ae5e615aa41972f4 | 705 | ex | Elixir | lib/hydra_web/gettext.ex | adrianomota/hydra | b72386467089d087cd3dc8f3106842ecb8e68ac3 | [
"MIT"
] | null | null | null | lib/hydra_web/gettext.ex | adrianomota/hydra | b72386467089d087cd3dc8f3106842ecb8e68ac3 | [
"MIT"
] | null | null | null | lib/hydra_web/gettext.ex | adrianomota/hydra | b72386467089d087cd3dc8f3106842ecb8e68ac3 | [
"MIT"
] | null | null | null | defmodule HydraWeb.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 HydraWeb.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: :hydra
end
| 28.2 | 72 | 0.675177 |
e81aa382e9dd530233dc5b29bf9a46725e31b7ea | 2,121 | exs | Elixir | test/live_beats_web/live/profile_live_test.exs | umair-akb/spotifyduo | f32517602c977ad1cf70eaf0e780d839f0ea85f6 | [
"MIT"
] | 547 | 2022-02-02T14:11:31.000Z | 2022-03-31T12:34:03.000Z | test/live_beats_web/live/profile_live_test.exs | umair-akb/spotifyduo | f32517602c977ad1cf70eaf0e780d839f0ea85f6 | [
"MIT"
] | 24 | 2022-02-02T14:11:36.000Z | 2022-02-23T20:14:43.000Z | test/live_beats_web/live/profile_live_test.exs | umair-akb/spotifyduo | f32517602c977ad1cf70eaf0e780d839f0ea85f6 | [
"MIT"
] | 63 | 2022-02-02T15:59:36.000Z | 2022-03-23T05:30:43.000Z | defmodule LiveBeatsWeb.ProfileLiveTest do
use LiveBeatsWeb.ConnCase
import Phoenix.LiveViewTest
import LiveBeats.AccountsFixtures
alias LiveBeats.MediaLibrary
alias LiveBeatsWeb.LiveHelpers
setup %{conn: conn} do
current_user = user_fixture(%{username: "chrismccord"})
user2 = user_fixture(%{username: "mrkurt"})
conn = log_in_user(conn, current_user)
{:ok, conn: conn, current_user: current_user, user2: user2}
end
describe "own profile" do
test "profile page uploads", %{conn: conn, current_user: current_user} do
profile = MediaLibrary.get_profile!(current_user)
{:ok, lv, dead_html} = live(conn, LiveHelpers.profile_path(current_user))
assert dead_html =~ "chrismccord's beats"
# uploads
assert lv
|> element("#upload-btn")
|> render_click()
assert render(lv) =~ "Add Music"
mp3 =
file_input(lv, "#song-form", :mp3, [
%{
last_modified: 1_594_171_879_000,
name: "my.mp3",
content: File.read!("test/support/fixtures/silence1s.mp3"),
type: "audio/mpeg"
}
])
assert render_upload(mp3, "my.mp3") =~ "can't be blank"
[%{"ref" => ref}] = mp3.entries
refute lv
|> form("#song-form")
|> render_change(%{
"_target" => ["songs", ref, "artist"],
"songs" => %{
ref => %{"artist" => "Anon", "attribution" => "", "title" => "silence1s"}
}
}) =~ "can't be blank"
assert lv |> form("#song-form") |> render_submit() =~ "silence1s"
assert_patch(lv, "/#{current_user.username}")
# deleting songs
song = MediaLibrary.get_first_song(profile)
assert lv |> element("#delete-modal-#{song.id}-confirm") |> render_click()
{:ok, refreshed_lv, _} = live(conn, LiveHelpers.profile_path(current_user))
refute render(refreshed_lv) =~ "silence1s"
end
test "invalid uploads" do
# TODO
end
end
describe "viewing other profiles" do
# TODO
end
end
| 28.28 | 90 | 0.585573 |
e81aaa6fcc0ad3031f4614b4adf0461d23924798 | 870 | ex | Elixir | lib/wow/jobs/icon_crawler.ex | DrPandemic/expressive-broker | 66a8da94ede2c101db9e1841e17898b5bae5df49 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | lib/wow/jobs/icon_crawler.ex | DrPandemic/expressive-broker | 66a8da94ede2c101db9e1841e17898b5bae5df49 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | lib/wow/jobs/icon_crawler.ex | DrPandemic/expressive-broker | 66a8da94ede2c101db9e1841e17898b5bae5df49 | [
"Apache-2.0",
"CC-BY-4.0",
"MIT"
] | null | null | null | defmodule Wow.Jobs.IconCrawler do
use Toniq.Worker, max_concurrency: 10
import Wow.Helpers, only: [with_logs: 1]
@base_url "https://render-us.worldofwarcraft.com/icons"
@extension ".jpg"
@spec perform([{:name, String.t} | {:size, String.t}]) :: :ok
def perform(name: name, size: size) do
with_logs(fn ->
IO.puts("Fetching #{size} #{name}")
Application.ensure_all_started :inets
client = Tesla.client([Tesla.Middleware.Compression])
case Tesla.get(
client,
"#{@base_url}/#{size}/#{name}#{@extension}"
) do
{:ok, %Tesla.Env{status: 200, body: body}} ->
File.write!("./assets/static/images/blizzard/icons/#{size}/#{name}#{@extension}", body)
something ->
IO.inspect(something)
end
IO.puts("Fetched #{size} #{name}")
:ok
end)
end
end
| 27.1875 | 97 | 0.590805 |
e81adabb95b23298124d82b2d982dfd4caec1b78 | 2,121 | ex | Elixir | lib/zstream/encryption_coder/traditional.ex | derrimahendra/zstream | 81a777af16c1657fc5b607d49dab8e520fa8c890 | [
"MIT"
] | null | null | null | lib/zstream/encryption_coder/traditional.ex | derrimahendra/zstream | 81a777af16c1657fc5b607d49dab8e520fa8c890 | [
"MIT"
] | null | null | null | lib/zstream/encryption_coder/traditional.ex | derrimahendra/zstream | 81a777af16c1657fc5b607d49dab8e520fa8c890 | [
"MIT"
] | null | null | null | defmodule Zstream.EncryptionCoder.Traditional do
@behaviour Zstream.EncryptionCoder
@moduledoc """
Implements the trandition encryption
"""
use Bitwise
defmodule State do
@moduledoc false
defstruct key0: 0x12345678,
key1: 0x23456789,
key2: 0x34567890,
header: nil,
header_sent: false
end
def init(options) do
password = Keyword.fetch!(options, :password)
header =
:crypto.strong_rand_bytes(10) <>
<<dos_time(Keyword.fetch!(options, :mtime))::little-size(16)>>
state = %State{header: header}
update_keys(state, password)
end
def encode(chunk, state) do
{chunk, state} =
if !state.header_sent do
{[state.header, chunk], %{state | header_sent: true}}
else
{chunk, state}
end
encrypt(state, IO.iodata_to_binary(chunk))
end
def close(_state) do
[]
end
def general_purpose_flag, do: 0x0001
defp encrypt(state, chunk), do: encrypt(state, chunk, [])
defp encrypt(state, <<>>, encrypted), do: {Enum.reverse(encrypted), state}
defp encrypt(state, <<char::binary-size(1)>> <> rest, encrypted) do
<<byte::integer-size(8)>> = char
temp = (state.key2 ||| 2) &&& 0x0000FFFF
temp = (temp * (temp ^^^ 1)) >>> 8 &&& 0x000000FF
cipher = <<byte ^^^ temp::integer-size(8)>>
state = update_keys(state, <<byte::integer-size(8)>>)
encrypt(state, rest, [cipher | encrypted])
end
defp update_keys(state, <<>>), do: state
defp update_keys(state, <<char::binary-size(1)>> <> rest) do
state = put_in(state.key0, crc32(state.key0, char))
state =
put_in(
state.key1,
(state.key1 + (state.key0 &&& 0x000000FF)) * 134_775_813 + 1 &&& 0xFFFFFFFF
)
state =
put_in(
state.key2,
crc32(state.key2, <<state.key1 >>> 24::integer-size(8)>>)
)
update_keys(state, rest)
end
defp crc32(current, data) do
:erlang.crc32(current ^^^ 0xFFFFFFFF, data) ^^^ 0xFFFFFFFF
end
defp dos_time(t) do
round(t.second / 2 + (t.minute <<< 5) + (t.hour <<< 11))
end
end
| 24.37931 | 83 | 0.602546 |
e81b465bba2546cad997cefab4dda7ce6d5c05dc | 797 | exs | Elixir | mix.exs | evnu/rusty | 3655002b1584e9203f2cf93f0209e09961ec7c16 | [
"Apache-2.0"
] | 1 | 2019-09-27T05:52:36.000Z | 2019-09-27T05:52:36.000Z | mix.exs | evnu/rusty | 3655002b1584e9203f2cf93f0209e09961ec7c16 | [
"Apache-2.0"
] | null | null | null | mix.exs | evnu/rusty | 3655002b1584e9203f2cf93f0209e09961ec7c16 | [
"Apache-2.0"
] | null | null | null | defmodule Rusty.Mixfile do
use Mix.Project
def project do
[
app: :rusty,
version: "0.1.0",
elixir: "~> 1.5",
start_permanent: Mix.env == :prod,
deps: deps(),
compilers: [:rustler] ++ Mix.compilers(),
rustler_crates: rustler_crates()
]
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
[
{:rustler, git: "https://github.com/hansihe/rustler", sparse: "rustler_mix"},
{:benchee, "~>0.11"},
{:propcheck, "~> 1.0", only: :test}
]
end
defp rustler_crates do
[
rusty: [
path: "native/rusty",
mode: :release
]
]
end
end
| 19.439024 | 83 | 0.558344 |
e81b6b435f2323baeb565dcf8e671e4c7eeb5173 | 1,213 | exs | Elixir | bench/witchcraft/semigroup/map_bench.exs | doma-engineering/witchcraft | c84fa6b2146e7de745105e21f672ed413df93ad3 | [
"MIT"
] | 454 | 2019-06-05T22:56:45.000Z | 2022-03-27T23:03:02.000Z | bench/witchcraft/semigroup/map_bench.exs | doma-engineering/witchcraft | c84fa6b2146e7de745105e21f672ed413df93ad3 | [
"MIT"
] | 26 | 2019-07-08T09:29:08.000Z | 2022-02-04T02:40:48.000Z | bench/witchcraft/semigroup/map_bench.exs | doma-engineering/witchcraft | c84fa6b2146e7de745105e21f672ed413df93ad3 | [
"MIT"
] | 36 | 2019-06-25T17:45:27.000Z | 2022-03-21T01:53:42.000Z | defmodule Witchcraft.Semigroup.MapBench do
use Benchfella
use Witchcraft.Semigroup
#########
# Setup #
#########
# ---------- #
# Data Types #
# ---------- #
@list_a 11..100 |> Enum.to_list() |> Enum.shuffle()
@list_b 99..999 |> Enum.to_list() |> Enum.shuffle()
@map_a @list_a |> Enum.zip(@list_b) |> Enum.into(%{})
@map_b @list_b |> Enum.zip(@list_a) |> Enum.into(%{})
#######
# Map #
#######
bench "Map.merge/2", do: Map.merge(@map_a, @map_b)
#############
# Semigroup #
#############
bench "append/2", do: append(@map_a, @map_b)
bench "repeat/2", do: repeat(@map_a, times: 100)
# --------- #
# Operators #
# --------- #
bench "<>/2", do: @map_a <> @map_b
# ---------- #
# Large Data #
# ---------- #
@big_list_a 0..100_000 |> Enum.to_list() |> Enum.shuffle()
@big_list_b 99..999_999 |> Enum.to_list() |> Enum.shuffle()
@big_map_a @big_list_a |> Enum.zip(@list_b) |> Enum.into(%{})
@big_map_b @big_list_b |> Enum.zip(@list_a) |> Enum.into(%{})
bench "$$$ Map.merge/2", do: Map.merge(@big_map_a, @big_map_b)
bench "$$$ append/2", do: append(@big_map_a, @big_map_b)
bench "$$$ <>/2", do: @big_map_a <> @big_map_b
end
| 22.886792 | 64 | 0.521022 |
e81b9c3c60665f7208ab1ead827675fcd7510cc9 | 11,552 | ex | Elixir | lib/nerves/artifact.ex | amclain/nerves | 054e9b378d33280a4cf2eb30937d6137e95d6acf | [
"Apache-2.0"
] | 1,944 | 2016-01-25T14:04:50.000Z | 2022-03-30T13:25:53.000Z | lib/nerves/artifact.ex | amclain/nerves | 054e9b378d33280a4cf2eb30937d6137e95d6acf | [
"Apache-2.0"
] | 397 | 2016-05-19T21:17:51.000Z | 2022-03-30T18:02:49.000Z | lib/nerves/artifact.ex | LaudateCorpus1/nerves | 2028efffc184cefb2616c49446828ef93c92db58 | [
"Apache-2.0"
] | 191 | 2016-01-30T01:56:25.000Z | 2022-03-30T17:58:57.000Z | defmodule Nerves.Artifact do
@moduledoc """
Package artifacts are the product of compiling a package with a
specific toolchain.
"""
alias Nerves.Artifact.{Cache, BuildRunners, Resolvers}
@checksum_short 7
@doc """
Builds the package and produces an See Nerves.Artifact
for more information.
"""
@spec build(Nerves.Package.t(), Nerves.Package.t()) :: :ok
def build(pkg, toolchain) do
case pkg.build_runner do
{build_runner, opts} ->
case build_runner.build(pkg, toolchain, opts) do
{:ok, path} ->
Cache.put(pkg, path)
{:error, error} ->
Mix.raise("""
Nerves encountered an error while constructing the artifact
#{error}
""")
end
:noop ->
:ok
end
end
@doc """
Produces an archive of the package artifact which can be fetched when
calling `nerves.artifact.get`.
"""
def archive(%{app: app, build_runner: nil}, _toolchain, _opts) do
Mix.raise("""
#{inspect(app)} does not declare a build_runner and therefore cannot
be used to produce an artifact archive.
""")
end
def archive(pkg, toolchain, opts) do
Mix.shell().info("Creating Artifact Archive")
opts = default_archive_opts(pkg, opts)
case pkg.build_runner do
{build_runner, _opts} ->
Code.ensure_compiled(pkg.platform)
{:ok, archive_path} = build_runner.archive(pkg, toolchain, opts)
archive_path = Path.expand(archive_path)
path =
opts[:path]
|> Path.expand()
|> Path.join(download_name(pkg) <> ext(pkg))
if path != archive_path do
File.cp!(archive_path, path)
end
{:ok, archive_path}
_ ->
Mix.shell().info("No build_runner specified for #{pkg.app}")
:noop
end
end
@doc """
Cleans the artifacts for the package build_runners of all packages.
"""
@spec clean(Nerves.Package.t()) :: :ok | {:error, term}
def clean(pkg) do
Mix.shell().info("Cleaning Nerves Package #{pkg.app}")
case pkg.build_runner do
{build_runner, _opts} ->
build_runner.clean(pkg)
_ ->
Mix.shell().info("No build_runner specified for #{pkg.app}")
:noop
end
end
@doc """
Determines if the artifact for a package is stale and needs to be rebuilt.
"""
@spec stale?(Nerves.Package.t()) :: boolean
def stale?(pkg) do
if env_var?(pkg) do
false
else
!Cache.valid?(pkg)
end
end
@doc """
Get the artifact name
"""
@spec name(Nerves.Package.t()) :: String.t()
def name(pkg) do
"#{pkg.app}-#{host_tuple(pkg)}-#{pkg.version}"
end
@doc """
Get the artifact download name
"""
@spec download_name(Nerves.Package.t()) :: String.t()
def download_name(pkg, opts \\ []) do
checksum_short = opts[:checksum_short] || @checksum_short
"#{pkg.app}-#{host_tuple(pkg)}-#{pkg.version}-#{checksum(pkg, short: checksum_short)}"
end
def parse_download_name(name) when is_binary(name) do
name = Regex.run(~r/(.*)-([^-]*)-(.*)-([^-]*)/, name)
case name do
[_, app, host_tuple, version, checksum] ->
{:ok,
%{
app: app,
host_tuple: host_tuple,
checksum: checksum,
version: version
}}
_ ->
{:error, "Unable to parse artifact name #{name}"}
end
end
@doc """
Get the base dir for where an artifact for a package should be stored.
The directory for artifacts will be found in the directory returned
by `Nerves.Env.data_dir/0` (i.e. `"#{Nerves.Env.data_dir()}/artifacts/"`).
This location can be overriden by the environment variable `NERVES_ARTIFACTS_DIR`.
"""
@spec base_dir() :: String.t()
def base_dir() do
System.get_env("NERVES_ARTIFACTS_DIR") || Path.join(Nerves.Env.data_dir(), "artifacts")
end
@doc """
Get the path to where the artifact is built
"""
def build_path(pkg) do
Path.join([pkg.path, ".nerves", "artifacts", name(pkg)])
end
@doc """
Get the path where the global artifact will be linked to.
This path is typically a location within build_path, but can be
vary on different build platforms.
"""
def build_path_link(pkg) do
case pkg.platform do
platform when is_atom(platform) ->
if :erlang.function_exported(platform, :build_path_link, 1) do
apply(platform, :build_path_link, [pkg])
else
build_path(pkg)
end
_ ->
build_path(pkg)
end
end
@doc """
Produce a base16 encoded checksum for the package from the list of files
and expanded folders listed in the checksum config key.
"""
@spec checksum(Nerves.Package.t()) :: String.t()
def checksum(pkg, opts \\ []) do
blob =
(pkg.config[:checksum] || [])
|> expand_paths(pkg.path)
|> Enum.map(&File.read!/1)
|> Enum.map(&:crypto.hash(:sha256, &1))
|> Enum.join()
checksum =
:crypto.hash(:sha256, blob)
|> Base.encode16()
case Keyword.get(opts, :short) do
nil ->
checksum
short_len ->
{checksum_short, _} = String.split_at(checksum, short_len)
checksum_short
end
end
@doc """
The full path to the artifact.
"""
@spec dir(Nerves.Package.t()) :: String.t()
def dir(pkg) do
if env_var?(pkg) do
System.get_env(env_var(pkg)) |> Path.expand()
else
base_dir()
|> Path.join(name(pkg))
end
end
@doc """
Check to see if the artifact path is being set from the system env.
"""
@spec env_var?(Nerves.Package.t()) :: boolean
def env_var?(pkg) do
name = env_var(pkg)
dir = System.get_env(name)
dir != nil and File.dir?(dir)
end
@doc """
Determine the environment variable which would be set to override the path.
"""
@spec env_var(Nerves.Package.t()) :: String.t()
def env_var(pkg) do
case pkg.type do
:toolchain ->
"NERVES_TOOLCHAIN"
:system ->
"NERVES_SYSTEM"
_ ->
pkg.app
|> Atom.to_string()
|> String.upcase()
end
end
@doc """
Expands the sites helpers from `artifact_sites` in the nerves_package config.
Artifact sites can pass options as a third parameter for adding headers
or query string parameters. For example, if you are trying to resolve
artifacts hosted in a private Github repo, use `:github_api` and
pass a user, tag, and personal access token into the sites helper:
```elixir
{:github_api, "owner/repo", username: "skroob", token: "1234567", tag: "v0.1.0"}
```
Or pass query parameters for the URL:
```elixir
{:prefix, "https://my-organization.com", query_params: %{"id" => "1234567", "token" => "abcd"}}
```
You can also use this to add an authorization header for files behind basic auth.
```elixir
{:prefix, "http://my-organization.com/", headers: [{"Authorization", "Basic " <> System.get_env("BASIC_AUTH")}}]}
```
"""
def expand_sites(pkg) do
case pkg.config[:artifact_url] do
nil ->
# |> Enum.map(&expand_site(&1, pkg))
# Check entire checksum length
# This code can be removed sometime after nerves 1.0
# and instead use the commented line above
Keyword.get(pkg.config, :artifact_sites, [])
|> Enum.reduce([], fn site, urls ->
[expand_site(site, pkg), expand_site(site, pkg, checksum_short: 64) | urls]
end)
urls when is_list(urls) ->
# artifact_url is deprecated and this code can be removed sometime following
# nerves 1.0
if Enum.any?(urls, &(!is_binary(&1))) do
Mix.raise("""
artifact_urls can only be strings.
Please use artifact_sites instead.
""")
end
urls
_invalid ->
Mix.raise("Invalid artifact_url. Please use artifact_sites instead")
end
end
@doc """
Get the path to where the artifact archive is downloaded to.
"""
def download_path(pkg) do
name = download_name(pkg) <> ext(pkg)
Nerves.Env.download_dir()
|> Path.join(name)
|> Path.expand()
end
@doc """
Get the host_tuple for the package. Toolchains are specifically build to run
on a host for a target. Other packages are host agnostic for now. They are
marked as `portable`.
"""
def host_tuple(%{type: :system}) do
"portable"
end
def host_tuple(_pkg) do
(Nerves.Env.host_os() <> "_" <> Nerves.Env.host_arch())
|> normalize_osx()
end
# Workaround for OTP 24 returning 'aarch64-apple-darwin20.4.0'
# and OTP 23 and earlier returning 'arm-apple-darwin20.4.0'.
#
# The current Nerves tooling naming uses "arm".
defp normalize_osx("darwin_aarch64"), do: "darwin_arm"
defp normalize_osx(other), do: other
@doc """
Determines the extension for an artifact based off its type.
Toolchains use xz compression.
"""
@spec ext(Nerves.Package.t()) :: String.t()
def ext(%{type: :toolchain}), do: ".tar.xz"
def ext(_), do: ".tar.gz"
def build_runner(config) do
opts = config[:nerves_package][:build_runner_opts] || []
mod =
config[:nerves_package][:build_runner] || build_runner_type(config[:nerves_package][:type])
{mod, opts}
end
defp build_runner_type(:system_platform), do: nil
defp build_runner_type(:toolchain_platform), do: nil
defp build_runner_type(:toolchain), do: BuildRunners.Local
defp build_runner_type(:system) do
case :os.type() do
{_, :linux} -> BuildRunners.Local
_ -> BuildRunners.Docker
end
end
defp build_runner_type(_), do: BuildRunners.Local
defp expand_paths(paths, dir) do
paths
|> Enum.map(&Path.join(dir, &1))
|> Enum.flat_map(&Path.wildcard/1)
|> Enum.flat_map(&dir_files/1)
|> Enum.map(&Path.expand/1)
|> Enum.filter(&File.regular?/1)
|> Enum.uniq()
end
defp dir_files(path) do
if File.dir?(path) do
Path.wildcard(Path.join(path, "**"))
else
[path]
end
end
defp default_archive_opts(pkg, opts) do
name = download_name(pkg) <> ext(pkg)
opts
|> Keyword.put_new(:name, name)
|> Keyword.put_new(:path, File.cwd!())
end
defp expand_site(_, _, _ \\ [])
defp expand_site({:github_releases, org_proj}, pkg, opts) do
expand_site(
{:prefix, "https://github.com/#{org_proj}/releases/download/v#{pkg.version}/"},
pkg,
opts
)
end
defp expand_site({:prefix, url}, pkg, opts) do
expand_site({:prefix, url, []}, pkg, opts)
end
defp expand_site({:prefix, path, resolver_opts}, pkg, opts) do
path = Path.join(path, download_name(pkg, opts) <> ext(pkg))
{Resolvers.URI, {path, resolver_opts}}
end
defp expand_site({:github_api, org_proj, resolver_opts}, pkg, opts) do
resolver_opts =
Keyword.put(resolver_opts, :artifact_name, download_name(pkg, opts) <> ext(pkg))
{Resolvers.GithubAPI, {org_proj, resolver_opts}}
end
defp expand_site(site, _pkg, _opts),
do:
Mix.raise("""
Unsupported artifact site
#{inspect(site)}
Supported artifact sites:
{:github_releases, "owner/repo"}
{:github_api, "owner/repo", username: "skroob", token: "1234567", tag: "v0.1.0"}
{:prefix, "http://myserver.com/artifacts"}
{:prefix, "http://myserver.com/artifacts", headers: [{"Authorization", "Basic: 1234567=="}]}
{:prefix, "http://myserver.com/artifacts", query_params: %{"id" => "1234567"}}
{:prefix, "file:///my_artifacts/"}
{:prefix, "/users/my_user/artifacts/"}
""")
end
| 27.053864 | 115 | 0.620499 |
e81b9d4e7cee63e2f64c801348e7d5f57b61d7dc | 24,539 | ex | Elixir | lib/ex_hl7.ex | workpathco/ex_hl7 | 20f2fadb158e903cf1752f69cd0ecdeae377c2c3 | [
"Apache-2.0"
] | null | null | null | lib/ex_hl7.ex | workpathco/ex_hl7 | 20f2fadb158e903cf1752f69cd0ecdeae377c2c3 | [
"Apache-2.0"
] | null | null | null | lib/ex_hl7.ex | workpathco/ex_hl7 | 20f2fadb158e903cf1752f69cd0ecdeae377c2c3 | [
"Apache-2.0"
] | null | null | null | defmodule HL7 do
@moduledoc """
Main module of the **ex_hl7** library.
"""
alias HL7.{Codec, Message, Reader, Segment, Type, Writer}
@type segment_id :: Type.segment_id()
@type sequence :: Type.sequence()
@type composite_id :: Type.composite_id()
@type field :: Type.field()
@type item_type :: Type.item_type()
@type value_type :: Type.value_type()
@type value :: Type.value()
@type repetition :: Type.repetition()
@type read_option :: Reader.option()
@type write_option :: Writer.option()
@type read_ret ::
{:ok, Message.t()}
| {:incomplete, {(binary -> read_ret), rest :: binary}}
| {:error, reason :: any}
@doc """
Reads a binary containing an HL7 message converting it to a list of segments.
## Arguments
* `buffer`: a binary containing the HL7 message to be parsed (partial
messages are allowed).
* `options`: keyword list with the read options; these are:
* `input_format`: the format the message in the `buffer` is in; it can be
either `:wire` for the normal HL7 wire format with carriage-returns as
segment terminators or `:text` for a format that replaces segment
terminators with line feeds to easily output messages to a console or
text file.
* `segment_creator`: function that receives a segment ID and returns a
tuple containing the module and the struct corresponding to the given
segment ID. By default, `&HL7.Segment.new/1` is used.
* `trim`: boolean that when set to `true` causes the fields to be
shortened to their optimal layout, removing trailing empty items (see
`HL7.Codec` for an explanation of this).
## Return values
Returns the parsed message (i.e. list of segments) or raises an
`HL7.ReadError` exception in case of error.
## Examples
Given an HL7 message like the following bound to the `buffer` variable:
"MSH|^~\\&|CLIENTHL7|CLI01020304|SERVHL7|PREPAGA^112233^IIN|20120201101155||ZQA^Z02^ZQA_Z02|00XX20120201101155|P|2.4|||ER|SU|ARG\\r" <>
"PRD|PS~4600^^HL70454||^^^B||||30123456789^CU\\r" <>
"PID|0||1234567890ABC^^^&112233&IIN^HC||unknown\\r" <>
"PR1|1||903401^^99DH\\r" <>
"AUT||112233||||||1|0\\r" <>
"PR1|2||904620^^99DH\\r" <>
"AUT||112233||||||1|0\\r"
You could read the message in the following way:
iex> message = HL7.read!(buffer, input_format: :wire, trim: true)
"""
@spec read!(buffer :: binary, [read_option()]) :: Message.t() | no_return
def read!(buffer, options \\ []), do: Message.read!(Reader.new(options), buffer)
@doc """
Reads a binary containing an HL7 message converting it to a list of segments.
## Arguments
* `buffer`: a binary containing the HL7 message to be parsed (partial
messages are allowed).
* `options`: keyword list with the read options; these are:
* `input_format`: the format the message in the `buffer` is in; it can be
either `:wire` for the normal HL7 wire format with carriage-returns as
segment terminators or `:text` for a format that replaces segment
terminators with line feeds to easily output messages to a console or
text file.
* `segment_creator`: function that receives a segment ID and returns a
tuple containing the module and the struct corresponding to the given
segment ID. By default, `&HL7.Segment.new/1` is used.
* `trim`: boolean that when set to `true` causes the fields to be
shortened to their optimal layout, removing trailing empty items (see
`HL7.Codec` for an explanation of this).
## Return values
* `{:ok, HL7.message}` if the buffer could be parsed successfully, then
a message will be returned. This is actually a list of `HL7.segment`
structs (check the [segment.ex](lib/ex_hl7/segment.ex) file to see the
list of included segment definitions).
* `{:incomplete, {(binary -> read_ret), rest :: binary}}` if the message
in the string is not a complete HL7 message, then a function will be
returned together with the part of the message that could not be parsed.
You should acquire the remaining part of the message and concatenate it
to the `rest` of the previous buffer. Finally, you have to call the
function that was returned passing it the concatenated string.
* `{:error, reason :: any}` if the contents of the buffer were malformed
and could not be parsed correctly.
## Examples
Given an HL7 message like the following bound to the `buffer` variable:
"MSH|^~\\&|CLIENTHL7|CLI01020304|SERVHL7|PREPAGA^112233^IIN|20120201101155||ZQA^Z02^ZQA_Z02|00XX20120201101155|P|2.4|||ER|SU|ARG\\r" <>
"PRD|PS~4600^^HL70454||^^^B||||30123456789^CU\\r" <>
"PID|0||1234567890ABC^^^&112233&IIN^HC||unknown\\r" <>
"PR1|1||903401^^99DH\\r" <>
"AUT||112233||||||1|0\\r" <>
"PR1|2||904620^^99DH\\r" <>
"AUT||112233||||||1|0\\r"
You could read the message in the following way:
iex> {:ok, message} = HL7.read(buffer, input_format: :wire, trim: true)
"""
@spec read(buffer :: binary, [read_option()]) :: read_ret()
def read(buffer, options \\ []), do: Message.read(Reader.new(options), buffer)
@doc """
Writes a list of HL7 segments into an iolist.
## Arguments
* `message`: a list of HL7 segments to be written into the string.
* `options`: keyword list with the write options; these are:
* `output_format`: the format the message will be written in; it can be
either `:wire` for the normal HL7 wire format with carriage-returns as
segment terminators or `:text` for a format that replaces segment
terminators with line feeds to easily output messages to a console or
text file. Defaults to `:wire`.
* `separators`: a tuple containing the item separators to be used when
generating the message as returned by `HL7.Codec.set_separators/1`.
Defaults to `HL7.Codec.separators`.
* `trim`: boolean that when set to `true` causes the fields to be
shortened to their optimal layout, removing trailing empty items (see
`HL7.Codec` for an explanation of this). Defaults to `true`.
## Return value
iolist containing the message in the selected output format.
## Examples
Given the `message` parsed in the `HL7.read/2` example you could do:
iex> buffer = HL7.write(message, output_format: :text, trim: true)
iex> IO.puts(buffer)
MSH|^~\\&|CLIENTHL7|CLI01020304|SERVHL7|PREPAGA^112233^IIN|20120201101155||ZQA^Z02^ZQA_Z02|00XX20120201101155|P|2.4|||ER|SU|ARG
PRD|PS~4600^^HL70454||^^^B||||30123456789^CU
PID|0||1234567890ABC^^^&112233&IIN^HC||unknown
PR1|1||903401^^99DH
AUT||112233||||||1|0
PR1|2||904620^^99DH
AUT||112233||||||1|0
"""
@spec write(Message.t(), [write_option()]) :: iodata
def write(message, options \\ []), do: Message.write(Writer.new(options), message)
@doc """
Retrieve the segment ID from a segment.
## Return value
If the argument is an `HL7.segment` the function returns a binary with the
segment ID; otherwise it returns `nil`.
## Examples
iex> aut = HL7.segment(message, "AUT")
iex> "AUT" = HL7.segment_id(aut)
"""
@spec segment_id(Segment.t()) :: segment_id()
defdelegate segment_id(segment), to: Segment, as: :id
@doc """
Return the first repetition of a segment within a message.
## Return value
If a segment with the passed `segment_id` can be found in the `message`
then the function returns the segment; otherwise it returns `nil`.
## Examples
iex> pr1 = HL7.segment(message, "PR1")
iex> 1 = pr1.set_id
"""
@spec segment(Message.t(), segment_id()) :: Segment.t() | nil
defdelegate segment(message, segment_id), to: Message
@doc """
Return the nth repetition (0-based) of a segment within a message.
## Return value
If the corresponding `repetition` of a segment with the passed `segment_id`
is present in the `message` then the function returns the segment; otherwise
it returns `nil`.
## Examples
iex> pr1 = HL7.segment(message, "PR1", 0)
iex> 1 = pr1.set_id
iex> pr1 = HL7.segment(message, "PR1", 1)
iex> 2 = pr1.set_id
"""
@spec segment(Message.t(), segment_id(), repetition()) :: Segment.t() | nil
defdelegate segment(message, segment_id, repetition), to: Message
@doc """
Return the first grouping of segments with the specified segment IDs.
In HL7 messages sometimes some segments are immediately followed by other
segments within the message. This function was created to help find those
"grouped segments".
For example, the `PR1` segment is sometimes followed by some other segments
(e.g. `OBX`, `AUT`, etc.) to include observations and other related
information for a practice. Note that there might be multiple segment
groupings in a message.
## Return value
A list of segments corresponding to the segment IDs that were passed. The
list might not include all of the requested segments if they were not
present in the message. The function will stop as soon as it finds a segment
that does not belong to the passed sequence.
## Examples
iex> [pr1, aut] = HL7.paired_segments(message, ["PR1", "AUT"])
"""
@spec paired_segments(Message.t(), [segment_id()]) :: [Segment.t()]
defdelegate paired_segments(message, segment_ids), to: Message
@doc """
Return the nth (0-based) grouping of segments with the specified segment IDs.
In HL7 messages sometimes some segments are immediately followed by other
segments within the message. This function was created to help find those
"grouped segments".
For example, the `PR1` segment is sometimes followed by some other segments
(e.g. `OBX`, `AUT`, etc.) to include observations and other related
information for a practice. Note that there might be multiple segment
groupings in a message.
## Return value
A list of segments corresponding to the segment IDs that were passed. The
list might not include all of the requested segments if they were not
present in the message. The function will stop as soon as it finds a segment
that does not belong to the passed sequence.
## Examples
iex> [pr1, aut] = HL7.paired_segments(message, ["PR1", "AUT"], 0)
iex> [pr1, aut] = HL7.paired_segments(message, ["PR1", "AUT"], 1)
iex> [] = HL7.paired_segments(message, ["PR1", "AUT"], 2)
iex> [aut] = HL7.paired_segments(message, ["PR1", "OBX"], 1)
"""
@spec paired_segments(Message.t(), [segment_id()], repetition()) :: [Segment.t()]
defdelegate paired_segments(message, segment_ids, repetition), to: Message
@doc """
It skips over the first `repetition` groups of paired segment and invokes
`fun` for each subsequent group of paired segments in the `message`. It
passes the following arguments to `fun` on each call:
- list of segments found that correspond to the group.
- index of the group of segments in the `message` (0-based).
- accumulator `acc` with the incremental results returned by `fun`.
In HL7 messages sometimes some segments are immediately followed by other
segments within the message. This function was created to easily process
those "paired segments".
For example, the `PR1` segment is sometimes followed by some other segments
(e.g. `OBX`, `AUT`, etc.) to include observations and other related
information for a procedure. Note that there might be multiple segment
groupings in a message.
## Arguments
* `message`: list of segments containing a decoded HL7 message.
* `segment_ids`: list of segment IDs that define the group of segments to
retrieve.
* `repetition`: index of the group of segments to retrieve (0-based); it also
corresponds to the number of groups to skip.
* `acc`: term containing the initial value of the accumulator to be passed to
the `fun` callback.
* `fun`: callback function receiving a group of segments, the index of the
group in the message and the accumulator.
## Return value
The accumulator returned by `fun` in its last invocation.
## Examples
iex> HL7.reduce_paired_segments(message, ["PR1", "AUT"], 0, [], fun segments, index, acc ->
segment_ids = for segment <- segments, do: HL7.segment_id(segment)
[{index, segment_ids} | acc]
end
[{0, ["PR1", "AUT"]}, {1, ["PR1", "AUT"]}]
"""
@spec reduce_paired_segments(
Message.t(),
[segment_id()],
repetition(),
acc :: term,
([Segment.t()], repetition(), acc :: term -> acc :: term)
) :: acc :: term
defdelegate reduce_paired_segments(message, segment_ids, repetition, acc, fun), to: Message
@doc """
Return the number of segments with a specified segment ID in an HL7 message.
## Examples
iex> 2 = HL7.segment_count(message, "PR1")
iex> 0 = HL7.segment_count(message, "OBX")
"""
@spec segment_count(Message.t(), segment_id()) :: non_neg_integer
defdelegate segment_count(message, segment_id), to: Message
@doc """
Deletes the first repetition of a segment in a message
## Examples
iex> HL7.delete(message, "NTE")
"""
@spec delete(Message.t(), segment_id()) :: Message.t()
defdelegate delete(message, segment_id), to: Message
@doc """
Deletes the given repetition (0-based) of a segment in a message
## Examples
iex> HL7.delete(message, "NTE", 0)
"""
@spec delete(Message.t(), segment_id(), repetition()) :: Message.t()
defdelegate delete(message, segment_id, repetition), to: Message
@doc """
Inserts a segment or group of segments before the first repetition of an
existing segment in a message.
## Arguments
* `message`: the `HL7.message` where the segment/s will be inserted.
* `segment_id`: the segment ID of a segment that should be present in the
`message`.
* `segment`: the segment or list of segments that will be inserted
## Return values
If a segment with the `segment_id` was present, the function will return a
new message with the inserted segments. If not, it will return the original
message
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.insert_before(message, "ERR", msa)
"""
@spec insert_before(Message.t(), segment_id(), Segment.t() | [Segment.t()]) :: Message.t()
defdelegate insert_before(message, segment_id, segment), to: Message
@doc """
Inserts a segment or group of segments before the given repetition of an
existing segment in a message.
## Arguments
* `message`: the `HL7.message` where the segment/s will be inserted.
* `segment_id`: the segment ID of a segment that should be present in the
`message`.
* `repetition`: the repetition (0-based) of the `segment_id` in the `message`.
* `segment`: the segment or list of segments that will be inserted
## Return values
If a segment with the `segment_id` was present with the given `repetition`,
the function will return a new message with the inserted segments. If not,
it will return the original message
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.insert_before(message, "ERR", 0, msa)
"""
@spec insert_before(Message.t(), segment_id(), repetition(), Segment.t() | [Segment.t()]) ::
Message.t()
defdelegate insert_before(message, segment_id, repetition, segment), to: Message
@doc """
Inserts a segment or group of segments after the first repetition of an
existing segment in a message.
## Arguments
* `message`: the `HL7.message` where the segment/s will be inserted.
* `segment_id`: the segment ID of a segment that should be present in the
`message`.
* `segment`: the segment or list of segments that will be inserted
## Return values
If a segment with the `segment_id` was present, the function will return a
new message with the inserted segments. If not, it will return the original
message
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.insert_after(message, "MSH", msa)
"""
@spec insert_after(Message.t(), segment_id(), Segment.t() | [Segment.t()]) :: Message.t()
defdelegate insert_after(message, segment_id, segment), to: Message
@doc """
Inserts a segment or group of segments after the given repetition of an
existing segment in a message.
## Arguments
* `message`: the `HL7.message` where the segment/s will be inserted.
* `segment_id`: the segment ID of a segment that should be present in the
`message`.
* `repetition`: the repetition (0-based) of the `segment_id` in the `message`.
* `segment`: the segment or list of segments that will be inserted
## Return values
If a segment with the `segment_id` was present with the given `repetition`,
the function will return a new message with the inserted segments. If not,
it will return the original message
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.insert_after(message, "MSH", 0, msa)
"""
@spec insert_after(Message.t(), segment_id(), repetition(), Segment.t() | [Segment.t()]) :: Message.t()
defdelegate insert_after(message, segment_id, repetition, segment), to: Message
@doc """
Appends a segment or segments onto the end of a message
## Arguments
* `message`: the `HL7.message` where the segment/s will be appended.
* `segment`: the segment or list of segments that will be appended
## Return values
Return a new message with the appended segments.
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.Message.append(message, msa)
"""
@spec append(Message.t(), Segment.t() | [Segment.t()]) :: Message.t()
defdelegate append(message, segment), to: Message
@doc """
Replaces the first repetition of an existing segment in a message.
## Arguments
* `message`: the `HL7.message` where the segment/s will be inserted.
* `segment_id`: the segment ID of a segment that should be present in the
`message`.
* `segment`: the segment or list of segments that will replace the existing
one.
## Return values
If a segment with the `segment_id` was present, the function will return a
new message with the replaced segments. If not, it will return the original
message
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.replace(message, "MSA", msa)
"""
@spec replace(Message.t(), segment_id(), Segment.t()) :: Message.t()
defdelegate replace(message, segment_id, segment), to: Message
@doc """
Replaces the given repetition of an existing segment in a message.
## Arguments
* `message`: the `HL7.message` where the segment/s will be inserted.
* `segment_id`: the segment ID of a segment that should be present in the
`message`.
* `repetition`: the repetition (0-based) of the `segment_id` in the `message`.
* `segment`: the segment or list of segments that will replace the existing
one.
## Return values
If a segment with the `segment_id` was present with the given `repetition`,
the function will return a new message with the replaced segments. If not,
it will return the original message.
## Examples
iex> alias HL7.Segment.MSA
iex> ack = %MSA{ack_code: "AA", message_control_id: "1234"}
iex> HL7.replace(message, "MSA", 0, msa)
"""
@spec replace(Message.t(), segment_id(), repetition(), Segment.t()) :: Message.t()
defdelegate replace(message, segment_id, repetition, segment), to: Message
@doc """
Escape a string that may contain separators using the HL7 escaping rules.
## Arguments
* `value`: a string to escape; it may or may not contain separator
characters.
* `options`: keyword list with the escape options; these are:
* `separators`: a tuple containing the item separators to be used when
generating the message as returned by `HL7.Codec.set_separators/1`.
Defaults to `HL7.Codec.separators`.
* `escape_char`: character to be used as escape delimiter. Defaults to `?\\\\ `
(backlash).
## Examples
iex> "ABCDEF" = HL7.escape("ABCDEF")
iex> "ABC\\\\F\\\\DEF\\\\F\\\\GHI" = HL7.escape("ABC|DEF|GHI", separators: HL7.Codec.separators())
"""
@spec escape(binary, options :: Keyword.t()) :: binary
def escape(value, options \\ []) do
separators = Keyword.get(options, :separators, Codec.separators())
escape_char = Keyword.get(options, :escape_char, ?\\)
Codec.escape(value, separators, escape_char)
end
@doc """
Convert an escaped string into its original value.
## Arguments
* `value`: a string to unescape; it may or may not contain escaped characters.
* `options`: keyword list with the escape options; these are:
* `separators`: a tuple containing the item separators to be used when
generating the message as returned by `HL7.Codec.set_separators/1`.
Defaults to `HL7.Codec.separators`.
* `escape_char`: character to be used as escape delimiter. Defaults to `?\\\\ `
(backlash).
## Examples
iex> "ABCDEF" = HL7.unescape("ABCDEF")
iex> "ABC|DEF|GHI" = HL7.unescape("ABC\\\\F\\\\DEF\\\\F\\\\GHI", escape_char: ?\\)
"""
@spec unescape(binary, options :: Keyword.t()) :: binary
def unescape(value, options \\ []) do
separators = Keyword.get(options, :separators, Codec.separators())
escape_char = Keyword.get(options, :escape_char, ?\\)
Codec.unescape(value, separators, escape_char)
end
@vertical_tab 0x0b
@file_separator 0x1c
@carriage_return 0x0d
@doc """
Add MLLP framing to an already encoded HL7 message.
An MLLP-framed message carries a one byte vertical tab (0x0b) control code
as header and a two byte trailer consisting of a file separator (0x1c) and
a carriage return (0x0d) control code.
## Arguments
* `buffer`: binary or iolist containing an encoded HL7 message as returned
by `HL7.write/2`.
"""
@spec to_mllp(buffer :: iodata) :: iolist
def to_mllp(buffer) when is_binary(buffer) or is_list(buffer) do
[@vertical_tab, buffer, @file_separator, @carriage_return]
end
@doc """
Remove MLLP framing from an already encoded HL7 message.
An MLLP-framed message carries a one byte vertical tab (0x0b) control code
as header and a two byte trailer consisting of a file separator (0x1c) and
a carriage return (0x0d) control code.
## Arguments
* `buffer`: binary or iolist containing an MLLP-framed HL7 message as
returned by `HL7.to_mllp/1`.
## Return value
Returns the encoded message with the MLLP framing removed.
"""
@spec from_mllp(buffer :: iodata) ::
{:ok, msg_buffer :: iodata} | :incomplete | {:error, reason :: term}
def from_mllp([@vertical_tab, msg_buffer, @file_separator, @carriage_return]) do
{:ok, msg_buffer}
end
def from_mllp([@vertical_tab | tail]) do
case Enum.reverse(tail) do
[@carriage_return, @file_separator | msg_iolist] ->
{:ok, Enum.reverse(msg_iolist)}
_ ->
:incomplete
end
end
def from_mllp(buffer) when is_binary(buffer) do
msg_len = byte_size(buffer) - 3
case buffer do
<<@vertical_tab, msg_buffer::binary-size(msg_len), @file_separator, @carriage_return>>
when msg_len > 0 ->
{:ok, msg_buffer}
<<@vertical_tab, _tail::binary>> ->
:incomplete
_ ->
{:error, :bad_mllp_framing}
end
end
@doc """
Remove MLLP framing from an already encoded HL7 message.
An MLLP-framed message carries a one byte vertical tab (0x0b) control code
as header and a two byte trailer consisting of a file separator (0x1c) and
a carriage return (0x0d) control code.
## Arguments
* `buffer`: binary or iolist containing an MLLP-framed HL7 message as
returned by `HL7.to_mllp/1`.
## Return value
Returns the encoded message with the MLLP framing removed or raises an
`HL7.ReadError` exception in case of error.
"""
@spec from_mllp!(buffer :: iodata) :: msg_buffer :: iodata | no_return
def from_mllp!(buffer) do
case from_mllp(buffer) do
{:ok, msg_buffer} -> msg_buffer
:incomplete -> raise HL7.ReadError, :incomplete
{:error, reason} -> raise HL7.ReadError, reason
end
end
end
| 33.753783 | 141 | 0.680875 |
e81ba05f5c80c48ad0eb9b1b091485e69e27748b | 954 | ex | Elixir | test/support/channel_case.ex | shawnonthenet/mathmatical | d0f8d9e77dc71edfdc88776daca973fcd9cd106b | [
"Apache-2.0"
] | null | null | null | test/support/channel_case.ex | shawnonthenet/mathmatical | d0f8d9e77dc71edfdc88776daca973fcd9cd106b | [
"Apache-2.0"
] | null | null | null | test/support/channel_case.ex | shawnonthenet/mathmatical | d0f8d9e77dc71edfdc88776daca973fcd9cd106b | [
"Apache-2.0"
] | null | null | null | defmodule MathmaticalWeb.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 MathmaticalWeb.Endpoint
end
end
setup tags do
:ok = Ecto.Adapters.SQL.Sandbox.checkout(Mathmatical.Repo)
unless tags[:async] do
Ecto.Adapters.SQL.Sandbox.mode(Mathmatical.Repo, {:shared, self()})
end
:ok
end
end
| 25.105263 | 73 | 0.720126 |
e81bad1c7c4ce11f3b5ffcd205e756edb5e64942 | 4,489 | ex | Elixir | lib/xmlmetaprogramming.ex | dkuhlman/xmlelixirstructs | 466b7c163703a1a8b9eb4553e3e3f7cf0404e53d | [
"BSD-3-Clause"
] | 1 | 2020-01-27T11:30:32.000Z | 2020-01-27T11:30:32.000Z | lib/xmlmetaprogramming.ex | dkuhlman/xmlelixirstructs | 466b7c163703a1a8b9eb4553e3e3f7cf0404e53d | [
"BSD-3-Clause"
] | null | null | null | lib/xmlmetaprogramming.ex | dkuhlman/xmlelixirstructs | 466b7c163703a1a8b9eb4553e3e3f7cf0404e53d | [
"BSD-3-Clause"
] | null | null | null | defmodule XmerlAccess do
@moduledoc """
Use Elixir meta-programming to generate test and accessor functions.
For each Xmerl record type generate the following:
- A test function, e.g. `is_element/1`, `is_attribute/1`, etc.
- A set of assessor functions, one for each field, e.g. `get_element_name/1`,
`get_element_attributes/1`, ..., `get_attribute_name/1`, etc.
"""
require XmerlRecs
@record_types ["element", "attribute", "text", "namespace", "comment"]
@record_types
|> Enum.each(fn record_type_str ->
record_type_string = "xml#{String.capitalize(record_type_str)}"
record_type_atom = String.to_atom(record_type_string)
is_method_name_str = "is_#{record_type_str}"
is_method_name_atom = String.to_atom(is_method_name_str)
is_method_body_str = """
if is_tuple(item) and tuple_size(item) > 0 do
case elem(item, 0) do
:#{record_type_string} -> true
_ -> false
end
else
false
end
"""
{:ok, is_method_body_ast} = Code.string_to_quoted(is_method_body_str)
def unquote(is_method_name_atom) (item) do
unquote(is_method_body_ast)
end
Record.extract(record_type_atom, from_lib: "xmerl/include/xmerl.hrl")
|> Enum.each(fn {field_name_atom, _} ->
method_name_str = "get_#{record_type_str}_#{to_string(field_name_atom)}"
method_name_atom = String.to_atom(method_name_str)
method_body_str = "XmerlRecs.#{to_string(record_type_atom)}(item, :#{to_string(field_name_atom)})"
{:ok, method_body_ast} = Code.string_to_quoted(method_body_str)
def unquote(method_name_atom)(item) do
unquote(method_body_ast)
end
end)
end)
end
defmodule TestMetaprogramming do
@moduledoc """
Test functions for metaprogramming generated Xmerl access functions
"""
require XmerlAccess
require XmerlRecs
@doc """
Walk and show the tree of XML elements.
## Examples
iex> rec = File.stream!("Data/test02.xml") |> SweetXml.parse
iex> Test22.show_tree(rec)
"""
@spec show_tree(Tuple.t(), String.t()) :: nil
def show_tree(rec, init_filler \\ "", add_filler \\ " ") do
IO.puts("#{init_filler}element name: #{XmerlAccess.get_element_name(rec)}")
Enum.each(XmerlAccess.get_element_attributes(rec), fn attr ->
name = XmerlAccess.get_attribute_name(attr)
value = XmerlAccess.get_attribute_value(attr)
IO.puts("#{init_filler} attribute -- name: #{name} value: #{value}")
end)
Enum.each(XmerlAccess.get_element_content(rec), fn item ->
filler1 = init_filler <> add_filler
case elem(item, 0) do
:xmlElement ->
show_tree(item, filler1, add_filler)
nil
_ -> nil
end
end)
nil
end
@doc """
Show some infomation in the element tree using Elixir Xmerl records.
## Examples
iex> record = File.stream!("path/to/my/doc.xml") |> SweetXml.parse
iex> TestMetaprogramming.demo1 record
"""
@spec demo1(Tuple.t()) :: :ok
def demo1 element do
name = XmerlRecs.xmlElement(element, :name)
IO.puts("element name: #{name}")
XmerlRecs.xmlElement(element, :attributes)
|> Enum.each(fn attr ->
attrname = XmerlRecs.xmlAttribute(attr, :name)
attrvalue = XmerlRecs.xmlAttribute(attr, :value)
IO.puts(" attribute -- name: #{attrname} value: #{attrvalue}")
end)
XmerlRecs.xmlElement(element, :content)
|> Enum.each(fn item ->
case elem(item, 0) do
:xmlText ->
IO.puts(" text -- value: #{XmerlRecs.xmlText(item, :value)}")
_ -> nil
end
end)
end
@doc """
Show some infomation in element tree using functions created with meta-programming.
## Examples
iex> record = File.stream!("path/to/my/doc.xml") |> SweetXml.parse
iex> TestMetaprogramming.demo2 record
"""
@spec demo2(Tuple.t()) :: :ok
def demo2 element do
name = Xml.Element.get_name(element)
IO.puts("element name: #{name}")
Xml.Element.get_attributes(element)
|> Enum.each(fn attr ->
attrname = XmerlRecs.xmlAttribute(attr, :name)
attrvalue = XmerlRecs.xmlAttribute(attr, :value)
IO.puts(" attribute -- name: #{attrname} value: #{attrvalue}")
end)
Xml.Element.get_content(element)
|> Enum.each(fn item ->
case elem(item, 0) do
:xmlText ->
IO.puts(" text -- value: #{Xml.Text.get_value(item)}")
_ -> nil
end
end)
end
end
| 30.127517 | 104 | 0.648474 |
e81bc99ebb5589222310c7f7ae269f712a4b0567 | 2,898 | exs | Elixir | apps/sherbet_api/test/sherbet.api.contact/email_test.exs | ScrimpyCat/sherbet | f245c994b15c47bb31b68d5af24de925c853c3d7 | [
"BSD-2-Clause"
] | 3 | 2017-05-02T12:52:54.000Z | 2017-05-28T11:53:17.000Z | apps/sherbet_api/test/sherbet.api.contact/email_test.exs | ScrimpyCat/sherbet | f245c994b15c47bb31b68d5af24de925c853c3d7 | [
"BSD-2-Clause"
] | null | null | null | apps/sherbet_api/test/sherbet.api.contact/email_test.exs | ScrimpyCat/sherbet | f245c994b15c47bb31b68d5af24de925c853c3d7 | [
"BSD-2-Clause"
] | 2 | 2017-05-02T13:13:25.000Z | 2019-10-24T11:55:39.000Z | defmodule Sherbet.API.Contact.EmailTest do
use Sherbet.Service.Case
alias Sherbet.API.Contact.Email
setup do
{ :ok, %{ identity: Ecto.UUID.generate() } }
end
test "associate email with identity", %{ identity: identity } do
assert { :ok, false } == Email.contact?(identity, "foo@foo")
assert :ok == Email.add(identity, "foo@foo")
assert { :ok, [{ :unverified, :secondary, "foo@foo" }] } == Email.contacts(identity)
assert { :ok, false } == Email.verified?(identity, "foo@foo")
assert { :ok, true } == Email.contact?(identity, "foo@foo")
assert { :ok, identity } == Email.owner("foo@foo")
end
test "remove email from identity", %{ identity: identity } do
:ok = Email.add(identity, "foo@foo")
assert :ok == Email.remove(identity, "foo@foo")
assert { :ok, [] } == Email.contacts(identity)
end
test "remove unverified email per request with valid key", %{ identity: identity } do
:ok = Email.add(identity, "foo@foo")
assert :ok == Email.request_removal("foo@foo")
query = from removal in Sherbet.Service.Contact.Communication.Method.Email.RemovalKey.Model,
join: contact in Sherbet.Service.Contact.Communication.Method.Email.Model, on: contact.id == removal.email_id and contact.email == "foo@foo",
select: removal.key
key = Sherbet.Service.Repo.one!(query)
assert :ok == Email.finalise_removal("foo@foo", key)
assert { :ok, [] } == Email.contacts(identity)
end
test "verify unverified email per request for identity with valid key", %{ identity: identity } do
:ok = Email.add(identity, "foo@foo")
assert :ok == Email.request_verification(identity, "foo@foo")
query = from verification in Sherbet.Service.Contact.Communication.Method.Email.VerificationKey.Model,
join: contact in Sherbet.Service.Contact.Communication.Method.Email.Model, on: contact.id == verification.email_id and contact.email == "foo@foo",
select: verification.key
key = Sherbet.Service.Repo.one!(query)
assert :ok == Email.finalise_verification(identity, "foo@foo", key)
assert { :ok, [{ :verified, :secondary, "foo@foo" }] } == Email.contacts(identity)
assert { :ok, true } == Email.verified?(identity, "foo@foo")
end
test "setting email priority", %{ identity: identity } do
:ok = Email.add(identity, "foo@foo", :primary)
assert { :ok, { :unverified, "foo@foo" } } == Email.primary_contact(identity)
assert :ok == Email.add(identity, "foo@foo2")
assert { :ok, { :unverified, "foo@foo" } } == Email.primary_contact(identity)
assert :ok == Email.set_priority(identity, "foo@foo2", :primary)
assert { :ok, { :unverified, "foo@foo2" } } == Email.primary_contact(identity)
end
end
| 42.617647 | 158 | 0.6294 |
e81bcbc1d3e86da3b7b4bc99673e3c1a70448a65 | 1,185 | ex | Elixir | lib/csv_uploader_web/channels/user_socket.ex | jolyus/csv-uploader | ca29234a4b1bf1ab3f0760099b1bcd4f9aa8c354 | [
"MIT"
] | null | null | null | lib/csv_uploader_web/channels/user_socket.ex | jolyus/csv-uploader | ca29234a4b1bf1ab3f0760099b1bcd4f9aa8c354 | [
"MIT"
] | null | null | null | lib/csv_uploader_web/channels/user_socket.ex | jolyus/csv-uploader | ca29234a4b1bf1ab3f0760099b1bcd4f9aa8c354 | [
"MIT"
] | null | null | null | defmodule CsvUploaderWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", CsvUploaderWeb.RoomChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# CsvUploaderWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 31.184211 | 86 | 0.706329 |
e81bef9de19be241ef9075dfc707d60f2808f219 | 1,011 | exs | Elixir | test/cli_test.exs | erikvullings/issues | ccfc7086891b2fd793a519996a9a2eb7ca29dbb0 | [
"MIT"
] | null | null | null | test/cli_test.exs | erikvullings/issues | ccfc7086891b2fd793a519996a9a2eb7ca29dbb0 | [
"MIT"
] | null | null | null | test/cli_test.exs | erikvullings/issues | ccfc7086891b2fd793a519996a9a2eb7ca29dbb0 | [
"MIT"
] | null | null | null | defmodule CliTest do
use ExUnit.Case
import Issues.CLI, only: [
parse_args: 1,
sort_into_ascending_order: 1,
convert_to_list_of_hashdicts: 1
]
test ":help returned by option parsing with -h and --help options" do
assert parse_args(["-h", "anything"]) == :help
assert parse_args(["--help", "anything"]) == :help
end
test "three values returned if three given" do
assert parse_args(["user", "project", "99"]) == { "user", "project", 99 }
end
test "count is defaulted if two values given" do
assert parse_args(["user", "project"]) == { "user", "project", 4 }
end
test "sort ascending orders the correct way" do
result = sort_into_ascending_order(fake_created_at_list(["c", "a", "b"]))
issues = for issue <- result, do: issue["created_at"]
assert issues == ~w{a b c}
end
defp fake_created_at_list(values) do
data = for value <- values,
do: [{"created_at", value}, {"other_data", "xyz"}]
convert_to_list_of_hashdicts data
end
end
| 28.885714 | 77 | 0.652819 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.