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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
93a3ed7e711037ada824620aa7ae0e503ff1f85f
| 3,061
|
exs
|
Elixir
|
apps/slack/test/router_test.exs
|
pluralsight/compliments
|
bb0a9f9cc55e41adbdb56d138bf462d0eb12208e
|
[
"MIT"
] | 1
|
2019-01-16T01:03:14.000Z
|
2019-01-16T01:03:14.000Z
|
apps/slack/test/router_test.exs
|
pluralsight/compliments
|
bb0a9f9cc55e41adbdb56d138bf462d0eb12208e
|
[
"MIT"
] | 1
|
2020-04-12T09:58:03.000Z
|
2020-04-12T09:58:03.000Z
|
apps/slack/test/router_test.exs
|
pluralsight/compliments
|
bb0a9f9cc55e41adbdb56d138bf462d0eb12208e
|
[
"MIT"
] | 2
|
2018-10-02T18:09:55.000Z
|
2021-03-19T04:44:25.000Z
|
defmodule Slack.RouterTest do
use ExUnit.Case, async: true
use Plug.Test
alias Slack.Router
import Mock
@opts Router.init([])
@example_body "token=xyzz0WbapA4vBCDEFasx0q6G&team_id=T1DC2JH3J&" <>
"team_domain=testteamnow&channel_id=G8PSS9T3V&" <>
"channel_name=foobar&user_id=U2CERLKJA&" <>
"user_name=roadrunner&command=%2Fwebhook-collect" <>
"&text=&response_url=https%3A%2F%2Fhooks.slack.com%2F" <>
"commands%2FT1DC2JH3J%2F397700885554%2F96rGlfmibIGlgc" <>
"ZRskXaIFfN&trigger_id=398738663015.47445629121.803a0" <>
"bc887a14d10d2c447fce8b6703c"
@example_timestamp "1531420618"
@example_signature "v0=a2114d57b48eac39b9ad189dd8316235a7b4a8d21a10bd27519666489c69b503"
describe "GET /heath" do
test "returns health check" do
conn =
conn(:get, "/health")
|> Router.call(@opts)
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body == "OK"
end
end
describe "GET /" do
test "returns informational message" do
conn =
conn(:get, "/")
|> Router.call(@opts)
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body =~ "compliment"
end
end
describe "GET unknown route" do
test "returns error" do
conn =
conn(:get, "/nonexistent")
|> Router.call(@opts)
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body =~ "error"
end
end
describe "POST /" do
test "returns when successful" do
with_mock Manager, run: fn _ -> :ok end do
conn =
conn(:post, "/", @example_body)
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> put_req_header("x-slack-request-timestamp", @example_timestamp)
|> put_req_header("x-slack-signature", @example_signature)
|> Router.call(@opts)
assert conn.state == :sent
assert conn.status == 200
end
end
test "returns error when missing headers" do
with_mock Manager, run: fn _ -> :ok end do
conn =
conn(:post, "/", @example_body)
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> Router.call(@opts)
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body =~ "error"
end
end
test "returns error when incorrectly signed" do
with_mock Manager, run: fn _ -> :ok end do
conn =
conn(:post, "/", @example_body)
|> put_req_header("content-type", "application/x-www-form-urlencoded")
|> put_req_header("x-slack-request-timestamp", @example_timestamp)
|> put_req_header("x-slack-signature", @example_signature <> "a")
|> Router.call(@opts)
assert conn.state == :sent
assert conn.status == 200
assert conn.resp_body =~ "error"
end
end
end
end
| 30.009804
| 90
| 0.601764
|
93a42aba6eeea2e3cb526aef91462d63ef8f5959
| 2,091
|
exs
|
Elixir
|
file-metadata/config/runtime.exs
|
dalamilla/phoenix-projects
|
52654fb0d3ff7d5b556569dac5c0863e230e3a00
|
[
"MIT"
] | null | null | null |
file-metadata/config/runtime.exs
|
dalamilla/phoenix-projects
|
52654fb0d3ff7d5b556569dac5c0863e230e3a00
|
[
"MIT"
] | null | null | null |
file-metadata/config/runtime.exs
|
dalamilla/phoenix-projects
|
52654fb0d3ff7d5b556569dac5c0863e230e3a00
|
[
"MIT"
] | null | null | null |
import Config
# config/runtime.exs is executed for all environments, including
# during releases. It is executed after compilation and before the
# system starts, so it is typically used to load production configuration
# and secrets from environment variables or elsewhere. Do not define
# any compile-time configuration in here, as it won't be applied.
# The block below contains prod specific runtime configuration.
# Start the phoenix server if environment is set and running in a release
if System.get_env("PHX_SERVER") && System.get_env("RELEASE_NAME") do
config :file_metadata, FileMetadataWeb.Endpoint, server: true
end
if config_env() == :prod do
# The secret key base is used to sign/encrypt cookies and other secrets.
# A default value is used in config/dev.exs and config/test.exs but you
# want to use a different value for prod and you most likely don't want
# to check this value into version control, so we use an environment
# variable instead.
secret_key_base =
System.get_env("SECRET_KEY_BASE") ||
raise """
environment variable SECRET_KEY_BASE is missing.
You can generate one by calling: mix phx.gen.secret
"""
host = System.get_env("PHX_HOST") || "example.com"
port = String.to_integer(System.get_env("PORT") || "4000")
config :file_metadata, FileMetadataWeb.Endpoint,
url: [host: host, port: 443],
http: [
# Enable IPv6 and bind on all interfaces.
# Set it to {0, 0, 0, 0, 0, 0, 0, 1} for local network only access.
# See the documentation on https://hexdocs.pm/plug_cowboy/Plug.Cowboy.html
# for details about using IPv6 vs IPv4 and loopback vs public addresses.
ip: {0, 0, 0, 0, 0, 0, 0, 0},
port: port
],
secret_key_base: secret_key_base
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start each relevant endpoint:
#
# config :file_metadata, FileMetadataWeb.Endpoint, server: true
#
# Then you can assemble a release by calling `mix release`.
# See `mix help release` for more information.
end
| 39.45283
| 80
| 0.713056
|
93a42c8769efa7f2e8a318639d8a0d30ba8367fa
| 2,246
|
ex
|
Elixir
|
lib/coherence/responders.ex
|
thefuture2092/coherence
|
377d91ff01622773b5a9ec39fadf1f8c27328879
|
[
"MIT"
] | 1,347
|
2016-07-04T23:20:10.000Z
|
2022-02-10T20:10:48.000Z
|
lib/coherence/responders.ex
|
thefuture2092/coherence
|
377d91ff01622773b5a9ec39fadf1f8c27328879
|
[
"MIT"
] | 378
|
2016-07-06T16:30:28.000Z
|
2021-09-16T13:34:05.000Z
|
lib/coherence/responders.ex
|
thefuture2092/coherence
|
377d91ff01622773b5a9ec39fadf1f8c27328879
|
[
"MIT"
] | 276
|
2016-07-06T20:26:17.000Z
|
2021-12-06T19:32:41.000Z
|
defmodule Coherence.Responders do
@callback session_create_success(conn :: term, opts :: term) :: term
@callback session_create_error(conn :: term, opts :: term) :: term
@callback session_create_error_locked(conn :: term, opts :: term) :: term
@callback session_delete_success(conn :: term, opts :: term) :: term
@callback session_already_logged_in(conn :: term, opts :: term) :: term
@callback registration_create_success(conn :: term, opts :: term) :: term
@callback registration_create_error(conn :: term, opts :: term) :: term
@callback registration_update_success(conn :: term, opts :: term) :: term
@callback registration_update_error(conn :: term, opts :: term) :: term
@callback registration_delete_success(conn :: term, opts :: term) :: term
@callback unlock_create_success(conn :: term, opts :: term) :: term
@callback unlock_create_error(conn :: term, opts :: term) :: term
@callback unlock_create_error_not_locked(conn :: term, opts :: term) :: term
@callback unlock_update_success(conn :: term, opts :: term) :: term
@callback unlock_update_error(conn :: term, opts :: term) :: term
@callback unlock_update_error_not_locked(conn :: term, opts :: term) :: term
@callback confirmation_create_success(conn :: term, opts :: term) :: term
@callback confirmation_create_error(conn :: term, opts :: term) :: term
@callback confirmation_update_success(conn :: term, opts :: term) :: term
@callback confirmation_update_error(conn :: term, opts :: term) :: term
@callback password_create_success(conn :: term, opts :: term) :: term
@callback password_create_error(conn :: term, opts :: term) :: term
@callback password_update_success(conn :: term, opts :: term) :: term
@callback password_update_error(conn :: term, opts :: term) :: term
@callback invitation_create_success(conn :: term, opts :: term) :: term
@callback invitation_create_error(conn :: term, opts :: term) :: term
@callback invitation_resend_success(conn :: term, opts :: term) :: term
@callback invitation_resend_error(conn :: term, opts :: term) :: term
@callback invitation_create_user_success(conn :: term, opts :: term) :: term
@callback invitation_create_user_error(conn :: term, opts :: term) :: term
end
| 59.105263
| 78
| 0.715049
|
93a47a1e359beedf6b67b39d0b156dffc77e30e2
| 2,658
|
ex
|
Elixir
|
lib/ex_dhcp/utils.ex
|
ityonemo/ExDhcp
|
9a7f47da61a93b4fb9efaa62bbdb362e3b467b2b
|
[
"MIT"
] | null | null | null |
lib/ex_dhcp/utils.ex
|
ityonemo/ExDhcp
|
9a7f47da61a93b4fb9efaa62bbdb362e3b467b2b
|
[
"MIT"
] | 16
|
2019-12-16T04:56:50.000Z
|
2020-03-11T20:18:56.000Z
|
lib/ex_dhcp/utils.ex
|
ityonemo/ex_dhcp
|
9a7f47da61a93b4fb9efaa62bbdb362e3b467b2b
|
[
"MIT"
] | 1
|
2019-12-13T19:04:50.000Z
|
2019-12-13T19:04:50.000Z
|
defmodule ExDhcp.Utils do
@moduledoc """
Provides utilities containing typespecs for data types and binary/string
conversions for _ip_ and _mac_ addresses. For ease-of-use both within this
library and when using it.
"""
@typedoc "Erlang-style _ip_ addresses."
@type ip4 :: :inet.ip4_address
@typedoc "_Mac_ addresses in the same style as the erlang _ip_ address."
@type mac :: {byte, byte, byte, byte, byte, byte}
@doc """
Represents an erlang-style ip4 value as a string, without going through
a list intermediate.
"""
@spec ip2str(ip4) :: binary
def ip2str(_ip_addr = {a, b, c, d}), do: "#{a}.#{b}.#{c}.#{d}"
@doc """
Converts an erlang-style _ip_ address (4-tuple of bytes)
to a binary stored _ip_ address (in the dhcp packet spec)
"""
@spec ip2bin(ip4) :: <<_::32>>
def ip2bin(_ip_addr = {a, b, c, d}), do: <<a, b, c, d>>
@doc """
Converts a binary stored _ip_ address (in the dhcp packet spec) to
an erlang-style _ip_ address. (4-tuple of bytes)
"""
@spec bin2ip(<<_::32>>) :: ip4
def bin2ip(_mac_addr = <<a, b, c, d>>), do: {a, b, c, d}
@doc """
Converts a binary stored _mac_ address (in the dhcp packet spec) to
an erlang-style _mac_ address. (6-tuple of bytes)
"""
def bin2mac(_mac_addr = <<a, b, c, d, e, f>>), do: {a, b, c, d, e, f}
@doc """
Converts an erlang-style _mac_ address (6-tuple of bytes) to a
binary stored _mac_ address (in the dhcp packet spec).
"""
def mac2bin(_mac_addr = {a, b, c, d, e, f}), do: <<a, b, c, d, e, f>>
@doc """
Converts a _mac_ address 6-byte tuple to a string.
```elixir
iex> ExDhcp.Utils.mac2str({1, 2, 3, 16, 255, 254})
"01:02:03:10:FF:FE"
```
"""
def mac2str(mac_addr = {_, _, _, _, _, _}) do
mac_addr
|> Tuple.to_list
|> Enum.map(&padhex/1)
|> Enum.join(":")
end
@doc """
Converts a _mac_ address string into a raw binary value.
```elixir
iex> ExDhcp.Utils.str2mac("01:02:03:10:FF:FE")
{1, 2, 3, 16, 255, 254}
```
"""
def str2mac(_mac_addr = <<a::16, ":", b::16, ":", c::16, ":", d::16, ":", e::16, ":", f::16>>) do
[<<a::16>>, <<b::16>>, <<c::16>>, <<d::16>>, <<e::16>>, <<f::16>>]
|> Enum.map(&String.to_integer(&1, 16))
|> List.to_tuple
end
defp padhex(v) when v < 16, do: "0" <> Integer.to_string(v, 16)
defp padhex(v), do: Integer.to_string(v, 16)
@spec cidr2mask(cidr :: 0..32) :: ip4
@doc """
Creates a subnet mask from a _cidr_ value.
```elixir
iex> ExDhcp.Utils.cidr2mask(24)
{255, 255, 255, 0}
```
"""
def cidr2mask(_cidr_val = n) do
import Bitwise
<<a, b, c, d>> = <<-1 <<< (32 - n)::32>>
{a, b, c, d}
end
end
| 27.978947
| 99
| 0.58766
|
93a47b24b6bbdf341f8d8763f591c1b114573cc0
| 1,202
|
exs
|
Elixir
|
config/config.exs
|
MateusAquino/nlw5
|
e522495b983ecd823b7afc38b18231c0a7db980f
|
[
"MIT"
] | null | null | null |
config/config.exs
|
MateusAquino/nlw5
|
e522495b983ecd823b7afc38b18231c0a7db980f
|
[
"MIT"
] | null | null | null |
config/config.exs
|
MateusAquino/nlw5
|
e522495b983ecd823b7afc38b18231c0a7db980f
|
[
"MIT"
] | null | null | null |
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
#
# This configuration file is loaded before any dependency and
# is restricted to this project.
# General application configuration
use Mix.Config
config :inmana,
ecto_repos: [Inmana.Repo]
config :inmana, Inmana.Repo,
migration_primary_key: [type: :binary_id],
migration_foreign_key: [type: :binary_id]
config :inmana, Inmana.Mailer, adapter: Bamboo.LocalAdapter
# Configures the endpoint
config :inmana, InmanaWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "8DAoRUjzH303xmPzpBjbIZxQXa4Y/TmtVAbn2+OGv7BzekrTDdb10+GQkTD9cLbA",
render_errors: [view: InmanaWeb.ErrorView, accepts: ~w(json), layout: false],
pubsub_server: Inmana.PubSub,
live_view: [signing_salt: "Th+oB054"]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
# Import environment specific config. This must remain at the bottom
# of this file so it overrides the configuration defined above.
import_config "#{Mix.env()}.exs"
| 31.631579
| 86
| 0.767055
|
93a4c307d88295070f8d5377e823e93bd7a1aa8e
| 62,033
|
ex
|
Elixir
|
lib/radixir/core.ex
|
radixir/radixir
|
703034330e857bc084b78dd927ec611c3ea54349
|
[
"Apache-2.0"
] | 16
|
2022-01-05T20:41:55.000Z
|
2022-03-25T09:06:43.000Z
|
lib/radixir/core.ex
|
radixir/radixir
|
703034330e857bc084b78dd927ec611c3ea54349
|
[
"Apache-2.0"
] | null | null | null |
lib/radixir/core.ex
|
radixir/radixir
|
703034330e857bc084b78dd927ec611c3ea54349
|
[
"Apache-2.0"
] | 1
|
2022-02-10T21:55:26.000Z
|
2022-02-10T21:55:26.000Z
|
defmodule Radixir.Core do
@moduledoc """
Provides high level interaction with the Core API.
"""
alias Radixir.Core.API
alias Radixir.Core.Request
alias Radixir.Key
alias Radixir.Util
@type public_key :: String.t()
@type private_key :: String.t()
@type type :: String.t()
@type address :: String.t()
@type amount :: String.t()
@type rri :: String.t()
@type symbol :: String.t()
@type round :: integer
@type epoch :: integer
@type timestamp :: integer
@type state_version :: integer
@type action :: String.t()
@type substate_data_hex :: String.t()
@type options :: keyword
@type error_message :: String.t()
@type epoch_unlock :: integer
@type unsigned_transaction :: String.t()
@type transaction :: String.t()
@type signed :: boolean
@type signed_transaction :: String.t()
@type signature_bytes :: String.t()
@type signature_public_key :: String.t()
@type transaction_hash :: String.t()
@type fee_payer_address :: String.t()
@type validator_address :: String.t()
@type operation_groups :: list
@type substate_operation :: String.t()
@type substate_identifier :: String.t()
@type granularity :: integer
@type is_mutable :: boolean
@type registered :: boolean
@type fee :: integer
@type name :: String.t()
@type url :: String.t()
@type proposals_completed :: integer
@type proposals_missed :: integer
@type allow_delegation :: boolean
@type data :: String.t()
@doc """
Gets network configuration.
## Parameters
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_network_configuration(options) :: {:ok, map} | {:error, map | error_message}
def get_network_configuration(options \\ []),
do: API.get_network_configuration(Keyword.get(options, :api, []))
@doc """
Gets network status.
## Parameters
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_network_status(options) :: {:ok, map} | {:error, map | error_message}
def get_network_status(options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.GetNetworkStatus.network_identifier(network)
|> Util.stitch()
API.get_network_status(body, Keyword.get(options, :api, []))
end
@doc """
Gets entity information.
## Parameters
- `address`: Radix address.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_entity_information(address, options) :: {:ok, map} | {:error, map | error_message}
def get_entity_information(address, options \\ []) do
network = Keyword.take(options, [:network])
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
body =
[]
|> Request.GetEntityInformation.network_identifier(network)
|> Request.GetEntityInformation.entity_identifier(address: address)
|> Util.maybe_create_stitch_plan(sub_entity, &Request.GetEntityInformation.sub_entity/2)
|> Util.stitch()
API.get_entity_information(body, Keyword.get(options, :api, []))
end
@doc """
Gets mempool transactions.
## Parameters
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_mempool_transactions(options) :: {:ok, map} | {:error, map | error_message}
def get_mempool_transactions(options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.GetMempoolTransactions.network_identifier(network)
|> Util.stitch()
API.get_mempool_transactions(body, Keyword.get(options, :api, []))
end
@doc """
Gets mempool transaction.
## Parameters
- `transaction_hash`: Transaction hash.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_mempool_transaction(transaction_hash, options) ::
{:ok, map} | {:error, map | error_message}
def get_mempool_transaction(transaction_hash, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.GetMempoolTransaction.network_identifier(network)
|> Request.GetMempoolTransaction.transaction_identifier(hash: transaction_hash)
|> Util.stitch()
API.get_mempool_transaction(body, Keyword.get(options, :api, []))
end
@doc """
Gets committed transactions.
## Parameters
- `state_version`: State version.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
- `transaction_accumulator` (optional, string): Transaction accumulator in state identifier map.
- `limit` (optional, integer): Maximum number of transactions that will be returned.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_committed_transactions(state_version, options) ::
{:ok, map} | {:error, map | error_message}
def get_committed_transactions(state_version, options \\ []) do
network = Keyword.take(options, [:network])
limit = Keyword.take(options, [:limit])
state_version = [state_version: state_version]
transaction_accumulator = Keyword.take(options, [:transaction_accumulator])
state_version = Keyword.merge(state_version, transaction_accumulator)
body =
[]
|> Request.GetCommittedTransactions.network_identifier(network)
|> Request.GetCommittedTransactions.state_identifier(state_version)
|> Util.maybe_create_stitch_plan(limit, &Request.GetCommittedTransactions.limit/2)
|> Util.stitch()
API.get_committed_transactions(body, Keyword.get(options, :api, []))
end
@doc """
Derives `Account` entity identifier.
## Parameters
- `public_key`: Public key.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_account_entity_identifier(public_key, options) ::
{:ok, map} | {:error, map | error_message}
def derive_account_entity_identifier(public_key, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.Account.type()
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Derives `Validator` entity identifier.
## Parameters
- `public_key`: Public key.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_validator_entity_identifier(public_key, options) ::
{:ok, map} | {:error, map | error_message}
def derive_validator_entity_identifier(public_key, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.Validator.type()
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Derives `Token` entity identifier.
## Parameters
- `public_key`: Public key.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_token_entity_identifier(public_key, symbol, options) ::
{:ok, map} | {:error, map | error_message}
def derive_token_entity_identifier(public_key, symbol, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.Token.type()
|> Request.DeriveEntityIdentifier.Metadata.Token.symbol(symbol: symbol)
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Derives `PreparedStakes` entity identifier.
## Parameters
- `public_key`: Public key.
- `validator_address`: Radix address.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_prepared_stakes_entity_identifier(public_key, validator_address, options) ::
{:ok, map} | {:error, map | error_message}
def derive_prepared_stakes_entity_identifier(public_key, validator_address, options \\ []) do
network = Keyword.take(options, [:network])
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.PreparedStakes.type()
|> Request.DeriveEntityIdentifier.Metadata.PreparedStakes.validator(
address: validator_address
)
|> Util.maybe_create_stitch_plan(
sub_entity,
&Request.DeriveEntityIdentifier.Metadata.PreparedStakes.sub_entity/2
)
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Derives `PreparedUnstakes` entity identifier.
## Parameters
- `public_key`: Public key.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_prepared_unstakes_entity_identifier(public_key, options) ::
{:ok, map} | {:error, map | error_message}
def derive_prepared_unstakes_entity_identifier(public_key, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.PreparedUnstakes.type()
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Derives `ExitingUnstakes` entity identifier.
## Parameters
- `public_key`: Public key.
- `validator_address`: Radix address.
- `epoch_unlock`: Epoch unlock.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_exiting_unstakes_entity_identifier(
public_key,
validator_address,
epoch_unlock,
options
) ::
{:ok, map} | {:error, map | error_message}
def derive_exiting_unstakes_entity_identifier(
public_key,
validator_address,
epoch_unlock,
options \\ []
) do
network = Keyword.take(options, [:network])
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.ExitingUnstakes.type()
|> Request.DeriveEntityIdentifier.Metadata.ExitingUnstakes.validator(
address: validator_address
)
|> Util.maybe_create_stitch_plan(
sub_entity,
&Request.DeriveEntityIdentifier.Metadata.ExitingUnstakes.sub_entity/2
)
|> Request.DeriveEntityIdentifier.Metadata.ExitingUnstakes.epoch_unlock(
epoch_unlock: epoch_unlock
)
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Derives `ValidatorSystem` entity identifier.
## Parameters
- `public_key`: Public key.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec derive_validator_system_entity_identifier(public_key, options) ::
{:ok, map} | {:error, map | error_message}
def derive_validator_system_entity_identifier(public_key, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.DeriveEntityIdentifier.network_identifier(network)
|> Request.DeriveEntityIdentifier.public_key(hex: public_key)
|> Request.DeriveEntityIdentifier.Metadata.ValidatorSystem.type()
|> Util.stitch()
API.derive_entity_identifier(body, Keyword.get(options, :api, []))
end
@doc """
Builds type map in an operation.
## Parameters
- `type`: Can be Resource, Data, or ResourceAndData.
"""
@spec build_operation_type(type) :: map
def build_operation_type(type) do
[]
|> Request.BuildTransaction.Operation.type(type: type)
|> Util.stitch()
end
@doc """
Builds entity identifier map in operation.
## Parameters
- `address`: Radix address.
- `options`: Keyword list that contains
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
"""
@spec build_operation_entity_identifier(address, options) :: map
def build_operation_entity_identifier(address, options \\ []) do
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
[]
|> Request.BuildTransaction.Operation.entity_identifier(address: address)
|> Util.maybe_create_stitch_plan(sub_entity, &Request.BuildTransaction.Operation.sub_entity/2)
|> Util.stitch()
end
@doc """
Builds substate map in operation.
## Parameters
- `substate_operation`: Substate operation - can be "BOOTUP" or "SHUTDOWN".
- `substate_identifier`: Substate identifier
"""
@spec build_operation_substate(substate_operation, substate_identifier) :: map
def build_operation_substate(substate_operation, substate_identifier) do
[]
|> Request.BuildTransaction.Operation.substate(
substate_operation: substate_operation,
identifier: substate_identifier
)
|> Util.stitch()
end
@doc """
Builds amount map in operation where resource type is token.
## Parameters
- `amount`: Amount.
- `rri`: Token rri.
"""
@spec build_operation_amount_token(amount, rri) :: map
def build_operation_amount_token(amount, rri) do
[]
|> Request.BuildTransaction.Operation.amount(amount: amount)
|> Request.BuildTransaction.Operation.ResourceIdentifier.token(rri: rri)
|> Util.stitch()
end
@doc """
Builds amount map in operation where resource type is stake unit.
## Parameters
- `amount`: Amount.
- `validator_address`: Validator addres.
"""
@spec build_operation_amount_stake_unit(amount, validator_address) :: map
def build_operation_amount_stake_unit(amount, validator_address) do
[]
|> Request.BuildTransaction.Operation.amount(amount: amount)
|> Request.BuildTransaction.Operation.ResourceIdentifier.stake_unit(
validator_address: validator_address
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is UnclaimedRadixEngineAddress.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
"""
@spec build_operation_data_unclaimed_radix_engine_address(action) :: map
def build_operation_data_unclaimed_radix_engine_address(action) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.UnclaimedRadixEngineAddress.type()
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is RoundData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `round`: Round
- `timestamp`: Timestamp
"""
@spec build_operation_data_round_data(action, round, timestamp) :: map
def build_operation_data_round_data(action, round, timestamp) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.RoundData.type()
|> Request.BuildTransaction.Operation.DataObject.RoundData.round(round: round)
|> Request.BuildTransaction.Operation.DataObject.RoundData.timestamp(timestamp: timestamp)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is EpochData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `epoch`: Epoch
"""
@spec build_operation_data_epoch_data(action, epoch) :: map
def build_operation_data_epoch_data(action, epoch) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.EpochData.type()
|> Request.BuildTransaction.Operation.DataObject.EpochData.epoch(epoch: epoch)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is TokenData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `granularity`: Granularity
- `is_mutable`: If the token is mutable.
- `options`: Keyword list that contains
- `address` (optional, string): Owner address
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
"""
@spec build_operation_data_token_data(action, granularity, is_mutable, options) :: map
def build_operation_data_token_data(action, granularity, is_mutable, options \\ []) do
owner_address = Keyword.take(options, [:address])
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.TokenData.type()
|> Request.BuildTransaction.Operation.DataObject.TokenData.granularity(
granularity: granularity
)
|> Request.BuildTransaction.Operation.DataObject.TokenData.is_mutable(is_mutable: is_mutable)
|> Util.maybe_create_stitch_plan(
owner_address,
&Request.BuildTransaction.Operation.DataObject.TokenData.owner/2
)
|> Util.maybe_create_stitch_plan(
sub_entity,
&Request.BuildTransaction.Operation.DataObject.TokenData.sub_entity/2
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is TokenMetaData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `symbol`: Token symbol
- `options`: Keyword list that contains
- `name` (optional, string): Token name.
- `description` (optional, string): Token description.
- `url` (optional, string): Token url.
- `icon_url` (optional, string): Token icon_url.
"""
@spec build_operation_data_token_metadata(action, symbol, options) :: map
def build_operation_data_token_metadata(action, symbol, options \\ []) do
name = Keyword.take(options, [:name])
description = Keyword.take(options, [:description])
url = Keyword.take(options, [:url])
icon_url = Keyword.take(options, [:icon_url])
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.TokenMetaData.type()
|> Request.BuildTransaction.Operation.DataObject.TokenMetaData.symbol(symbol: symbol)
|> Util.maybe_create_stitch_plan(
name,
&Request.BuildTransaction.Operation.DataObject.TokenMetaData.name/2
)
|> Util.maybe_create_stitch_plan(
description,
&Request.BuildTransaction.Operation.DataObject.TokenMetaData.description/2
)
|> Util.maybe_create_stitch_plan(
url,
&Request.BuildTransaction.Operation.DataObject.TokenMetaData.url/2
)
|> Util.maybe_create_stitch_plan(
icon_url,
&Request.BuildTransaction.Operation.DataObject.TokenMetaData.icon_url/2
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is TokenMetaData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `symbol`: Token symbol
- `options`: Keyword list that contains
- `epoch` (options, integer): Epoch.
"""
@spec build_operation_data_prepared_validator_registered(action, registered, options) :: map
def build_operation_data_prepared_validator_registered(action, registered, options \\ []) do
epoch = Keyword.take(options, [:epoch])
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.PreparedValidatorRegistered.type()
|> Request.BuildTransaction.Operation.DataObject.PreparedValidatorRegistered.registered(
registered: registered
)
|> Util.maybe_create_stitch_plan(
epoch,
&Request.BuildTransaction.Operation.DataObject.PreparedValidatorRegistered.epoch/2
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is PreparedValidatorOwner.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `address`: Owner address
- `options`: Keyword list that contains
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
"""
@spec build_operation_data_prepared_validator_owner(action, address, options) :: map
def build_operation_data_prepared_validator_owner(action, address, options \\ []) do
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.PreparedValidatorOwner.type()
|> Request.BuildTransaction.Operation.DataObject.PreparedValidatorOwner.owner(
address: address
)
|> Util.maybe_create_stitch_plan(
sub_entity,
&Request.BuildTransaction.Operation.DataObject.PreparedValidatorOwner.sub_entity/2
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is PreparedValidatorFee.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `fee`: Validator fee.
- `options`: Keyword list that contains
- `epoch` (optional, integer): Epoch.
"""
@spec build_operation_data_prepared_validator_fee(action, fee, options) :: map
def build_operation_data_prepared_validator_fee(action, fee, options \\ []) do
epoch = Keyword.take(options, [:epoch])
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.PreparedValidatorFee.type()
|> Request.BuildTransaction.Operation.DataObject.PreparedValidatorFee.fee(fee: fee)
|> Util.maybe_create_stitch_plan(
epoch,
&Request.BuildTransaction.Operation.DataObject.PreparedValidatorFee.epoch/2
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is ValidatorMetadata.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `name`: Validator name.
- `url`: Validator url.
"""
@spec build_operation_data_validator_metadata(action, name, url) :: map
def build_operation_data_validator_metadata(action, name, url) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.ValidatorMetadata.type()
|> Request.BuildTransaction.Operation.DataObject.ValidatorMetadata.name(name: name)
|> Request.BuildTransaction.Operation.DataObject.ValidatorMetadata.url(url: url)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is ValidatorBFTData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `proposals_completed`: Number of completed proposals by this validator as a leader in the current epoch.
- `proposals_missed`: Number of missed proposals by this validator as a leader in the current epoch.
"""
@spec build_operation_data_validator_bft_data(action, proposals_completed, proposals_missed) ::
map
def build_operation_data_validator_bft_data(action, proposals_completed, proposals_missed) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.ValidatorBFTdata.type()
|> Request.BuildTransaction.Operation.DataObject.ValidatorBFTdata.proposals_completed(
proposals_completed: proposals_completed
)
|> Request.BuildTransaction.Operation.DataObject.ValidatorBFTdata.proposals_missed(
proposals_missed: proposals_missed
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is ValidatorAllowDelegation.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `allow_delegation`: If validator allows delegation.
"""
@spec build_operation_data_validator_allow_delegation(action, allow_delegation) ::
map
def build_operation_data_validator_allow_delegation(action, allow_delegation) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.ValidatorAllowDelegation.type()
|> Request.BuildTransaction.Operation.DataObject.ValidatorAllowDelegation.allow_delegation(
allow_delegation: allow_delegation
)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is ValidatorData.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `address`: Owner address
- `registered`: If validator is registered or not.
- `fee`: Validator fee.
- `options`: Keyword list that contains
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
"""
@spec build_operation_data_validator_data(action, address, registered, fee, options) ::
map
def build_operation_data_validator_data(
action,
address,
registered,
fee,
options \\ []
) do
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.ValidatorData.type()
|> Request.BuildTransaction.Operation.DataObject.ValidatorData.owner(address: address)
|> Util.maybe_create_stitch_plan(
sub_entity,
&Request.BuildTransaction.Operation.DataObject.ValidatorData.sub_entity/2
)
|> Request.BuildTransaction.Operation.DataObject.ValidatorData.registered(
registered: registered
)
|> Request.BuildTransaction.Operation.DataObject.ValidatorData.fee(fee: fee)
|> Util.stitch()
end
@doc """
Builds data map in operation where data object type is ValidatorSystemMetadata.
## Parameters
- `action`: Action - can be "CREATE" or "DELETE".
- `data`: Hex encoded byte array.
"""
@spec build_operation_data_validator_system_metadata(action, data) ::
map
def build_operation_data_validator_system_metadata(action, data) do
[]
|> Request.BuildTransaction.Operation.data(action: action)
|> Request.BuildTransaction.Operation.DataObject.ValidatorSystemMetadata.type()
|> Request.BuildTransaction.Operation.DataObject.ValidatorSystemMetadata.data(data: data)
|> Util.stitch()
end
@doc """
Builds metadata map in operation.
## Parameters
- `substate_data_hex`: Substate data hex.
"""
@spec build_operation_metadata(substate_data_hex) :: map
def build_operation_metadata(substate_data_hex) do
[]
|> Request.BuildTransaction.Operation.metadata(substate_data_hex: substate_data_hex)
|> Util.stitch()
end
@doc """
Builds an operation.
## Parameters
- `type`: Type map.
- `entity_identifier`: Entity identifier map.
- `options`: Keyword list that contains
- `substate` (optional, map): Substate map.
- `amount` (optional, map): Amount map.
- `data` (optional, map): Data map.
- `metadata` (optional, map): Metadata map.
"""
def build_operation(type, entity_identifier, options \\ []) do
substate = Keyword.get(options, :substate, %{})
amount = Keyword.get(options, :amount, %{})
data = Keyword.get(options, :data, %{})
metadata = Keyword.get(options, :metadata, %{})
type
|> Map.merge(entity_identifier)
|> Map.merge(substate)
|> Map.merge(amount)
|> Map.merge(data)
|> Map.merge(metadata)
end
@doc """
Builds an operation group.
## Parameters
- `operations`: List of operation maps.
"""
@spec build_operation_group(list(map)) :: map
def build_operation_group(operations) do
Request.BuildTransaction.OperationGroup.create(operations)
end
@doc """
Builds a transaction.
## Parameters
- `operation_groups`: Operation groups.
- `fee_payer_address`: Fee payer address.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
- `message` (optional, string): Message to be included in transaction.
- `disable_resource_allocate_and_destroy` (optional, boolean): Disable resource allocate and destroy.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec build_transaction(
operation_groups,
fee_payer_address,
options
) ::
{:ok, map} | {:error, map | error_message}
def build_transaction(
operation_groups,
fee_payer_address,
options \\ []
) do
network = Keyword.take(options, [:network])
sub_entity = Keyword.take(options, [:sub_entity_address, :validator_address, :epoch_unlock])
message = Keyword.take(options, [:message])
disable_resource_allocate_and_destroy =
Keyword.take(options, [:disable_resource_allocate_and_destroy])
body =
[]
|> Request.BuildTransaction.network_identifier(network)
|> Request.BuildTransaction.fee_payer(address: fee_payer_address)
|> Util.maybe_create_stitch_plan(sub_entity, &Request.BuildTransaction.sub_entity/2)
|> Util.maybe_create_stitch_plan(message, &Request.BuildTransaction.message/2)
|> Util.maybe_create_stitch_plan(
disable_resource_allocate_and_destroy,
&Request.BuildTransaction.disable_resource_allocate_and_destroy/2
)
|> Util.stitch()
body = Request.BuildTransaction.add_operation_groups(body, operation_groups)
API.build_transaction(body, Keyword.get(options, :api, []))
end
@doc """
Parses a transaction.
## Parameters
- `transaction`: Transaction to parse.
- `signed`: Whether the transaction is signed or not.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec parse_transaction(transaction, signed, options) ::
{:ok, map} | {:error, map | error_message}
def parse_transaction(transaction, signed, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.ParseTransaction.network_identifier(network)
|> Request.ParseTransaction.transaction(transaction: transaction)
|> Request.ParseTransaction.signed(signed: signed)
|> Util.stitch()
API.parse_transaction(body, Keyword.get(options, :api, []))
end
@doc """
Finalizes a transaction.
## Parameters
- `unsigned_transaction`: Unsigned ransaction.
- `signature_public_key`: Signature public key.
- `signature_bytes`: Signature bytes.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec finalize_transaction(unsigned_transaction, signature_public_key, signature_bytes, options) ::
{:ok, map} | {:error, map | error_message}
def finalize_transaction(
unsigned_transaction,
signature_public_key,
signature_bytes,
options \\ []
) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.FinalizeTransaction.network_identifier(network)
|> Request.FinalizeTransaction.unsigned_transaction(
unsigned_transaction: unsigned_transaction
)
|> Request.FinalizeTransaction.signature(hex: signature_public_key, bytes: signature_bytes)
|> Util.stitch()
API.finalize_transaction(body, Keyword.get(options, :api, []))
end
@doc """
Gets transaction hash.
## Parameters
- `signed_transaction`: Signed ransaction.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_transaction_hash(signed_transaction, options) ::
{:ok, map} | {:error, map | error_message}
def get_transaction_hash(
signed_transaction,
options \\ []
) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.GetTransactionHash.network_identifier(network)
|> Request.GetTransactionHash.signed_transaction(signed_transaction: signed_transaction)
|> Util.stitch()
API.get_transaction_hash(body, Keyword.get(options, :api, []))
end
@doc """
Submits a transaction.
## Parameters
- `signed_transaction`: Signed ransaction.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec submit_transaction(signed_transaction, options) ::
{:ok, map} | {:error, map | error_message}
def submit_transaction(
signed_transaction,
options \\ []
) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.SubmitTransaction.network_identifier(network)
|> Request.SubmitTransaction.signed_transaction(signed_transaction: signed_transaction)
|> Util.stitch()
API.submit_transaction(body, Keyword.get(options, :api, []))
end
@doc """
Gets public keys.
## Parameters
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec get_public_keys(options) ::
{:ok, map} | {:error, map | error_message}
def get_public_keys(options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.GetPublicKeys.network_identifier(network)
|> Util.stitch()
API.get_public_keys(body, Keyword.get(options, :api, []))
end
@doc """
Signs a transaction.
## Parameters
- `unsigned_transaction`: Unsigned Transaction.
- `public_key`: Public key.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec sign_transaction(unsigned_transaction, public_key, options) ::
{:ok, map} | {:error, map | error_message}
def sign_transaction(unsigned_transaction, public_key, options \\ []) do
network = Keyword.take(options, [:network])
body =
[]
|> Request.SignTransaction.network_identifier(network)
|> Request.SignTransaction.unsigned_transaction(unsigned_transaction: unsigned_transaction)
|> Request.SignTransaction.public_key(hex: public_key)
|> Util.stitch()
API.sign_transaction(body, Keyword.get(options, :api, []))
end
@doc """
Sends a transaction.
## Parameters
- `operation_groups`: Operation groups.
- `fee_payer_address`: Fee payer address.
- `private_key`: Private key to sign transaction.
- `options`: Keyword list that contains
- `api`: Keyword list that contains
- `url` (optional, string): If url is not in options then the url set in the configs will be used.
- any other options one may want to pass along to the http layer - for example `headers`
- `auth_index` (optional, integer): Index of the username + password combo to be used for endpoint authentication.
- `username`: (optional, string): Username to be used for endpoint authentication.
- `password`: (optional, string): Password to be used for endpoint authentication.
- `network` (optional, string): If network is not in options it will default to what is returned from `Radixir.Config.network()`.
- `sub_entity_address` (optional, string): Sub entity address.
- `validator_address` (optional, string): Validator address.
- `epoch_unlock` (optional, integer): Epoch unlock.
- `message` (optional, string): Message to be included in transaction.
- `disable_resource_allocate_and_destroy` (optional, boolean): Disable resource allocate and destroy.
## Note
- Either `username` and `password` or `auth_index` must be provided.
- If all three are provided `auth_index` is used.
If the following usernames and passwords are exported as follows:
```
export USERNAMES='admin, superadmin, metrics'
export PASSWORDS='funny cats very Jack 21!, harry Kack love h39! LW, monitor Kat darrel 23 Jack!'
```
then an `auth_index` of 0 would result in `admin` being used as the username and `funny cats very Jack 21!` being used as the password.
"""
@spec send_transaction(
operation_groups,
fee_payer_address,
private_key,
options
) ::
{:ok, map} | {:error, map | error_message}
def send_transaction(
operation_groups,
fee_payer_address,
private_key,
options \\ []
) do
with {:ok, %{public_key: public_key}} <- Key.from_private_key(private_key),
{:ok, built_transaction} <-
build_transaction(
operation_groups,
fee_payer_address,
options
),
:ok <-
Util.verify_hash(
built_transaction["unsigned_transaction"],
built_transaction["payload_to_sign"]
),
{:ok, signature_bytes} <-
Key.sign_data(built_transaction["payload_to_sign"], private_key),
{:ok, finalized_transaction} <-
finalize_transaction(
built_transaction["unsigned_transaction"],
public_key,
signature_bytes,
options
) do
case submit_transaction(finalized_transaction["signed_transaction"], options) do
{:ok, submitted_transaction} ->
{:ok,
%{
build_transaction: built_transaction,
finalize_transaction: finalized_transaction,
submit_transaction: submitted_transaction
}}
{:error, error} ->
{:error,
%{
succeeded: %{
build_transaction: built_transaction,
finalize_transaction: finalized_transaction
},
failed: %{submit_transaction: error}
}}
end
end
end
end
| 42.663686
| 137
| 0.693631
|
93a4e4c9431888693d6ede3ea333fe7ec075fae8
| 1,551
|
ex
|
Elixir
|
lib/dune/eval/env.ex
|
functional-rewire/dune
|
9a7d3fd182e5b29e0bfb0b2a97daba468231546c
|
[
"MIT"
] | 58
|
2021-09-19T09:06:36.000Z
|
2022-02-03T11:19:38.000Z
|
lib/dune/eval/env.ex
|
functional-rewire/dune
|
9a7d3fd182e5b29e0bfb0b2a97daba468231546c
|
[
"MIT"
] | null | null | null |
lib/dune/eval/env.ex
|
functional-rewire/dune
|
9a7d3fd182e5b29e0bfb0b2a97daba468231546c
|
[
"MIT"
] | 1
|
2021-09-26T14:56:18.000Z
|
2021-09-26T14:56:18.000Z
|
defmodule Dune.Eval.Env do
@moduledoc false
alias Dune.AtomMapping
alias Dune.Eval.FakeModule
@type t :: %__MODULE__{
atom_mapping: AtomMapping.t(),
allowlist: module,
fake_modules: %{optional(atom) => FakeModule.t()}
}
@enforce_keys [:atom_mapping, :allowlist, :fake_modules]
defstruct [:atom_mapping, :allowlist, :fake_modules]
def new(atom_mapping = %AtomMapping{}, allowlist) when is_atom(allowlist) do
%__MODULE__{atom_mapping: atom_mapping, allowlist: allowlist, fake_modules: %{}}
end
def add_module(env = %__MODULE__{fake_modules: modules}, module_name, module = %FakeModule{})
when is_atom(module_name) do
# TODO check a bunch of things here:
# - warn if module redefined
# - fail if overriding existing module
# - fail if overriding Kernel/Special forms
%{env | fake_modules: Map.put(modules, module_name, module)}
end
def apply_fake(env = %__MODULE__{}, module, fun_name, args)
when is_atom(module) and is_atom(fun_name) and is_list(args) do
case fetch_fake_function(env, module, fun_name, length(args)) do
{:def, fun} -> fun.(env, args)
other -> throw(other)
end
end
defp fetch_fake_function(%{fake_modules: modules}, module, fun_name, arity) do
case modules do
%{^module => fake_module} ->
case FakeModule.get_function(fake_module, fun_name, arity) do
nil -> :undefined_function
{:def, fun} -> {:def, fun}
end
_ ->
:undefined_module
end
end
end
| 31.653061
| 95
| 0.663443
|
93a4e4cdd5c46126e66fabc834119b45d246a113
| 446
|
exs
|
Elixir
|
test/canon_web/views/error_view_test.exs
|
megalithic/canon
|
8178207cdaf1f137fcdf1f42481636e0209dcbeb
|
[
"MIT"
] | null | null | null |
test/canon_web/views/error_view_test.exs
|
megalithic/canon
|
8178207cdaf1f137fcdf1f42481636e0209dcbeb
|
[
"MIT"
] | null | null | null |
test/canon_web/views/error_view_test.exs
|
megalithic/canon
|
8178207cdaf1f137fcdf1f42481636e0209dcbeb
|
[
"MIT"
] | null | null | null |
defmodule CanonWeb.ErrorViewTest do
use CanonWeb.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(CanonWeb.ErrorView, "404.json", []) == %{errors: %{detail: "Not Found"}}
end
test "renders 500.json" do
assert render(CanonWeb.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| 27.875
| 90
| 0.67713
|
93a50b640aa9e20d0128d19351ae6bcd8751d5ac
| 153,015
|
ex
|
Elixir
|
lib/codes/codes_m80.ex
|
badubizzle/icd_code
|
4c625733f92b7b1d616e272abc3009bb8b916c0c
|
[
"Apache-2.0"
] | null | null | null |
lib/codes/codes_m80.ex
|
badubizzle/icd_code
|
4c625733f92b7b1d616e272abc3009bb8b916c0c
|
[
"Apache-2.0"
] | null | null | null |
lib/codes/codes_m80.ex
|
badubizzle/icd_code
|
4c625733f92b7b1d616e272abc3009bb8b916c0c
|
[
"Apache-2.0"
] | null | null | null |
defmodule IcdCode.ICDCode.Codes_M80 do
alias IcdCode.ICDCode
def _M8000XA do
%ICDCode{full_code: "M8000XA",
category_code: "M80",
short_code: "00XA",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified site, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified site, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified site, initial encounter for fracture"
}
end
def _M8000XD do
%ICDCode{full_code: "M8000XD",
category_code: "M80",
short_code: "00XD",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with routine healing"
}
end
def _M8000XG do
%ICDCode{full_code: "M8000XG",
category_code: "M80",
short_code: "00XG",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with delayed healing"
}
end
def _M8000XK do
%ICDCode{full_code: "M8000XK",
category_code: "M80",
short_code: "00XK",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with nonunion"
}
end
def _M8000XP do
%ICDCode{full_code: "M8000XP",
category_code: "M80",
short_code: "00XP",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with malunion"
}
end
def _M8000XS do
%ICDCode{full_code: "M8000XS",
category_code: "M80",
short_code: "00XS",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified site, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified site, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified site, sequela"
}
end
def _M80011A do
%ICDCode{full_code: "M80011A",
category_code: "M80",
short_code: "011A",
full_name: "Age-related osteoporosis with current pathological fracture, right shoulder, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right shoulder, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right shoulder, initial encounter for fracture"
}
end
def _M80011D do
%ICDCode{full_code: "M80011D",
category_code: "M80",
short_code: "011D",
full_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with routine healing"
}
end
def _M80011G do
%ICDCode{full_code: "M80011G",
category_code: "M80",
short_code: "011G",
full_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with delayed healing"
}
end
def _M80011K do
%ICDCode{full_code: "M80011K",
category_code: "M80",
short_code: "011K",
full_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with nonunion"
}
end
def _M80011P do
%ICDCode{full_code: "M80011P",
category_code: "M80",
short_code: "011P",
full_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with malunion"
}
end
def _M80011S do
%ICDCode{full_code: "M80011S",
category_code: "M80",
short_code: "011S",
full_name: "Age-related osteoporosis with current pathological fracture, right shoulder, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right shoulder, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right shoulder, sequela"
}
end
def _M80012A do
%ICDCode{full_code: "M80012A",
category_code: "M80",
short_code: "012A",
full_name: "Age-related osteoporosis with current pathological fracture, left shoulder, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left shoulder, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left shoulder, initial encounter for fracture"
}
end
def _M80012D do
%ICDCode{full_code: "M80012D",
category_code: "M80",
short_code: "012D",
full_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with routine healing"
}
end
def _M80012G do
%ICDCode{full_code: "M80012G",
category_code: "M80",
short_code: "012G",
full_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with delayed healing"
}
end
def _M80012K do
%ICDCode{full_code: "M80012K",
category_code: "M80",
short_code: "012K",
full_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with nonunion"
}
end
def _M80012P do
%ICDCode{full_code: "M80012P",
category_code: "M80",
short_code: "012P",
full_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with malunion"
}
end
def _M80012S do
%ICDCode{full_code: "M80012S",
category_code: "M80",
short_code: "012S",
full_name: "Age-related osteoporosis with current pathological fracture, left shoulder, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left shoulder, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left shoulder, sequela"
}
end
def _M80019A do
%ICDCode{full_code: "M80019A",
category_code: "M80",
short_code: "019A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, initial encounter for fracture"
}
end
def _M80019D do
%ICDCode{full_code: "M80019D",
category_code: "M80",
short_code: "019D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with routine healing"
}
end
def _M80019G do
%ICDCode{full_code: "M80019G",
category_code: "M80",
short_code: "019G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with delayed healing"
}
end
def _M80019K do
%ICDCode{full_code: "M80019K",
category_code: "M80",
short_code: "019K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with nonunion"
}
end
def _M80019P do
%ICDCode{full_code: "M80019P",
category_code: "M80",
short_code: "019P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with malunion"
}
end
def _M80019S do
%ICDCode{full_code: "M80019S",
category_code: "M80",
short_code: "019S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified shoulder, sequela"
}
end
def _M80021A do
%ICDCode{full_code: "M80021A",
category_code: "M80",
short_code: "021A",
full_name: "Age-related osteoporosis with current pathological fracture, right humerus, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right humerus, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right humerus, initial encounter for fracture"
}
end
def _M80021D do
%ICDCode{full_code: "M80021D",
category_code: "M80",
short_code: "021D",
full_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with routine healing"
}
end
def _M80021G do
%ICDCode{full_code: "M80021G",
category_code: "M80",
short_code: "021G",
full_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with delayed healing"
}
end
def _M80021K do
%ICDCode{full_code: "M80021K",
category_code: "M80",
short_code: "021K",
full_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with nonunion"
}
end
def _M80021P do
%ICDCode{full_code: "M80021P",
category_code: "M80",
short_code: "021P",
full_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with malunion"
}
end
def _M80021S do
%ICDCode{full_code: "M80021S",
category_code: "M80",
short_code: "021S",
full_name: "Age-related osteoporosis with current pathological fracture, right humerus, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right humerus, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right humerus, sequela"
}
end
def _M80022A do
%ICDCode{full_code: "M80022A",
category_code: "M80",
short_code: "022A",
full_name: "Age-related osteoporosis with current pathological fracture, left humerus, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left humerus, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left humerus, initial encounter for fracture"
}
end
def _M80022D do
%ICDCode{full_code: "M80022D",
category_code: "M80",
short_code: "022D",
full_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with routine healing"
}
end
def _M80022G do
%ICDCode{full_code: "M80022G",
category_code: "M80",
short_code: "022G",
full_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with delayed healing"
}
end
def _M80022K do
%ICDCode{full_code: "M80022K",
category_code: "M80",
short_code: "022K",
full_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with nonunion"
}
end
def _M80022P do
%ICDCode{full_code: "M80022P",
category_code: "M80",
short_code: "022P",
full_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with malunion"
}
end
def _M80022S do
%ICDCode{full_code: "M80022S",
category_code: "M80",
short_code: "022S",
full_name: "Age-related osteoporosis with current pathological fracture, left humerus, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left humerus, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left humerus, sequela"
}
end
def _M80029A do
%ICDCode{full_code: "M80029A",
category_code: "M80",
short_code: "029A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, initial encounter for fracture"
}
end
def _M80029D do
%ICDCode{full_code: "M80029D",
category_code: "M80",
short_code: "029D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with routine healing"
}
end
def _M80029G do
%ICDCode{full_code: "M80029G",
category_code: "M80",
short_code: "029G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with delayed healing"
}
end
def _M80029K do
%ICDCode{full_code: "M80029K",
category_code: "M80",
short_code: "029K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with nonunion"
}
end
def _M80029P do
%ICDCode{full_code: "M80029P",
category_code: "M80",
short_code: "029P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with malunion"
}
end
def _M80029S do
%ICDCode{full_code: "M80029S",
category_code: "M80",
short_code: "029S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified humerus, sequela"
}
end
def _M80031A do
%ICDCode{full_code: "M80031A",
category_code: "M80",
short_code: "031A",
full_name: "Age-related osteoporosis with current pathological fracture, right forearm, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right forearm, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right forearm, initial encounter for fracture"
}
end
def _M80031D do
%ICDCode{full_code: "M80031D",
category_code: "M80",
short_code: "031D",
full_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with routine healing"
}
end
def _M80031G do
%ICDCode{full_code: "M80031G",
category_code: "M80",
short_code: "031G",
full_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with delayed healing"
}
end
def _M80031K do
%ICDCode{full_code: "M80031K",
category_code: "M80",
short_code: "031K",
full_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with nonunion"
}
end
def _M80031P do
%ICDCode{full_code: "M80031P",
category_code: "M80",
short_code: "031P",
full_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with malunion"
}
end
def _M80031S do
%ICDCode{full_code: "M80031S",
category_code: "M80",
short_code: "031S",
full_name: "Age-related osteoporosis with current pathological fracture, right forearm, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right forearm, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right forearm, sequela"
}
end
def _M80032A do
%ICDCode{full_code: "M80032A",
category_code: "M80",
short_code: "032A",
full_name: "Age-related osteoporosis with current pathological fracture, left forearm, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left forearm, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left forearm, initial encounter for fracture"
}
end
def _M80032D do
%ICDCode{full_code: "M80032D",
category_code: "M80",
short_code: "032D",
full_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with routine healing"
}
end
def _M80032G do
%ICDCode{full_code: "M80032G",
category_code: "M80",
short_code: "032G",
full_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with delayed healing"
}
end
def _M80032K do
%ICDCode{full_code: "M80032K",
category_code: "M80",
short_code: "032K",
full_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with nonunion"
}
end
def _M80032P do
%ICDCode{full_code: "M80032P",
category_code: "M80",
short_code: "032P",
full_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with malunion"
}
end
def _M80032S do
%ICDCode{full_code: "M80032S",
category_code: "M80",
short_code: "032S",
full_name: "Age-related osteoporosis with current pathological fracture, left forearm, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left forearm, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left forearm, sequela"
}
end
def _M80039A do
%ICDCode{full_code: "M80039A",
category_code: "M80",
short_code: "039A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, initial encounter for fracture"
}
end
def _M80039D do
%ICDCode{full_code: "M80039D",
category_code: "M80",
short_code: "039D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with routine healing"
}
end
def _M80039G do
%ICDCode{full_code: "M80039G",
category_code: "M80",
short_code: "039G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with delayed healing"
}
end
def _M80039K do
%ICDCode{full_code: "M80039K",
category_code: "M80",
short_code: "039K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with nonunion"
}
end
def _M80039P do
%ICDCode{full_code: "M80039P",
category_code: "M80",
short_code: "039P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with malunion"
}
end
def _M80039S do
%ICDCode{full_code: "M80039S",
category_code: "M80",
short_code: "039S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified forearm, sequela"
}
end
def _M80041A do
%ICDCode{full_code: "M80041A",
category_code: "M80",
short_code: "041A",
full_name: "Age-related osteoporosis with current pathological fracture, right hand, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right hand, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right hand, initial encounter for fracture"
}
end
def _M80041D do
%ICDCode{full_code: "M80041D",
category_code: "M80",
short_code: "041D",
full_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with routine healing"
}
end
def _M80041G do
%ICDCode{full_code: "M80041G",
category_code: "M80",
short_code: "041G",
full_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with delayed healing"
}
end
def _M80041K do
%ICDCode{full_code: "M80041K",
category_code: "M80",
short_code: "041K",
full_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with nonunion"
}
end
def _M80041P do
%ICDCode{full_code: "M80041P",
category_code: "M80",
short_code: "041P",
full_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with malunion"
}
end
def _M80041S do
%ICDCode{full_code: "M80041S",
category_code: "M80",
short_code: "041S",
full_name: "Age-related osteoporosis with current pathological fracture, right hand, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right hand, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right hand, sequela"
}
end
def _M80042A do
%ICDCode{full_code: "M80042A",
category_code: "M80",
short_code: "042A",
full_name: "Age-related osteoporosis with current pathological fracture, left hand, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left hand, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left hand, initial encounter for fracture"
}
end
def _M80042D do
%ICDCode{full_code: "M80042D",
category_code: "M80",
short_code: "042D",
full_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with routine healing"
}
end
def _M80042G do
%ICDCode{full_code: "M80042G",
category_code: "M80",
short_code: "042G",
full_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with delayed healing"
}
end
def _M80042K do
%ICDCode{full_code: "M80042K",
category_code: "M80",
short_code: "042K",
full_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with nonunion"
}
end
def _M80042P do
%ICDCode{full_code: "M80042P",
category_code: "M80",
short_code: "042P",
full_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with malunion"
}
end
def _M80042S do
%ICDCode{full_code: "M80042S",
category_code: "M80",
short_code: "042S",
full_name: "Age-related osteoporosis with current pathological fracture, left hand, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left hand, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left hand, sequela"
}
end
def _M80049A do
%ICDCode{full_code: "M80049A",
category_code: "M80",
short_code: "049A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, initial encounter for fracture"
}
end
def _M80049D do
%ICDCode{full_code: "M80049D",
category_code: "M80",
short_code: "049D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with routine healing"
}
end
def _M80049G do
%ICDCode{full_code: "M80049G",
category_code: "M80",
short_code: "049G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with delayed healing"
}
end
def _M80049K do
%ICDCode{full_code: "M80049K",
category_code: "M80",
short_code: "049K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with nonunion"
}
end
def _M80049P do
%ICDCode{full_code: "M80049P",
category_code: "M80",
short_code: "049P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with malunion"
}
end
def _M80049S do
%ICDCode{full_code: "M80049S",
category_code: "M80",
short_code: "049S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified hand, sequela"
}
end
def _M80051A do
%ICDCode{full_code: "M80051A",
category_code: "M80",
short_code: "051A",
full_name: "Age-related osteoporosis with current pathological fracture, right femur, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right femur, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right femur, initial encounter for fracture"
}
end
def _M80051D do
%ICDCode{full_code: "M80051D",
category_code: "M80",
short_code: "051D",
full_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with routine healing"
}
end
def _M80051G do
%ICDCode{full_code: "M80051G",
category_code: "M80",
short_code: "051G",
full_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with delayed healing"
}
end
def _M80051K do
%ICDCode{full_code: "M80051K",
category_code: "M80",
short_code: "051K",
full_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with nonunion"
}
end
def _M80051P do
%ICDCode{full_code: "M80051P",
category_code: "M80",
short_code: "051P",
full_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with malunion"
}
end
def _M80051S do
%ICDCode{full_code: "M80051S",
category_code: "M80",
short_code: "051S",
full_name: "Age-related osteoporosis with current pathological fracture, right femur, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right femur, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right femur, sequela"
}
end
def _M80052A do
%ICDCode{full_code: "M80052A",
category_code: "M80",
short_code: "052A",
full_name: "Age-related osteoporosis with current pathological fracture, left femur, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left femur, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left femur, initial encounter for fracture"
}
end
def _M80052D do
%ICDCode{full_code: "M80052D",
category_code: "M80",
short_code: "052D",
full_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with routine healing"
}
end
def _M80052G do
%ICDCode{full_code: "M80052G",
category_code: "M80",
short_code: "052G",
full_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with delayed healing"
}
end
def _M80052K do
%ICDCode{full_code: "M80052K",
category_code: "M80",
short_code: "052K",
full_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with nonunion"
}
end
def _M80052P do
%ICDCode{full_code: "M80052P",
category_code: "M80",
short_code: "052P",
full_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with malunion"
}
end
def _M80052S do
%ICDCode{full_code: "M80052S",
category_code: "M80",
short_code: "052S",
full_name: "Age-related osteoporosis with current pathological fracture, left femur, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left femur, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left femur, sequela"
}
end
def _M80059A do
%ICDCode{full_code: "M80059A",
category_code: "M80",
short_code: "059A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, initial encounter for fracture"
}
end
def _M80059D do
%ICDCode{full_code: "M80059D",
category_code: "M80",
short_code: "059D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with routine healing"
}
end
def _M80059G do
%ICDCode{full_code: "M80059G",
category_code: "M80",
short_code: "059G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with delayed healing"
}
end
def _M80059K do
%ICDCode{full_code: "M80059K",
category_code: "M80",
short_code: "059K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with nonunion"
}
end
def _M80059P do
%ICDCode{full_code: "M80059P",
category_code: "M80",
short_code: "059P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with malunion"
}
end
def _M80059S do
%ICDCode{full_code: "M80059S",
category_code: "M80",
short_code: "059S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified femur, sequela"
}
end
def _M80061A do
%ICDCode{full_code: "M80061A",
category_code: "M80",
short_code: "061A",
full_name: "Age-related osteoporosis with current pathological fracture, right lower leg, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right lower leg, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right lower leg, initial encounter for fracture"
}
end
def _M80061D do
%ICDCode{full_code: "M80061D",
category_code: "M80",
short_code: "061D",
full_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with routine healing"
}
end
def _M80061G do
%ICDCode{full_code: "M80061G",
category_code: "M80",
short_code: "061G",
full_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with delayed healing"
}
end
def _M80061K do
%ICDCode{full_code: "M80061K",
category_code: "M80",
short_code: "061K",
full_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with nonunion"
}
end
def _M80061P do
%ICDCode{full_code: "M80061P",
category_code: "M80",
short_code: "061P",
full_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with malunion"
}
end
def _M80061S do
%ICDCode{full_code: "M80061S",
category_code: "M80",
short_code: "061S",
full_name: "Age-related osteoporosis with current pathological fracture, right lower leg, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right lower leg, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right lower leg, sequela"
}
end
def _M80062A do
%ICDCode{full_code: "M80062A",
category_code: "M80",
short_code: "062A",
full_name: "Age-related osteoporosis with current pathological fracture, left lower leg, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left lower leg, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left lower leg, initial encounter for fracture"
}
end
def _M80062D do
%ICDCode{full_code: "M80062D",
category_code: "M80",
short_code: "062D",
full_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with routine healing"
}
end
def _M80062G do
%ICDCode{full_code: "M80062G",
category_code: "M80",
short_code: "062G",
full_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with delayed healing"
}
end
def _M80062K do
%ICDCode{full_code: "M80062K",
category_code: "M80",
short_code: "062K",
full_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with nonunion"
}
end
def _M80062P do
%ICDCode{full_code: "M80062P",
category_code: "M80",
short_code: "062P",
full_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with malunion"
}
end
def _M80062S do
%ICDCode{full_code: "M80062S",
category_code: "M80",
short_code: "062S",
full_name: "Age-related osteoporosis with current pathological fracture, left lower leg, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left lower leg, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left lower leg, sequela"
}
end
def _M80069A do
%ICDCode{full_code: "M80069A",
category_code: "M80",
short_code: "069A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, initial encounter for fracture"
}
end
def _M80069D do
%ICDCode{full_code: "M80069D",
category_code: "M80",
short_code: "069D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with routine healing"
}
end
def _M80069G do
%ICDCode{full_code: "M80069G",
category_code: "M80",
short_code: "069G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with delayed healing"
}
end
def _M80069K do
%ICDCode{full_code: "M80069K",
category_code: "M80",
short_code: "069K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with nonunion"
}
end
def _M80069P do
%ICDCode{full_code: "M80069P",
category_code: "M80",
short_code: "069P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with malunion"
}
end
def _M80069S do
%ICDCode{full_code: "M80069S",
category_code: "M80",
short_code: "069S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified lower leg, sequela"
}
end
def _M80071A do
%ICDCode{full_code: "M80071A",
category_code: "M80",
short_code: "071A",
full_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, initial encounter for fracture"
}
end
def _M80071D do
%ICDCode{full_code: "M80071D",
category_code: "M80",
short_code: "071D",
full_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with routine healing"
}
end
def _M80071G do
%ICDCode{full_code: "M80071G",
category_code: "M80",
short_code: "071G",
full_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with delayed healing"
}
end
def _M80071K do
%ICDCode{full_code: "M80071K",
category_code: "M80",
short_code: "071K",
full_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with nonunion"
}
end
def _M80071P do
%ICDCode{full_code: "M80071P",
category_code: "M80",
short_code: "071P",
full_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with malunion"
}
end
def _M80071S do
%ICDCode{full_code: "M80071S",
category_code: "M80",
short_code: "071S",
full_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, right ankle and foot, sequela"
}
end
def _M80072A do
%ICDCode{full_code: "M80072A",
category_code: "M80",
short_code: "072A",
full_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, initial encounter for fracture"
}
end
def _M80072D do
%ICDCode{full_code: "M80072D",
category_code: "M80",
short_code: "072D",
full_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with routine healing"
}
end
def _M80072G do
%ICDCode{full_code: "M80072G",
category_code: "M80",
short_code: "072G",
full_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with delayed healing"
}
end
def _M80072K do
%ICDCode{full_code: "M80072K",
category_code: "M80",
short_code: "072K",
full_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with nonunion"
}
end
def _M80072P do
%ICDCode{full_code: "M80072P",
category_code: "M80",
short_code: "072P",
full_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with malunion"
}
end
def _M80072S do
%ICDCode{full_code: "M80072S",
category_code: "M80",
short_code: "072S",
full_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, left ankle and foot, sequela"
}
end
def _M80079A do
%ICDCode{full_code: "M80079A",
category_code: "M80",
short_code: "079A",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, initial encounter for fracture"
}
end
def _M80079D do
%ICDCode{full_code: "M80079D",
category_code: "M80",
short_code: "079D",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with routine healing"
}
end
def _M80079G do
%ICDCode{full_code: "M80079G",
category_code: "M80",
short_code: "079G",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with delayed healing"
}
end
def _M80079K do
%ICDCode{full_code: "M80079K",
category_code: "M80",
short_code: "079K",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with nonunion"
}
end
def _M80079P do
%ICDCode{full_code: "M80079P",
category_code: "M80",
short_code: "079P",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with malunion"
}
end
def _M80079S do
%ICDCode{full_code: "M80079S",
category_code: "M80",
short_code: "079S",
full_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, sequela",
short_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, sequela",
category_name: "Age-related osteoporosis with current pathological fracture, unspecified ankle and foot, sequela"
}
end
def _M8008XA do
%ICDCode{full_code: "M8008XA",
category_code: "M80",
short_code: "08XA",
full_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), initial encounter for fracture",
short_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), initial encounter for fracture",
category_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), initial encounter for fracture"
}
end
def _M8008XD do
%ICDCode{full_code: "M8008XD",
category_code: "M80",
short_code: "08XD",
full_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with routine healing",
short_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with routine healing",
category_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with routine healing"
}
end
def _M8008XG do
%ICDCode{full_code: "M8008XG",
category_code: "M80",
short_code: "08XG",
full_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with delayed healing",
short_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with delayed healing",
category_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with delayed healing"
}
end
def _M8008XK do
%ICDCode{full_code: "M8008XK",
category_code: "M80",
short_code: "08XK",
full_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with nonunion",
short_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with nonunion",
category_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with nonunion"
}
end
def _M8008XP do
%ICDCode{full_code: "M8008XP",
category_code: "M80",
short_code: "08XP",
full_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with malunion",
short_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with malunion",
category_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with malunion"
}
end
def _M8008XS do
%ICDCode{full_code: "M8008XS",
category_code: "M80",
short_code: "08XS",
full_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), sequela",
short_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), sequela",
category_name: "Age-related osteoporosis with current pathological fracture, vertebra(e), sequela"
}
end
def _M8080XA do
%ICDCode{full_code: "M8080XA",
category_code: "M80",
short_code: "80XA",
full_name: "Other osteoporosis with current pathological fracture, unspecified site, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified site, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified site, initial encounter for fracture"
}
end
def _M8080XD do
%ICDCode{full_code: "M8080XD",
category_code: "M80",
short_code: "80XD",
full_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with routine healing"
}
end
def _M8080XG do
%ICDCode{full_code: "M8080XG",
category_code: "M80",
short_code: "80XG",
full_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with delayed healing"
}
end
def _M8080XK do
%ICDCode{full_code: "M8080XK",
category_code: "M80",
short_code: "80XK",
full_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with nonunion"
}
end
def _M8080XP do
%ICDCode{full_code: "M8080XP",
category_code: "M80",
short_code: "80XP",
full_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified site, subsequent encounter for fracture with malunion"
}
end
def _M8080XS do
%ICDCode{full_code: "M8080XS",
category_code: "M80",
short_code: "80XS",
full_name: "Other osteoporosis with current pathological fracture, unspecified site, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified site, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified site, sequela"
}
end
def _M80811A do
%ICDCode{full_code: "M80811A",
category_code: "M80",
short_code: "811A",
full_name: "Other osteoporosis with current pathological fracture, right shoulder, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right shoulder, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right shoulder, initial encounter for fracture"
}
end
def _M80811D do
%ICDCode{full_code: "M80811D",
category_code: "M80",
short_code: "811D",
full_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with routine healing"
}
end
def _M80811G do
%ICDCode{full_code: "M80811G",
category_code: "M80",
short_code: "811G",
full_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with delayed healing"
}
end
def _M80811K do
%ICDCode{full_code: "M80811K",
category_code: "M80",
short_code: "811K",
full_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with nonunion"
}
end
def _M80811P do
%ICDCode{full_code: "M80811P",
category_code: "M80",
short_code: "811P",
full_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right shoulder, subsequent encounter for fracture with malunion"
}
end
def _M80811S do
%ICDCode{full_code: "M80811S",
category_code: "M80",
short_code: "811S",
full_name: "Other osteoporosis with current pathological fracture, right shoulder, sequela",
short_name: "Other osteoporosis with current pathological fracture, right shoulder, sequela",
category_name: "Other osteoporosis with current pathological fracture, right shoulder, sequela"
}
end
def _M80812A do
%ICDCode{full_code: "M80812A",
category_code: "M80",
short_code: "812A",
full_name: "Other osteoporosis with current pathological fracture, left shoulder, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left shoulder, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left shoulder, initial encounter for fracture"
}
end
def _M80812D do
%ICDCode{full_code: "M80812D",
category_code: "M80",
short_code: "812D",
full_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with routine healing"
}
end
def _M80812G do
%ICDCode{full_code: "M80812G",
category_code: "M80",
short_code: "812G",
full_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with delayed healing"
}
end
def _M80812K do
%ICDCode{full_code: "M80812K",
category_code: "M80",
short_code: "812K",
full_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with nonunion"
}
end
def _M80812P do
%ICDCode{full_code: "M80812P",
category_code: "M80",
short_code: "812P",
full_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left shoulder, subsequent encounter for fracture with malunion"
}
end
def _M80812S do
%ICDCode{full_code: "M80812S",
category_code: "M80",
short_code: "812S",
full_name: "Other osteoporosis with current pathological fracture, left shoulder, sequela",
short_name: "Other osteoporosis with current pathological fracture, left shoulder, sequela",
category_name: "Other osteoporosis with current pathological fracture, left shoulder, sequela"
}
end
def _M80819A do
%ICDCode{full_code: "M80819A",
category_code: "M80",
short_code: "819A",
full_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, initial encounter for fracture"
}
end
def _M80819D do
%ICDCode{full_code: "M80819D",
category_code: "M80",
short_code: "819D",
full_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with routine healing"
}
end
def _M80819G do
%ICDCode{full_code: "M80819G",
category_code: "M80",
short_code: "819G",
full_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with delayed healing"
}
end
def _M80819K do
%ICDCode{full_code: "M80819K",
category_code: "M80",
short_code: "819K",
full_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with nonunion"
}
end
def _M80819P do
%ICDCode{full_code: "M80819P",
category_code: "M80",
short_code: "819P",
full_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, subsequent encounter for fracture with malunion"
}
end
def _M80819S do
%ICDCode{full_code: "M80819S",
category_code: "M80",
short_code: "819S",
full_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified shoulder, sequela"
}
end
def _M80821A do
%ICDCode{full_code: "M80821A",
category_code: "M80",
short_code: "821A",
full_name: "Other osteoporosis with current pathological fracture, right humerus, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right humerus, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right humerus, initial encounter for fracture"
}
end
def _M80821D do
%ICDCode{full_code: "M80821D",
category_code: "M80",
short_code: "821D",
full_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with routine healing"
}
end
def _M80821G do
%ICDCode{full_code: "M80821G",
category_code: "M80",
short_code: "821G",
full_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with delayed healing"
}
end
def _M80821K do
%ICDCode{full_code: "M80821K",
category_code: "M80",
short_code: "821K",
full_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with nonunion"
}
end
def _M80821P do
%ICDCode{full_code: "M80821P",
category_code: "M80",
short_code: "821P",
full_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right humerus, subsequent encounter for fracture with malunion"
}
end
def _M80821S do
%ICDCode{full_code: "M80821S",
category_code: "M80",
short_code: "821S",
full_name: "Other osteoporosis with current pathological fracture, right humerus, sequela",
short_name: "Other osteoporosis with current pathological fracture, right humerus, sequela",
category_name: "Other osteoporosis with current pathological fracture, right humerus, sequela"
}
end
def _M80822A do
%ICDCode{full_code: "M80822A",
category_code: "M80",
short_code: "822A",
full_name: "Other osteoporosis with current pathological fracture, left humerus, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left humerus, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left humerus, initial encounter for fracture"
}
end
def _M80822D do
%ICDCode{full_code: "M80822D",
category_code: "M80",
short_code: "822D",
full_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with routine healing"
}
end
def _M80822G do
%ICDCode{full_code: "M80822G",
category_code: "M80",
short_code: "822G",
full_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with delayed healing"
}
end
def _M80822K do
%ICDCode{full_code: "M80822K",
category_code: "M80",
short_code: "822K",
full_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with nonunion"
}
end
def _M80822P do
%ICDCode{full_code: "M80822P",
category_code: "M80",
short_code: "822P",
full_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left humerus, subsequent encounter for fracture with malunion"
}
end
def _M80822S do
%ICDCode{full_code: "M80822S",
category_code: "M80",
short_code: "822S",
full_name: "Other osteoporosis with current pathological fracture, left humerus, sequela",
short_name: "Other osteoporosis with current pathological fracture, left humerus, sequela",
category_name: "Other osteoporosis with current pathological fracture, left humerus, sequela"
}
end
def _M80829A do
%ICDCode{full_code: "M80829A",
category_code: "M80",
short_code: "829A",
full_name: "Other osteoporosis with current pathological fracture, unspecified humerus, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified humerus, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified humerus, initial encounter for fracture"
}
end
def _M80829D do
%ICDCode{full_code: "M80829D",
category_code: "M80",
short_code: "829D",
full_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with routine healing"
}
end
def _M80829G do
%ICDCode{full_code: "M80829G",
category_code: "M80",
short_code: "829G",
full_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with delayed healing"
}
end
def _M80829K do
%ICDCode{full_code: "M80829K",
category_code: "M80",
short_code: "829K",
full_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with nonunion"
}
end
def _M80829P do
%ICDCode{full_code: "M80829P",
category_code: "M80",
short_code: "829P",
full_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified humerus, subsequent encounter for fracture with malunion"
}
end
def _M80829S do
%ICDCode{full_code: "M80829S",
category_code: "M80",
short_code: "829S",
full_name: "Other osteoporosis with current pathological fracture, unspecified humerus, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified humerus, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified humerus, sequela"
}
end
def _M80831A do
%ICDCode{full_code: "M80831A",
category_code: "M80",
short_code: "831A",
full_name: "Other osteoporosis with current pathological fracture, right forearm, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right forearm, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right forearm, initial encounter for fracture"
}
end
def _M80831D do
%ICDCode{full_code: "M80831D",
category_code: "M80",
short_code: "831D",
full_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with routine healing"
}
end
def _M80831G do
%ICDCode{full_code: "M80831G",
category_code: "M80",
short_code: "831G",
full_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with delayed healing"
}
end
def _M80831K do
%ICDCode{full_code: "M80831K",
category_code: "M80",
short_code: "831K",
full_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with nonunion"
}
end
def _M80831P do
%ICDCode{full_code: "M80831P",
category_code: "M80",
short_code: "831P",
full_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right forearm, subsequent encounter for fracture with malunion"
}
end
def _M80831S do
%ICDCode{full_code: "M80831S",
category_code: "M80",
short_code: "831S",
full_name: "Other osteoporosis with current pathological fracture, right forearm, sequela",
short_name: "Other osteoporosis with current pathological fracture, right forearm, sequela",
category_name: "Other osteoporosis with current pathological fracture, right forearm, sequela"
}
end
def _M80832A do
%ICDCode{full_code: "M80832A",
category_code: "M80",
short_code: "832A",
full_name: "Other osteoporosis with current pathological fracture, left forearm, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left forearm, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left forearm, initial encounter for fracture"
}
end
def _M80832D do
%ICDCode{full_code: "M80832D",
category_code: "M80",
short_code: "832D",
full_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with routine healing"
}
end
def _M80832G do
%ICDCode{full_code: "M80832G",
category_code: "M80",
short_code: "832G",
full_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with delayed healing"
}
end
def _M80832K do
%ICDCode{full_code: "M80832K",
category_code: "M80",
short_code: "832K",
full_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with nonunion"
}
end
def _M80832P do
%ICDCode{full_code: "M80832P",
category_code: "M80",
short_code: "832P",
full_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left forearm, subsequent encounter for fracture with malunion"
}
end
def _M80832S do
%ICDCode{full_code: "M80832S",
category_code: "M80",
short_code: "832S",
full_name: "Other osteoporosis with current pathological fracture, left forearm, sequela",
short_name: "Other osteoporosis with current pathological fracture, left forearm, sequela",
category_name: "Other osteoporosis with current pathological fracture, left forearm, sequela"
}
end
def _M80839A do
%ICDCode{full_code: "M80839A",
category_code: "M80",
short_code: "839A",
full_name: "Other osteoporosis with current pathological fracture, unspecified forearm, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified forearm, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified forearm, initial encounter for fracture"
}
end
def _M80839D do
%ICDCode{full_code: "M80839D",
category_code: "M80",
short_code: "839D",
full_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with routine healing"
}
end
def _M80839G do
%ICDCode{full_code: "M80839G",
category_code: "M80",
short_code: "839G",
full_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with delayed healing"
}
end
def _M80839K do
%ICDCode{full_code: "M80839K",
category_code: "M80",
short_code: "839K",
full_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with nonunion"
}
end
def _M80839P do
%ICDCode{full_code: "M80839P",
category_code: "M80",
short_code: "839P",
full_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified forearm, subsequent encounter for fracture with malunion"
}
end
def _M80839S do
%ICDCode{full_code: "M80839S",
category_code: "M80",
short_code: "839S",
full_name: "Other osteoporosis with current pathological fracture, unspecified forearm, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified forearm, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified forearm, sequela"
}
end
def _M80841A do
%ICDCode{full_code: "M80841A",
category_code: "M80",
short_code: "841A",
full_name: "Other osteoporosis with current pathological fracture, right hand, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right hand, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right hand, initial encounter for fracture"
}
end
def _M80841D do
%ICDCode{full_code: "M80841D",
category_code: "M80",
short_code: "841D",
full_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with routine healing"
}
end
def _M80841G do
%ICDCode{full_code: "M80841G",
category_code: "M80",
short_code: "841G",
full_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with delayed healing"
}
end
def _M80841K do
%ICDCode{full_code: "M80841K",
category_code: "M80",
short_code: "841K",
full_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with nonunion"
}
end
def _M80841P do
%ICDCode{full_code: "M80841P",
category_code: "M80",
short_code: "841P",
full_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right hand, subsequent encounter for fracture with malunion"
}
end
def _M80841S do
%ICDCode{full_code: "M80841S",
category_code: "M80",
short_code: "841S",
full_name: "Other osteoporosis with current pathological fracture, right hand, sequela",
short_name: "Other osteoporosis with current pathological fracture, right hand, sequela",
category_name: "Other osteoporosis with current pathological fracture, right hand, sequela"
}
end
def _M80842A do
%ICDCode{full_code: "M80842A",
category_code: "M80",
short_code: "842A",
full_name: "Other osteoporosis with current pathological fracture, left hand, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left hand, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left hand, initial encounter for fracture"
}
end
def _M80842D do
%ICDCode{full_code: "M80842D",
category_code: "M80",
short_code: "842D",
full_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with routine healing"
}
end
def _M80842G do
%ICDCode{full_code: "M80842G",
category_code: "M80",
short_code: "842G",
full_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with delayed healing"
}
end
def _M80842K do
%ICDCode{full_code: "M80842K",
category_code: "M80",
short_code: "842K",
full_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with nonunion"
}
end
def _M80842P do
%ICDCode{full_code: "M80842P",
category_code: "M80",
short_code: "842P",
full_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left hand, subsequent encounter for fracture with malunion"
}
end
def _M80842S do
%ICDCode{full_code: "M80842S",
category_code: "M80",
short_code: "842S",
full_name: "Other osteoporosis with current pathological fracture, left hand, sequela",
short_name: "Other osteoporosis with current pathological fracture, left hand, sequela",
category_name: "Other osteoporosis with current pathological fracture, left hand, sequela"
}
end
def _M80849A do
%ICDCode{full_code: "M80849A",
category_code: "M80",
short_code: "849A",
full_name: "Other osteoporosis with current pathological fracture, unspecified hand, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified hand, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified hand, initial encounter for fracture"
}
end
def _M80849D do
%ICDCode{full_code: "M80849D",
category_code: "M80",
short_code: "849D",
full_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with routine healing"
}
end
def _M80849G do
%ICDCode{full_code: "M80849G",
category_code: "M80",
short_code: "849G",
full_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with delayed healing"
}
end
def _M80849K do
%ICDCode{full_code: "M80849K",
category_code: "M80",
short_code: "849K",
full_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with nonunion"
}
end
def _M80849P do
%ICDCode{full_code: "M80849P",
category_code: "M80",
short_code: "849P",
full_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified hand, subsequent encounter for fracture with malunion"
}
end
def _M80849S do
%ICDCode{full_code: "M80849S",
category_code: "M80",
short_code: "849S",
full_name: "Other osteoporosis with current pathological fracture, unspecified hand, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified hand, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified hand, sequela"
}
end
def _M80851A do
%ICDCode{full_code: "M80851A",
category_code: "M80",
short_code: "851A",
full_name: "Other osteoporosis with current pathological fracture, right femur, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right femur, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right femur, initial encounter for fracture"
}
end
def _M80851D do
%ICDCode{full_code: "M80851D",
category_code: "M80",
short_code: "851D",
full_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with routine healing"
}
end
def _M80851G do
%ICDCode{full_code: "M80851G",
category_code: "M80",
short_code: "851G",
full_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with delayed healing"
}
end
def _M80851K do
%ICDCode{full_code: "M80851K",
category_code: "M80",
short_code: "851K",
full_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with nonunion"
}
end
def _M80851P do
%ICDCode{full_code: "M80851P",
category_code: "M80",
short_code: "851P",
full_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right femur, subsequent encounter for fracture with malunion"
}
end
def _M80851S do
%ICDCode{full_code: "M80851S",
category_code: "M80",
short_code: "851S",
full_name: "Other osteoporosis with current pathological fracture, right femur, sequela",
short_name: "Other osteoporosis with current pathological fracture, right femur, sequela",
category_name: "Other osteoporosis with current pathological fracture, right femur, sequela"
}
end
def _M80852A do
%ICDCode{full_code: "M80852A",
category_code: "M80",
short_code: "852A",
full_name: "Other osteoporosis with current pathological fracture, left femur, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left femur, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left femur, initial encounter for fracture"
}
end
def _M80852D do
%ICDCode{full_code: "M80852D",
category_code: "M80",
short_code: "852D",
full_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with routine healing"
}
end
def _M80852G do
%ICDCode{full_code: "M80852G",
category_code: "M80",
short_code: "852G",
full_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with delayed healing"
}
end
def _M80852K do
%ICDCode{full_code: "M80852K",
category_code: "M80",
short_code: "852K",
full_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with nonunion"
}
end
def _M80852P do
%ICDCode{full_code: "M80852P",
category_code: "M80",
short_code: "852P",
full_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left femur, subsequent encounter for fracture with malunion"
}
end
def _M80852S do
%ICDCode{full_code: "M80852S",
category_code: "M80",
short_code: "852S",
full_name: "Other osteoporosis with current pathological fracture, left femur, sequela",
short_name: "Other osteoporosis with current pathological fracture, left femur, sequela",
category_name: "Other osteoporosis with current pathological fracture, left femur, sequela"
}
end
def _M80859A do
%ICDCode{full_code: "M80859A",
category_code: "M80",
short_code: "859A",
full_name: "Other osteoporosis with current pathological fracture, unspecified femur, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified femur, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified femur, initial encounter for fracture"
}
end
def _M80859D do
%ICDCode{full_code: "M80859D",
category_code: "M80",
short_code: "859D",
full_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with routine healing"
}
end
def _M80859G do
%ICDCode{full_code: "M80859G",
category_code: "M80",
short_code: "859G",
full_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with delayed healing"
}
end
def _M80859K do
%ICDCode{full_code: "M80859K",
category_code: "M80",
short_code: "859K",
full_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with nonunion"
}
end
def _M80859P do
%ICDCode{full_code: "M80859P",
category_code: "M80",
short_code: "859P",
full_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified femur, subsequent encounter for fracture with malunion"
}
end
def _M80859S do
%ICDCode{full_code: "M80859S",
category_code: "M80",
short_code: "859S",
full_name: "Other osteoporosis with current pathological fracture, unspecified femur, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified femur, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified femur, sequela"
}
end
def _M80861A do
%ICDCode{full_code: "M80861A",
category_code: "M80",
short_code: "861A",
full_name: "Other osteoporosis with current pathological fracture, right lower leg, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right lower leg, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right lower leg, initial encounter for fracture"
}
end
def _M80861D do
%ICDCode{full_code: "M80861D",
category_code: "M80",
short_code: "861D",
full_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with routine healing"
}
end
def _M80861G do
%ICDCode{full_code: "M80861G",
category_code: "M80",
short_code: "861G",
full_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with delayed healing"
}
end
def _M80861K do
%ICDCode{full_code: "M80861K",
category_code: "M80",
short_code: "861K",
full_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with nonunion"
}
end
def _M80861P do
%ICDCode{full_code: "M80861P",
category_code: "M80",
short_code: "861P",
full_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right lower leg, subsequent encounter for fracture with malunion"
}
end
def _M80861S do
%ICDCode{full_code: "M80861S",
category_code: "M80",
short_code: "861S",
full_name: "Other osteoporosis with current pathological fracture, right lower leg, sequela",
short_name: "Other osteoporosis with current pathological fracture, right lower leg, sequela",
category_name: "Other osteoporosis with current pathological fracture, right lower leg, sequela"
}
end
def _M80862A do
%ICDCode{full_code: "M80862A",
category_code: "M80",
short_code: "862A",
full_name: "Other osteoporosis with current pathological fracture, left lower leg, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left lower leg, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left lower leg, initial encounter for fracture"
}
end
def _M80862D do
%ICDCode{full_code: "M80862D",
category_code: "M80",
short_code: "862D",
full_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with routine healing"
}
end
def _M80862G do
%ICDCode{full_code: "M80862G",
category_code: "M80",
short_code: "862G",
full_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with delayed healing"
}
end
def _M80862K do
%ICDCode{full_code: "M80862K",
category_code: "M80",
short_code: "862K",
full_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with nonunion"
}
end
def _M80862P do
%ICDCode{full_code: "M80862P",
category_code: "M80",
short_code: "862P",
full_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left lower leg, subsequent encounter for fracture with malunion"
}
end
def _M80862S do
%ICDCode{full_code: "M80862S",
category_code: "M80",
short_code: "862S",
full_name: "Other osteoporosis with current pathological fracture, left lower leg, sequela",
short_name: "Other osteoporosis with current pathological fracture, left lower leg, sequela",
category_name: "Other osteoporosis with current pathological fracture, left lower leg, sequela"
}
end
def _M80869A do
%ICDCode{full_code: "M80869A",
category_code: "M80",
short_code: "869A",
full_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, initial encounter for fracture"
}
end
def _M80869D do
%ICDCode{full_code: "M80869D",
category_code: "M80",
short_code: "869D",
full_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with routine healing"
}
end
def _M80869G do
%ICDCode{full_code: "M80869G",
category_code: "M80",
short_code: "869G",
full_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with delayed healing"
}
end
def _M80869K do
%ICDCode{full_code: "M80869K",
category_code: "M80",
short_code: "869K",
full_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with nonunion"
}
end
def _M80869P do
%ICDCode{full_code: "M80869P",
category_code: "M80",
short_code: "869P",
full_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, subsequent encounter for fracture with malunion"
}
end
def _M80869S do
%ICDCode{full_code: "M80869S",
category_code: "M80",
short_code: "869S",
full_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified lower leg, sequela"
}
end
def _M80871A do
%ICDCode{full_code: "M80871A",
category_code: "M80",
short_code: "871A",
full_name: "Other osteoporosis with current pathological fracture, right ankle and foot, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, right ankle and foot, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, right ankle and foot, initial encounter for fracture"
}
end
def _M80871D do
%ICDCode{full_code: "M80871D",
category_code: "M80",
short_code: "871D",
full_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with routine healing"
}
end
def _M80871G do
%ICDCode{full_code: "M80871G",
category_code: "M80",
short_code: "871G",
full_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with delayed healing"
}
end
def _M80871K do
%ICDCode{full_code: "M80871K",
category_code: "M80",
short_code: "871K",
full_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with nonunion"
}
end
def _M80871P do
%ICDCode{full_code: "M80871P",
category_code: "M80",
short_code: "871P",
full_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, right ankle and foot, subsequent encounter for fracture with malunion"
}
end
def _M80871S do
%ICDCode{full_code: "M80871S",
category_code: "M80",
short_code: "871S",
full_name: "Other osteoporosis with current pathological fracture, right ankle and foot, sequela",
short_name: "Other osteoporosis with current pathological fracture, right ankle and foot, sequela",
category_name: "Other osteoporosis with current pathological fracture, right ankle and foot, sequela"
}
end
def _M80872A do
%ICDCode{full_code: "M80872A",
category_code: "M80",
short_code: "872A",
full_name: "Other osteoporosis with current pathological fracture, left ankle and foot, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, left ankle and foot, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, left ankle and foot, initial encounter for fracture"
}
end
def _M80872D do
%ICDCode{full_code: "M80872D",
category_code: "M80",
short_code: "872D",
full_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with routine healing"
}
end
def _M80872G do
%ICDCode{full_code: "M80872G",
category_code: "M80",
short_code: "872G",
full_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with delayed healing"
}
end
def _M80872K do
%ICDCode{full_code: "M80872K",
category_code: "M80",
short_code: "872K",
full_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with nonunion"
}
end
def _M80872P do
%ICDCode{full_code: "M80872P",
category_code: "M80",
short_code: "872P",
full_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, left ankle and foot, subsequent encounter for fracture with malunion"
}
end
def _M80872S do
%ICDCode{full_code: "M80872S",
category_code: "M80",
short_code: "872S",
full_name: "Other osteoporosis with current pathological fracture, left ankle and foot, sequela",
short_name: "Other osteoporosis with current pathological fracture, left ankle and foot, sequela",
category_name: "Other osteoporosis with current pathological fracture, left ankle and foot, sequela"
}
end
def _M80879A do
%ICDCode{full_code: "M80879A",
category_code: "M80",
short_code: "879A",
full_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, initial encounter for fracture"
}
end
def _M80879D do
%ICDCode{full_code: "M80879D",
category_code: "M80",
short_code: "879D",
full_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with routine healing"
}
end
def _M80879G do
%ICDCode{full_code: "M80879G",
category_code: "M80",
short_code: "879G",
full_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with delayed healing"
}
end
def _M80879K do
%ICDCode{full_code: "M80879K",
category_code: "M80",
short_code: "879K",
full_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with nonunion"
}
end
def _M80879P do
%ICDCode{full_code: "M80879P",
category_code: "M80",
short_code: "879P",
full_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, subsequent encounter for fracture with malunion"
}
end
def _M80879S do
%ICDCode{full_code: "M80879S",
category_code: "M80",
short_code: "879S",
full_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, sequela",
short_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, sequela",
category_name: "Other osteoporosis with current pathological fracture, unspecified ankle and foot, sequela"
}
end
def _M8088XA do
%ICDCode{full_code: "M8088XA",
category_code: "M80",
short_code: "88XA",
full_name: "Other osteoporosis with current pathological fracture, vertebra(e), initial encounter for fracture",
short_name: "Other osteoporosis with current pathological fracture, vertebra(e), initial encounter for fracture",
category_name: "Other osteoporosis with current pathological fracture, vertebra(e), initial encounter for fracture"
}
end
def _M8088XD do
%ICDCode{full_code: "M8088XD",
category_code: "M80",
short_code: "88XD",
full_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with routine healing",
short_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with routine healing",
category_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with routine healing"
}
end
def _M8088XG do
%ICDCode{full_code: "M8088XG",
category_code: "M80",
short_code: "88XG",
full_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with delayed healing",
short_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with delayed healing",
category_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with delayed healing"
}
end
def _M8088XK do
%ICDCode{full_code: "M8088XK",
category_code: "M80",
short_code: "88XK",
full_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with nonunion",
short_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with nonunion",
category_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with nonunion"
}
end
def _M8088XP do
%ICDCode{full_code: "M8088XP",
category_code: "M80",
short_code: "88XP",
full_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with malunion",
short_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with malunion",
category_name: "Other osteoporosis with current pathological fracture, vertebra(e), subsequent encounter for fracture with malunion"
}
end
def _M8088XS do
%ICDCode{full_code: "M8088XS",
category_code: "M80",
short_code: "88XS",
full_name: "Other osteoporosis with current pathological fracture, vertebra(e), sequela",
short_name: "Other osteoporosis with current pathological fracture, vertebra(e), sequela",
category_name: "Other osteoporosis with current pathological fracture, vertebra(e), sequela"
}
end
end
| 61.427138
| 170
| 0.723393
|
93a529ae12ab8ea404d674fc7ab30150f63f948b
| 1,995
|
exs
|
Elixir
|
config/prod.exs
|
anamba/webrtc_example
|
b539101d29ffeb52f551f263128a0884a5d6a7ae
|
[
"MIT"
] | 44
|
2016-01-16T07:28:43.000Z
|
2021-05-05T04:45:19.000Z
|
config/prod.exs
|
anamba/webrtc_example
|
b539101d29ffeb52f551f263128a0884a5d6a7ae
|
[
"MIT"
] | null | null | null |
config/prod.exs
|
anamba/webrtc_example
|
b539101d29ffeb52f551f263128a0884a5d6a7ae
|
[
"MIT"
] | 6
|
2016-11-11T20:40:34.000Z
|
2021-05-05T04:45:24.000Z
|
use Mix.Config
# For production, we configure the host to read the PORT
# from the system environment. Therefore, you will need
# to set PORT=80 before running your server.
#
# You should also configure the url host to something
# meaningful, we use this information when generating URLs.
#
# Finally, we also include the path to a manifest
# containing the digested version of static files. This
# manifest is generated by the mix phoenix.digest task
# which you typically run after static files are built.
config :webrtc_example, WebrtcExample.Endpoint,
http: [port: {:system, "PORT"}],
url: [host: "example.com", port: 80],
cache_static_manifest: "priv/static/manifest.json"
# Do not print debug messages in production
config :logger, level: :info
# ## SSL Support
#
# To get SSL working, you will need to add the `https` key
# to the previous section and set your `:url` port to 443:
#
# config :webrtc, Webrtc.Endpoint,
# ...
# url: [host: "example.com", port: 443],
# https: [port: 443,
# keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
# certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
#
# Where those two env variables return an absolute path to
# the key and cert in disk or a relative path inside priv,
# for example "priv/ssl/server.key".
#
# We also recommend setting `force_ssl`, ensuring no data is
# ever sent via http, always redirecting to https:
#
# config :webrtc, Webrtc.Endpoint,
# force_ssl: [hsts: true]
#
# Check `Plug.SSL` for all available options in `force_ssl`.
# ## Using releases
#
# If you are doing OTP releases, you need to instruct Phoenix
# to start the server for all endpoints:
#
# config :phoenix, :serve_endpoints, true
#
# Alternatively, you can configure exactly which server to
# start per endpoint:
#
# config :webrtc, Webrtc.Endpoint, server: true
#
# Finally import the config/prod.secret.exs
# which should be versioned separately.
import_config "prod.secret.exs"
| 32.177419
| 67
| 0.714286
|
93a54adb05341f66ade5d8f6a311b4386206e4a4
| 725
|
ex
|
Elixir
|
lib/erflow/model/dags.ex
|
roi-levoso/erflow
|
e8683fd93720703ea706af8f2317376dba3b401f
|
[
"MIT"
] | null | null | null |
lib/erflow/model/dags.ex
|
roi-levoso/erflow
|
e8683fd93720703ea706af8f2317376dba3b401f
|
[
"MIT"
] | null | null | null |
lib/erflow/model/dags.ex
|
roi-levoso/erflow
|
e8683fd93720703ea706af8f2317376dba3b401f
|
[
"MIT"
] | null | null | null |
defmodule Erflow.Model.Dag do
use Ecto.Schema
import Ecto.Changeset
# TODO Think about dag versioning
@already_exists "ALREADY_EXISTS"
@primary_key {:dag_id, :binary_id, autogenerate: true}
schema "dags" do
field :name, :string
field :enabled, :boolean
field :schedule, :string
field :owner, :string
has_many :jobs, Erflow.Model.Job, foreign_key: :job_id
has_many :tasks, Erflow.Model.Task, foreign_key: :task_id
timestamps()
end
@doc false
def changeset(dag, attrs) do
dag
|> cast(attrs, [:name, :enabled, :schedule, :owner])
|> validate_required([:name])
|> unique_constraint([:name],
name: :dags_name_index,
message: @already_exists)
end
end
| 22.65625
| 62
| 0.677241
|
93a54cabf284b6c1c8d22cfb9e5ba6f0f9e2078d
| 1,678
|
ex
|
Elixir
|
clients/os_config/lib/google_api/os_config/v1/model/repository_resource_goo_repository.ex
|
ukrbublik/elixir-google-api
|
364cec36bc76f60bec94cbcad34844367a29d174
|
[
"Apache-2.0"
] | null | null | null |
clients/os_config/lib/google_api/os_config/v1/model/repository_resource_goo_repository.ex
|
ukrbublik/elixir-google-api
|
364cec36bc76f60bec94cbcad34844367a29d174
|
[
"Apache-2.0"
] | null | null | null |
clients/os_config/lib/google_api/os_config/v1/model/repository_resource_goo_repository.ex
|
ukrbublik/elixir-google-api
|
364cec36bc76f60bec94cbcad34844367a29d174
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.OSConfig.V1.Model.RepositoryResourceGooRepository do
@moduledoc """
Represents a Goo package repository. These will be added to a repo file that will be managed at C:/ProgramData/GooGet/repos/google_osconfig.repo.
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - The name of the repository.
* `url` (*type:* `String.t`, *default:* `nil`) - The url of the repository.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t(),
:url => String.t()
}
field(:name)
field(:url)
end
defimpl Poison.Decoder, for: GoogleApi.OSConfig.V1.Model.RepositoryResourceGooRepository do
def decode(value, options) do
GoogleApi.OSConfig.V1.Model.RepositoryResourceGooRepository.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.OSConfig.V1.Model.RepositoryResourceGooRepository do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.56
| 147
| 0.731228
|
93a5588e24fdde4d54f07516a3970b589a2fc19c
| 2,309
|
ex
|
Elixir
|
episode-026/lib/elm_is_fun/signing.ex
|
thaterikperson/elmseeds
|
72b09358926287ab4ea79893196d1ba002f190b3
|
[
"MIT"
] | 84
|
2016-07-02T05:21:36.000Z
|
2021-02-12T22:45:45.000Z
|
episode-026/lib/elm_is_fun/signing.ex
|
thaterikperson/elmseeds
|
72b09358926287ab4ea79893196d1ba002f190b3
|
[
"MIT"
] | 3
|
2016-07-02T06:03:47.000Z
|
2017-06-03T14:11:06.000Z
|
episode-026/lib/elm_is_fun/signing.ex
|
thaterikperson/elmseeds
|
72b09358926287ab4ea79893196d1ba002f190b3
|
[
"MIT"
] | 6
|
2017-02-16T19:33:49.000Z
|
2019-04-05T19:27:17.000Z
|
defmodule ElmIsFun.Signing do
use Timex
@bucket Application.get_env(:elm_is_fun, :aws_s3_bucket)
@public_key Application.get_env(:elm_is_fun, :aws_s3_public_key)
@private_key Application.get_env(:elm_is_fun, :aws_s3_secret_key)
@region "us-east-1"
@service "s3"
@aws_request "aws4_request"
def credential() do
credential(@public_key, get_date())
end
def get_date() do
datetime = Timex.now
{:ok, t} = Timex.format(datetime, "%Y%m%d", :strftime)
t
end
def policy64(host, expiration_window \\ 30) do
policy(host, expiration_window)
|> Poison.encode!
|> Base.encode64
end
def signature(host, expiration_window \\ 30) do
string_to_sign = policy64(host, expiration_window)
signing_key()
|> hash_sha256(string_to_sign)
|> Base.encode16(case: :lower)
end
def random_string(length) do
:crypto.strong_rand_bytes(length) |> Base.url_encode64 |> binary_part(0, length)
end
####### Helpers
defp policy(host, _expiration_window) do
%{"expiration" => now_plus(),
"conditions" => [
%{"bucket" => @bucket},
["starts-with", "$key", ""],
%{"x-amz-algorithm" => "AWS4-HMAC-SHA256"},
%{"x-amz-credential" => credential()},
%{"x-amz-date" => get_date() <> "T000000Z"}]}
end
defp credential(key, date) do
key <> "/" <> date <> "/" <> @region <> "/" <> @service <> "/" <> @aws_request
end
defp now_plus(minutes \\ 5) do
secs = :calendar.datetime_to_gregorian_seconds(:calendar.universal_time)
{ {year, month, day}, {hour, min, sec} } =
:calendar.gregorian_seconds_to_datetime(secs + 60 * minutes)
to_string(:io_lib.format("~.4.0w-~.2.0w-~.2.0wT~.2.0w:~.2.0w:~.2.0wZ", [year, month, day, hour, min, sec]))
end
defp signing_key() do
signing_key(@private_key, get_date(), @region, @service)
end
def signing_key(secret_key, date, region, service) do
hash_sha256("AWS4" <> secret_key, date)
|> hash_sha256(region)
|> hash_sha256(service)
|> hash_sha256("aws4_request")
end
def hash_sha256(secret, msg) do
:crypto.hmac(:sha256, secret, msg)
end
end
| 29.227848
| 113
| 0.59463
|
93a55a2d229ec3619269f5eac1aa7e7783d9d4e2
| 1,169
|
ex
|
Elixir
|
lib/database/status.ex
|
dicarlo2/bors-ng
|
0b7d6e1ccf9d5fdbce73b690da8a4f76fffc38eb
|
[
"Apache-2.0"
] | null | null | null |
lib/database/status.ex
|
dicarlo2/bors-ng
|
0b7d6e1ccf9d5fdbce73b690da8a4f76fffc38eb
|
[
"Apache-2.0"
] | null | null | null |
lib/database/status.ex
|
dicarlo2/bors-ng
|
0b7d6e1ccf9d5fdbce73b690da8a4f76fffc38eb
|
[
"Apache-2.0"
] | 3
|
2020-11-15T16:17:58.000Z
|
2021-06-04T11:26:42.000Z
|
defmodule BorsNG.Database.Status do
@moduledoc """
A database record for an individual CI run.
It corresponds to an item in the status = []
array of bors.toml.
"""
@type state_n :: 0 | 1 | 2 | 3
@type state :: :waiting | :running | :ok | :error
use BorsNG.Database.Model
alias BorsNG.Database.StatusState
schema "statuses" do
belongs_to :batch, Batch
field :identifier, :string
field :url, :string
field :state, StatusState
timestamps()
end
def changeset(struct, params \\ %{}) do
struct
|> cast(params, [:batch_id, :identifier, :url, :state])
end
def get_for_batch(batch_id, identifier) do
from s in Status,
where: s.batch_id == ^batch_id,
where: fragment("? LIKE ?", ^identifier, s.identifier)
end
def all_for_batch(batch_id) do
from s in Status, where: s.batch_id == ^batch_id
end
def all_for_batch(batch_id, :incomplete) do
from s in Status,
where: s.batch_id == ^batch_id,
where: s.state == 1 or s.state == 0
end
def all_for_batch(batch_id, state) do
from s in Status,
where: s.batch_id == ^batch_id,
where: s.state == ^state
end
end
| 23.857143
| 60
| 0.644996
|
93a55bcc20f4074c5127663bd9d08d7cd386d817
| 2,855
|
exs
|
Elixir
|
test/storage_test.exs
|
epinault/snowflake_elixir_ecto
|
9f8fc9d272ca140e27acb671af1a1c46ff923b2b
|
[
"MIT"
] | 4
|
2020-10-30T03:30:01.000Z
|
2021-08-07T10:27:15.000Z
|
test/storage_test.exs
|
epinault/snowflake_elixir_ecto
|
9f8fc9d272ca140e27acb671af1a1c46ff923b2b
|
[
"MIT"
] | 5
|
2020-10-25T12:48:17.000Z
|
2021-12-06T07:29:02.000Z
|
test/storage_test.exs
|
epinault/snowflake_elixir_ecto
|
9f8fc9d272ca140e27acb671af1a1c46ff923b2b
|
[
"MIT"
] | 3
|
2020-10-25T11:18:58.000Z
|
2021-10-16T04:00:18.000Z
|
defmodule Ecto.Integration.StorageTest do
use ExUnit.Case, async: false
@moduletag :capture_log
alias Ecto.Adapters.Snowflake
alias Ecto.Integration.PoolRepo
def params do
Application.get_env(:snowflake_elixir_ecto, PoolRepo)
end
setup do
Application.put_env(:snowflake_elixir_ecto, PoolRepo,
username: System.get_env("SNOWFLAKE_USERNAME"),
password: System.get_env("SNOWFLAKE_PASSWORD"),
host: System.get_env("SNOWFLAKE_HOST"),
account_name: System.get_env("SNOWFLAKE_ACCOUNT_NAME"),
database: "test_#{Ecto.UUID.generate|>String.replace("-", "")}",
schema: "test_#{Ecto.UUID.generate|>String.replace("-", "")}",
role: System.get_env("SNOWFLAKE_ROLE"),
pool_size: 5,
timeout: 100_000_000,
warehouse: System.get_env("SNOWFLAKE_WAREHOUSE"),
show_sensitive_data_on_connection_error: true,
queue_target: 1000,
queue_interval: 10000
)
{:ok, _} = Ecto.Adapters.Snowflake.ensure_all_started(PoolRepo.config(), :temporary)
{:ok, _} = PoolRepo.start_link()
:ok
end
def wrong_params do
Keyword.merge(params(),
username: "randomuser",
password: "password1234"
)
end
def drop_database() do
run_snowflake_sql("DROP DATABASE #{params()[:database]};")
end
def create_database() do
run_snowflake_sql("CREATE DATABASE #{params()[:database]};")
end
def create_posts() do
run_snowflake_sql("CREATE TABLE posts (title varchar(20));")
end
def run_snowflake_sql(sql) do
PoolRepo.query(sql)
end
test "storage up (twice in a row)" do
assert Snowflake.storage_up(params()) == :ok
assert Snowflake.storage_up(params()) == {:error, :already_up}
after
drop_database()
end
test "storage down (twice in a row)" do
create_database()
assert Snowflake.storage_down(params()) == :ok
assert Snowflake.storage_down(params()) == {:error, :already_down}
end
test "storage up and down (wrong credentials)" do
refute Snowflake.storage_up(wrong_params()) == :ok
create_database()
refute Snowflake.storage_down(wrong_params()) == :ok
after
drop_database()
end
defmodule Migration do
use Ecto.Migration
def change, do: :ok
end
test "storage status is up when database is created" do
create_database()
assert :up == Snowflake.storage_status(params())
after
drop_database()
end
test "storage status is down when database is not created" do
create_database()
drop_database()
assert :down == Snowflake.storage_status(params())
end
test "storage status is an error when wrong credentials are passed" do
assert Snowflake.storage_status(wrong_params()) ==
{:error,
{:error,
%RuntimeError{message: "\"Incorrect username or password was specified.\""}}}
end
end
| 26.933962
| 92
| 0.681611
|
93a57834a7137b1140606bbc83b8e97884d7b738
| 1,131
|
ex
|
Elixir
|
clients/android_publisher/lib/google_api/android_publisher/v3/connection.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/android_publisher/lib/google_api/android_publisher/v3/connection.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/android_publisher/lib/google_api/android_publisher/v3/connection.ex
|
pojiro/elixir-google-api
|
928496a017d3875a1929c6809d9221d79404b910
|
[
"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.AndroidPublisher.V3.Connection do
@moduledoc """
Handle Tesla connections for GoogleApi.AndroidPublisher.V3.
"""
@type t :: Tesla.Env.client()
use GoogleApi.Gax.Connection,
scopes: [
# View and manage your Google Play Developer account
"https://www.googleapis.com/auth/androidpublisher"
],
otp_app: :google_api_android_publisher,
base_url: "https://androidpublisher.googleapis.com/"
end
| 34.272727
| 74
| 0.746242
|
93a5913606b71adc53751022db0aae93c091411d
| 50
|
ex
|
Elixir
|
lib/ueberauth_meli.ex
|
marciotoze/ueberauth_meli
|
2f3ff7d6a0d211235c23591f40673eaf1d3707da
|
[
"MIT"
] | 1
|
2022-03-02T07:25:31.000Z
|
2022-03-02T07:25:31.000Z
|
lib/ueberauth_meli.ex
|
marciotoze/ueberauth_meli
|
2f3ff7d6a0d211235c23591f40673eaf1d3707da
|
[
"MIT"
] | null | null | null |
lib/ueberauth_meli.ex
|
marciotoze/ueberauth_meli
|
2f3ff7d6a0d211235c23591f40673eaf1d3707da
|
[
"MIT"
] | null | null | null |
defmodule UeberauthMeli do
@moduledoc false
end
| 12.5
| 26
| 0.82
|
93a5961dfe0559a6f107239869691218fa8171eb
| 1,700
|
exs
|
Elixir
|
test/cli/parser_test.exs
|
capbash/dioex
|
4aca1c01fd05917d41a98df4d0f0dab2347f28e8
|
[
"MIT"
] | 5
|
2017-08-06T09:22:35.000Z
|
2017-10-22T15:51:45.000Z
|
test/cli/parser_test.exs
|
capbash/doex
|
4aca1c01fd05917d41a98df4d0f0dab2347f28e8
|
[
"MIT"
] | null | null | null |
test/cli/parser_test.exs
|
capbash/doex
|
4aca1c01fd05917d41a98df4d0f0dab2347f28e8
|
[
"MIT"
] | null | null | null |
defmodule Doex.Cli.ParserTest do
use ExUnit.Case
alias Doex.Cli.Parser
setup do
on_exit(fn ->
File.rm("/tmp/parser.doex")
System.delete_env("DOEX_CONFIG")
Doex.reload()
end)
:ok
end
@opt_defn %{one: :string, two: :boolean, four: :list}
test "parse empty" do
assert {%{}, []} == Parser.parse([], %{})
assert {%{}, ["dosomething"]} == Parser.parse(["dosomething"], %{})
end
test "parse string, boolean and list" do
args = ["dox", "--one", "1", "--two", "three", "--four", "a,b,c"]
assert {%{four: ["a", "b", "c"], one: "1", two: true}, ["dox", "three"]} ==
Parser.parse(args, @opt_defn)
end
test "parse integer" do
assert {%{five: 0}, []} == Parser.parse([], %{five: :integer})
end
test "defaulted values (no overrides)" do
args = ["dox", "three"]
assert {%{four: [], one: nil, two: false}, ["dox", "three"]} == Parser.parse(args, @opt_defn)
end
test "no option definition" do
args = ["dox", "--a", "1", "--b", "three", "--c", "a,b,c"]
assert {%{a: "1", b: "three", c: "a,b,c"}, ["dox"]} == Parser.parse(args)
end
test "defaulted values (with overrides)" do
System.put_env("DOEX_CONFIG", "/tmp/parser.doex")
Doex.Config.put(:one, "uno")
Doex.Config.put(:two, true)
Doex.Config.put(:four, ["d", "e", "f"])
args = ["dox", "--one", "1", "--two", "three", "--four", "a,b,c"]
assert {%{four: ["a", "b", "c"], one: "1", two: true}, ["dox", "three"]} ==
Parser.parse(args, @opt_defn)
args = ["dox", "three"]
assert {%{four: ["d", "e", "f"], one: "uno", two: true}, ["dox", "three"]} ==
Parser.parse(args, @opt_defn)
end
end
| 28.333333
| 97
| 0.522353
|
93a5a91e65e641d3604e9c0cb95112b79abb7484
| 8,140
|
exs
|
Elixir
|
test/vintage_net_test.exs
|
fhunleth/vintage_net
|
215495533cb642eeb172daba08208a454f19b36f
|
[
"Apache-2.0"
] | 1
|
2019-05-08T19:09:17.000Z
|
2019-05-08T19:09:17.000Z
|
test/vintage_net_test.exs
|
fhunleth/vintage_net
|
215495533cb642eeb172daba08208a454f19b36f
|
[
"Apache-2.0"
] | null | null | null |
test/vintage_net_test.exs
|
fhunleth/vintage_net
|
215495533cb642eeb172daba08208a454f19b36f
|
[
"Apache-2.0"
] | null | null | null |
defmodule VintageNetTest do
use VintageNetTest.Case
doctest VintageNet
import ExUnit.CaptureLog
setup do
# Restart the VintageNet application, so all of the tests
# can be in a pristine and consistent configuration.
#
# The following interfaces will exist:
#
# * "bogus0" - only in the application config
# * "bogus1" - only in persistence store
# * "bogus2" - in both the application config and persistence.
# The persistence config should override.
capture_log(fn ->
Application.stop(:vintage_net)
# Just in case someone forgot to clean up...
File.rm_rf!(Application.get_env(:vintage_net, :persistence_dir))
Application.put_env(:vintage_net, :config, [
{"bogus0",
%{
type: VintageNetTest.TestTechnology,
bogus: 0
}},
{"bogus2",
%{
type: VintageNetTest.TestTechnology,
bogus: -1
}},
{"invalid_config", :this, :should, :be, :ignored, :with, :a, :warning}
])
VintageNet.Persistence.call(:save, [
"bogus1",
%{
type: VintageNetTest.TestTechnology,
bogus: 1
}
])
VintageNet.Persistence.call(:save, [
"bogus2",
%{
type: VintageNetTest.TestTechnology,
bogus: 2
}
])
Application.start(:vintage_net)
# Loading of configurations is async and sometimes fails without short sleep
Process.sleep(10)
end)
# Restore the configuration and persistance state to the original way
on_exit(fn ->
capture_log(fn ->
Application.stop(:vintage_net)
File.rm_rf!(Application.get_env(:vintage_net, :persistence_dir))
Application.put_env(:vintage_net, :config, [])
Application.start(:vintage_net)
end)
end)
:ok
end
test "configure fails on a missing type field" do
assert {:error,
"Missing :type field.\n\nThis should be set to a network technology. These are provided in other libraries.\nSee the `vintage_net` docs and cookbook for examples.\n"} ==
VintageNet.configure("eth0", %{})
end
test "configure fails if technology isn't available" do
assert {:error,
"Invalid technology VintageNetWifi.\n\nCheck the spelling and that you have the dependency that provides it in your mix.exs.\nSee the `vintage_net` docs for examples.\n"} ==
VintageNet.configure("eth0", %{type: VintageNetWifi})
end
@tag :requires_interfaces_monitor
test "interfaces exist" do
# On CircleCI, sometimes the interfaces monitor process is slow to start. This is ok.
Process.sleep(500)
interfaces = VintageNet.all_interfaces()
assert interfaces != []
# The loopback interface always exists, so check for it
assert Enum.any?(interfaces, &String.starts_with?(&1, "lo"))
end
test "only fake interfaces are configured when testing" do
assert ["bogus0", "bogus1", "bogus2"] == VintageNet.configured_interfaces()
end
test "configure returns error on bad configurations" do
assert match?({:error, _}, VintageNet.configure("eth0", %{this_totally_should_not_work: 1}))
end
test "calls normalize" do
:ok = VintageNet.configure("eth0", %{type: VintageNetTest.TestTechnology})
applied_config = VintageNet.get_configuration("eth0")
# See TestTechnology's normalize/1 method
assert Map.get(applied_config, :normalize_was_called)
end
test "configure persists by default" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "eth0")
:ok = VintageNet.configure("eth0", %{type: VintageNetTest.TestTechnology})
assert File.exists?(path)
end
test "configure does not persist on bad configurations" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "eth0")
{:error, _} = VintageNet.configure("eth0", %{this_totally_should_not_work: 1})
refute File.exists?(path)
end
test "can turn off configuration persistence" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "eth0")
:ok = VintageNet.configure("eth0", %{type: VintageNetTest.TestTechnology}, persist: false)
assert VintageNet.get_configuration("eth0") == %{
type: VintageNetTest.TestTechnology,
normalize_was_called: true
}
refute File.exists?(path)
end
test "configuration_valid? works" do
assert VintageNet.configuration_valid?("eth0", %{type: VintageNetTest.TestTechnology})
refute VintageNet.configuration_valid?("eth0", %{this_totally_should_not_work: 1})
end
test "persisted configurations get restored" do
assert VintageNet.get_configuration("bogus0") == %{
type: VintageNetTest.TestTechnology,
bogus: 0
}
assert VintageNet.get_configuration("bogus1") == %{
type: VintageNetTest.TestTechnology,
bogus: 1
}
assert VintageNet.get_configuration("bogus2") == %{
type: VintageNetTest.TestTechnology,
bogus: 2
}
end
describe "resets interfaces to defaults" do
test "already set to defaults" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "bogus0")
refute File.exists?(path)
:ok = VintageNet.reset_to_defaults("bogus0")
refute File.exists?(path)
assert %{bogus: 0} = VintageNet.get_configuration("bogus0")
end
test "unconfigured in defaults" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "bogus1")
assert File.exists?(path)
:ok = VintageNet.reset_to_defaults("bogus1")
refute File.exists?(path)
assert %{type: VintageNet.Technology.Null} == VintageNet.get_configuration("bogus1")
end
test "overridden by a configuration" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "bogus2")
assert File.exists?(path)
:ok = VintageNet.reset_to_defaults("bogus2")
refute File.exists?(path)
# The default for bogus2 is -1
assert %{bogus: -1} = VintageNet.get_configuration("bogus2")
end
test "unknown network interface" do
path = Path.join(Application.get_env(:vintage_net, :persistence_dir), "unknown1")
refute File.exists?(path)
:ok = VintageNet.reset_to_defaults("unknown1")
refute File.exists?(path)
assert %{type: VintageNet.Technology.Null} == VintageNet.get_configuration("unknown1")
end
end
# Check that get, get_by_prefix, and match are available in the public
# interface. Better tests should be else.
test "get" do
# These properties should always exist
assert [] == VintageNet.get(["available_interfaces"])
assert :disconnected == VintageNet.get(["connection"])
end
test "get_by_prefix" do
results = VintageNet.get_by_prefix([])
# There may or may not be "interfaces", so don't check for those.
assert {["available_interfaces"], []} in results
assert {["connection"], :disconnected} in results
end
test "match" do
assert [{["available_interfaces"], []}] ==
VintageNet.match(["available_interfaces"])
assert [
{["available_interfaces"], []},
{["connection"], :disconnected},
{["name_servers"], []}
] ==
VintageNet.match([:_])
end
test "verify system works", context do
# create files here at some tmp place
in_tmp(context.test, fn ->
opts = Application.get_all_env(:vintage_net) |> prefix_paths(File.cwd!())
File.mkdir!("sbin")
File.touch!("sbin/ip")
assert :ok == VintageNet.verify_system(opts)
end)
end
test "max interface count works" do
assert 8 == VintageNet.max_interface_count()
end
defp prefix_paths(opts, prefix) do
Enum.map(opts, fn kv -> prefix_path(kv, prefix) end)
end
defp prefix_path({key, path}, prefix) do
key_str = to_string(key)
if String.starts_with?(key_str, "bin_") do
{key, prefix <> path}
else
{key, path}
end
end
end
| 31.428571
| 185
| 0.653194
|
93a5d04795c02c5599d302e50cd97ce25fffec4e
| 1,596
|
exs
|
Elixir
|
test/stabby_flies/player_test.exs
|
hassanshaikley/ascii-quest
|
8b3b3af3b9c6c59b8155fe2e6cb2a794033c29f1
|
[
"MIT"
] | 8
|
2019-01-15T09:31:05.000Z
|
2020-04-20T13:59:01.000Z
|
test/stabby_flies/player_test.exs
|
hassanshaikley/ascii-quest
|
8b3b3af3b9c6c59b8155fe2e6cb2a794033c29f1
|
[
"MIT"
] | 2
|
2019-01-06T02:53:44.000Z
|
2019-05-30T20:30:20.000Z
|
test/stabby_flies/player_test.exs
|
hassanshaikley/ascii-quest
|
8b3b3af3b9c6c59b8155fe2e6cb2a794033c29f1
|
[
"MIT"
] | 1
|
2019-01-04T04:37:21.000Z
|
2019-01-04T04:37:21.000Z
|
defmodule StabbyFlies.PlayerTest do
use ExUnit.Case, async: true
alias StabbyFlies.Player
setup do
player =
start_supervised!(
{Player, name: "Faa", x: 15, y: 10, hp: 10, max_hp: 10, sword_rotation: 0}
)
%{player: player}
end
test "initialization", %{player: player} do
player_state = Player.state(player)
assert player_state.name == "Faa"
assert player_state.x != nil
assert player_state.y != nil
assert player_state.hp == 10
assert player_state.max_hp == 10
assert player_state.sword_rotation == 0
end
test "take damage", %{player: player} do
Player.take_damage(player, 1)
player_state = Player.state(player)
assert player_state.hp == 9
Player.take_damage(player, 999)
player_state = Player.state(player)
assert player_state.hp == player_state.max_hp
end
test "can_stab", %{player: player} do
assert Player.can_stab(player) == true
end
test "reset stab cooldown", %{player: player} do
Player.reset_stab_cooldown(player)
assert Player.can_stab(player) == false
end
test "increment kill count", %{player: player} do
old_kill_count = Player.state(player).kill_count
Player.increment_kill_count(player)
player_state = Player.state(player)
assert old_kill_count + 1 == player_state.kill_count
end
test "update moving", %{player: player} do
new_moving = %{
forward: true,
backward: true
}
Player.update_moving(player, new_moving)
player_state = Player.state(player)
assert player_state.moving == new_moving
end
end
| 24.9375
| 82
| 0.681704
|
93a5f97f5ac0f15049e9cdadc362c4332447ea5d
| 918
|
ex
|
Elixir
|
deps/postgrex/lib/postgrex/error.ex
|
hallebadkapp/rumbl-ms
|
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
|
[
"MIT"
] | null | null | null |
deps/postgrex/lib/postgrex/error.ex
|
hallebadkapp/rumbl-ms
|
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
|
[
"MIT"
] | null | null | null |
deps/postgrex/lib/postgrex/error.ex
|
hallebadkapp/rumbl-ms
|
ae2ef9975658115f8c4d5c49c28d8bde00a74b83
|
[
"MIT"
] | null | null | null |
defmodule Postgrex.Error do
defexception [:message, :postgres, :connection_id]
@type t :: %Postgrex.Error{}
@metadata [:table, :column, :constraint]
def message(e) do
if kw = e.postgres do
"#{kw[:severity]} (#{kw[:code]}): #{kw[:message]}"
<> build_metadata(kw)
<> build_detail(kw)
else
e.message
end
end
defp build_metadata(kw) do
metadata = for k <- @metadata, v = kw[k], do: "\n #{k}: #{v}"
case metadata do
[] -> ""
_ -> "\n" <> Enum.join(metadata)
end
end
defp build_detail(kw) do
if v = kw[:detail], do: "\n\n" <> v, else: ""
end
def exception([postgres: fields]) do
fields = Enum.into(fields, %{})
|> Map.put(:pg_code, fields[:code])
|> Map.update!(:code, &Postgrex.ErrorCode.code_to_name/1)
%Postgrex.Error{postgres: fields}
end
def exception(arg) do
super(arg)
end
end
| 21.857143
| 70
| 0.565359
|
93a5fd33ad567b18564afd1ef7ba05450faba569
| 1,456
|
exs
|
Elixir
|
MixProject/mssql_umbrella/apps/mssql/mix.exs
|
Dmdv/ElixirPlayground
|
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
|
[
"Apache-2.0"
] | null | null | null |
MixProject/mssql_umbrella/apps/mssql/mix.exs
|
Dmdv/ElixirPlayground
|
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
|
[
"Apache-2.0"
] | null | null | null |
MixProject/mssql_umbrella/apps/mssql/mix.exs
|
Dmdv/ElixirPlayground
|
02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1
|
[
"Apache-2.0"
] | null | null | null |
defmodule Mssql.Mixfile do
use Mix.Project
def project do
[
app: :mssql,
version: "0.0.1",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.4",
elixirc_paths: elixirc_paths(Mix.env),
start_permanent: Mix.env == :prod,
aliases: aliases(),
deps: deps()
]
end
# Configuration for the OTP application.
#
# Type `mix help compile.app` for more information.
def application do
[
mod: {Mssql.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:mssql_ecto, ">= 0.0.0"},
{:ecto, "~> 2.1"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]
]
end
end
| 25.103448
| 79
| 0.592033
|
93a6220ba17f7a3221f33d002380a62774890d90
| 156
|
exs
|
Elixir
|
test/test_helper.exs
|
avval-alumni/alumni_book
|
17b27da849919312a332aaa3b39ce5c65032f2b4
|
[
"MIT"
] | null | null | null |
test/test_helper.exs
|
avval-alumni/alumni_book
|
17b27da849919312a332aaa3b39ce5c65032f2b4
|
[
"MIT"
] | null | null | null |
test/test_helper.exs
|
avval-alumni/alumni_book
|
17b27da849919312a332aaa3b39ce5c65032f2b4
|
[
"MIT"
] | null | null | null |
ExUnit.start()
Mix.Task.run("ecto.create", ["--quiet"])
Mix.Task.run("ecto.migrate", ["--quiet"])
Ecto.Adapters.SQL.Sandbox.mode(AlumniBook.Repo, :manual)
| 26
| 56
| 0.692308
|
93a65daf0458c060d030bce56b3ae6c461e81616
| 6,084
|
ex
|
Elixir
|
lib/mix/tasks/phx.gen.json.ex
|
matthewp/phoenix
|
af86b95db365faada58d326e98de65c811690bc7
|
[
"MIT"
] | 2
|
2020-05-06T14:51:56.000Z
|
2020-05-06T14:52:21.000Z
|
lib/mix/tasks/phx.gen.json.ex
|
matthewp/phoenix
|
af86b95db365faada58d326e98de65c811690bc7
|
[
"MIT"
] | 3
|
2021-06-20T14:51:14.000Z
|
2021-06-25T00:56:11.000Z
|
lib/mix/tasks/phx.gen.json.ex
|
matthewp/phoenix
|
af86b95db365faada58d326e98de65c811690bc7
|
[
"MIT"
] | 1
|
2020-05-16T22:44:14.000Z
|
2020-05-16T22:44:14.000Z
|
defmodule Mix.Tasks.Phx.Gen.Json do
@shortdoc "Generates controller, views, and context for a JSON resource"
@moduledoc """
Generates controller, views, and context for a JSON resource.
mix phx.gen.json Accounts User users name:string age:integer
The first argument is the context module followed by the schema module
and its plural name (used as the schema table name).
The context is an Elixir module that serves as an API boundary for
the given resource. A context often holds many related resources.
Therefore, if the context already exists, it will be augmented with
functions for the given resource.
> Note: A resource may also be split
> over distinct contexts (such as `Accounts.User` and `Payments.User`).
The schema is responsible for mapping the database fields into an
Elixir struct. It is followed by an optional list of attributes,
with their respective names and types. See `mix phx.gen.schema`
for more information on attributes.
Overall, this generator will add the following files to `lib/`:
* a context module in `lib/app/accounts.ex` for the accounts API
* a schema in `lib/app/accounts/user.ex`, with an `users` table
* a view in `lib/app_web/views/user_view.ex`
* a controller in `lib/app_web/controllers/user_controller.ex`
A migration file for the repository and test files for the context and
controller features will also be generated.
## The context app
The location of the web files (controllers, views, templates, etc) in an
umbrella application will vary based on the `:context_app` config located
in your applications `:generators` configuration. When set, the Phoenix
generators will generate web files directly in your lib and test folders
since the application is assumed to be isolated to web specific functionality.
If `:context_app` is not set, the generators will place web related lib
and test files in a `web/` directory since the application is assumed
to be handling both web and domain specific functionality.
Example configuration:
config :my_app_web, :generators, context_app: :my_app
Alternatively, the `--context-app` option may be supplied to the generator:
mix phx.gen.json Sales User users --context-app warehouse
## Web namespace
By default, the controller and view will be namespaced by the schema name.
You can customize the web module namespace by passing the `--web` flag with a
module name, for example:
mix phx.gen.json Sales User users --web Sales
Which would generate a `lib/app_web/controllers/sales/user_controller.ex` and
`lib/app_web/views/sales/user_view.ex`.
## Customising the context, schema, tables and migrations
In some cases, you may wish to bootstrap JSON views, controllers,
and controller tests, but leave internal implementation of the context
or schema to yourself. You can use the `--no-context` and `--no-schema`
flags for file generation control.
You can also change the table name or configure the migrations to
use binary ids for primary keys, see `mix phx.gen.schema` for more
information.
"""
use Mix.Task
alias Mix.Phoenix.Context
alias Mix.Tasks.Phx.Gen
@doc false
def run(args) do
if Mix.Project.umbrella?() do
Mix.raise "mix phx.gen.json must be invoked from within your *_web application root directory"
end
{context, schema} = Gen.Context.build(args)
Gen.Context.prompt_for_code_injection(context)
binding = [context: context, schema: schema]
paths = Mix.Phoenix.generator_paths()
prompt_for_conflicts(context)
context
|> copy_new_files(paths, binding)
|> print_shell_instructions()
end
defp prompt_for_conflicts(context) do
context
|> files_to_be_generated()
|> Kernel.++(context_files(context))
|> Mix.Phoenix.prompt_for_conflicts()
end
defp context_files(%Context{generate?: true} = context) do
Gen.Context.files_to_be_generated(context)
end
defp context_files(%Context{generate?: false}) do
[]
end
@doc false
def files_to_be_generated(%Context{schema: schema, context_app: context_app}) do
web_prefix = Mix.Phoenix.web_path(context_app)
test_prefix = Mix.Phoenix.web_test_path(context_app)
web_path = to_string(schema.web_path)
[
{:eex, "controller.ex", Path.join([web_prefix, "controllers", web_path, "#{schema.singular}_controller.ex"])},
{:eex, "view.ex", Path.join([web_prefix, "views", web_path, "#{schema.singular}_view.ex"])},
{:eex, "controller_test.exs", Path.join([test_prefix, "controllers", web_path, "#{schema.singular}_controller_test.exs"])},
{:new_eex, "changeset_view.ex", Path.join([web_prefix, "views/changeset_view.ex"])},
{:new_eex, "fallback_controller.ex", Path.join([web_prefix, "controllers/fallback_controller.ex"])},
]
end
@doc false
def copy_new_files(%Context{} = context, paths, binding) do
files = files_to_be_generated(context)
Mix.Phoenix.copy_from paths, "priv/templates/phx.gen.json", binding, files
if context.generate?, do: Gen.Context.copy_new_files(context, paths, binding)
context
end
@doc false
def print_shell_instructions(%Context{schema: schema, context_app: ctx_app} = context) do
if schema.web_namespace do
Mix.shell().info """
Add the resource to your #{schema.web_namespace} :api scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex:
scope "/#{schema.web_path}", #{inspect Module.concat(context.web_module, schema.web_namespace)}, as: :#{schema.web_path} do
pipe_through :api
...
resources "/#{schema.plural}", #{inspect schema.alias}Controller
end
"""
else
Mix.shell().info """
Add the resource to your :api scope in #{Mix.Phoenix.web_path(ctx_app)}/router.ex:
resources "/#{schema.plural}", #{inspect schema.alias}Controller, except: [:new, :edit]
"""
end
if context.generate?, do: Gen.Context.print_shell_instructions(context)
end
end
| 37.78882
| 136
| 0.714497
|
93a67c4837c56cd8e82589ce9000e84d90919504
| 689
|
exs
|
Elixir
|
priv/repo/migrations/20210609210622_create_notifications.exs
|
elixirprogrammer/InstagramClonePETAL
|
5710f89de32a95b0416a960a46d081e7ad4833ab
|
[
"MIT"
] | 69
|
2021-04-11T21:57:26.000Z
|
2022-03-30T01:09:40.000Z
|
priv/repo/migrations/20210609210622_create_notifications.exs
|
hminy572/InstagramClonePETAL
|
577cdad0e17399e47ef9d3f8e789bd07e33012b9
|
[
"MIT"
] | 1
|
2021-04-16T17:38:11.000Z
|
2021-04-16T17:38:11.000Z
|
priv/repo/migrations/20210609210622_create_notifications.exs
|
hminy572/InstagramClonePETAL
|
577cdad0e17399e47ef9d3f8e789bd07e33012b9
|
[
"MIT"
] | 4
|
2021-04-16T10:45:18.000Z
|
2021-07-23T15:08:08.000Z
|
defmodule InstagramClone.Repo.Migrations.CreateNotifications do
use Ecto.Migration
def change do
create table(:notifications) do
add :action, :string
add :read, :boolean, default: false
add :user_id, references(:users, on_delete: :delete_all)
add :actor_id, references(:users, on_delete: :delete_all)
add :comment_id, references(:comments, on_delete: :delete_all)
add :post_id, references(:posts, on_delete: :delete_all)
timestamps()
end
create index(:notifications, [:user_id])
create index(:notifications, [:actor_id])
create index(:notifications, [:comment_id])
create index(:notifications, [:post_id])
end
end
| 31.318182
| 68
| 0.699565
|
93a69128e8d7b53a904b9cfcd52ae9ae6d24f166
| 1,698
|
ex
|
Elixir
|
lib/bitstyles_phoenix/bitstyles.ex
|
bitcrowd/bitstyles_phoenix
|
697d9380d376f23885b696776736643687d4dd14
|
[
"0BSD"
] | 4
|
2021-03-12T07:57:06.000Z
|
2021-11-15T11:41:30.000Z
|
lib/bitstyles_phoenix/bitstyles.ex
|
bitcrowd/bitstyles_phoenix
|
697d9380d376f23885b696776736643687d4dd14
|
[
"0BSD"
] | 39
|
2021-03-11T15:36:51.000Z
|
2022-01-04T12:13:48.000Z
|
lib/bitstyles_phoenix/bitstyles.ex
|
bitcrowd/bitstyles_phoenix
|
697d9380d376f23885b696776736643687d4dd14
|
[
"0BSD"
] | null | null | null |
defmodule BitstylesPhoenix.Bitstyles do
@moduledoc false
@default_version "3.0.0"
@cdn_url "https://cdn.jsdelivr.net/npm/bitstyles"
def cdn_url do
"#{@cdn_url}@#{@default_version}"
end
@doc """
Returns the classnames for the configured version.
Input classnames are assumed to be from the #{@default_version} version of bitstyles.
"""
def classname(name), do: classname(name, version())
def classname(class, version) when version > "3.0.0" do
IO.warn("Version #{version} of bitstyles is not yet supported")
class
end
def classname(class, version) when version >= "2.0.0", do: class
def classname(class, version) when version >= "1.5.0" do
mapping =
case class do
"u-flex-shrink-" <> number -> "u-flex__shrink-#{number}"
"u-flex-grow-" <> number -> "u-flex__grow-#{number}"
"u-flex-wrap" -> "u-flex--wrap"
"u-flex-col" -> "u-flex--col"
_ -> class
end
classname(mapping, "2.0.0")
end
def classname(class, version) when version >= "1.3.0" do
mapping =
case class do
"u-grid-cols-" <> number -> "u-grid--#{number}-col"
"u-col-span-" <> number -> "u-grid__col-span-#{number}"
"u-col-start-" <> number -> "u-grid__col-#{number}"
_ -> class
end
classname(mapping, "1.5.0")
end
def classname(_class, version) do
raise("""
The version #{version} of bitstyles is not supported. The helpers will produce incorrect classes.
Please upgrade bitsyles and set the `bitsyles_version` to the updated version.
""")
end
def version do
Application.get_env(:bitstyles_phoenix, :bitstyles_version, @default_version)
end
end
| 28.3
| 101
| 0.633098
|
93a6a3678945b58a31e007a82f35f3cc81e7e38b
| 794
|
ex
|
Elixir
|
schizo/lib/schizo.ex
|
enilsen16/elixir
|
b4d1d45858a25e4beb39e07de8685f3d93d6a520
|
[
"MIT"
] | null | null | null |
schizo/lib/schizo.ex
|
enilsen16/elixir
|
b4d1d45858a25e4beb39e07de8685f3d93d6a520
|
[
"MIT"
] | null | null | null |
schizo/lib/schizo.ex
|
enilsen16/elixir
|
b4d1d45858a25e4beb39e07de8685f3d93d6a520
|
[
"MIT"
] | null | null | null |
defmodule Schizo do
def uppercase(string) do
transform_every_other_word(string, &uppercaser/1)
end
def unvowel(string) do
transform_every_other_word(string, &unvowler/1)
end
def transform_every_other_word(string, transformation) do
words = String.split(string)
words_with_index = Stream.with_index(words)
transformed_words = Enum.map(words_with_index, transformation)
Enum.join(transformed_words, " ")
end
def uppercaser(input) do
transformer(input, &String.upcase/1)
end
def unvowler(input) do
transformer(input, fn(word) -> Regex.replace(~r([aeiou]), word, "") end)
end
def transformer({word, index}, transformation) do
cond do
rem(index, 2) == 0 -> word
rem(index, 2) == 1 -> transformation.(word)
end
end
end
| 24.8125
| 76
| 0.696474
|
93a6dd590ba887dc92ed3c840acdfa1af512e394
| 937
|
ex
|
Elixir
|
lib/blog_web/controllers/traditional_blog_controllers/session_controller.ex
|
albertschr/blog_supported_blockchain
|
ee9578c8ebddd3e72ff5eaabefc2d724c3e2a9a1
|
[
"MIT"
] | 1
|
2019-02-06T12:29:35.000Z
|
2019-02-06T12:29:35.000Z
|
lib/blog_web/controllers/traditional_blog_controllers/session_controller.ex
|
albertschr/blog_supported_blockchain
|
ee9578c8ebddd3e72ff5eaabefc2d724c3e2a9a1
|
[
"MIT"
] | null | null | null |
lib/blog_web/controllers/traditional_blog_controllers/session_controller.ex
|
albertschr/blog_supported_blockchain
|
ee9578c8ebddd3e72ff5eaabefc2d724c3e2a9a1
|
[
"MIT"
] | null | null | null |
defmodule BlogWeb.SessionController do
alias BlogWeb.UserController
alias WebHandler
use BlogWeb, :controller
@doc """
suit 「application/json」
"""
def create(conn, %{"password" => password, "username" => user}) do
do_create(conn, user, password)
end
# @doc """
# suit 「application/x-www-form-urlencoded」
# """
# def create(conn, params) do
# {:ok, %{"password" => password, "username" => user}} =
# WebHandler.handle_www_form(params)
# create(conn, user, password)
# end
defp do_create(conn, user, password) do
case User.authenticate_user(user, password) do
{:ok, user} ->
conn = UserController.login(conn, user)
json(conn, "success!")
{:error, _reason} ->
json(conn, "Invalid username/password combination")
end
end
def delete(conn, _) do
conn
|> UserController.logout()
|> redirect(to: page_path(conn, :index))
end
end
| 23.425
| 68
| 0.627535
|
93a740f76923cf9d8f7c4fbc03b262e3f64302e4
| 18,880
|
exs
|
Elixir
|
test/telemetry_metrics_test.exs
|
Cantido/telemetry_metrics
|
ddc41e5c64d0ea416d810529f1a251c738e8d568
|
[
"Apache-2.0"
] | null | null | null |
test/telemetry_metrics_test.exs
|
Cantido/telemetry_metrics
|
ddc41e5c64d0ea416d810529f1a251c738e8d568
|
[
"Apache-2.0"
] | null | null | null |
test/telemetry_metrics_test.exs
|
Cantido/telemetry_metrics
|
ddc41e5c64d0ea416d810529f1a251c738e8d568
|
[
"Apache-2.0"
] | null | null | null |
defmodule Telemetry.MetricsTest do
use ExUnit.Case
alias Telemetry.Metrics
# Tests common to all metric types.
for metric_type <- [:counter, :sum, :last_value, :summary, :distribution] do
describe "#{metric_type}/2" do
test "raises when metric name is invalid" do
assert_raise ArgumentError, fn ->
name = [:my, "event"]
apply(Metrics, unquote(metric_type), [name])
end
end
test "raises when event name is invalid" do
assert_raise ArgumentError, fn ->
options = [event_name: [:my, "event"]]
apply(Metrics, unquote(metric_type), ["my.metric", options])
end
end
test "raises when tag_values is invalid" do
assert_raise ArgumentError, fn ->
options = [tag_values: 1]
apply(Metrics, unquote(metric_type), ["my.metric", options])
end
end
test "raises when tags are invalid" do
assert_raise ArgumentError, fn ->
options = [tags: 1]
apply(Metrics, unquote(metric_type), ["my.metric", options])
end
end
test "raises when description is invalid" do
assert_raise ArgumentError, fn ->
options = [description: :"metric description"]
apply(Metrics, unquote(metric_type), ["my.metric", options])
end
end
test "raises when unit is invalid" do
assert_raise ArgumentError, fn ->
options = [unit: "second"]
apply(Metrics, unquote(metric_type), ["my.metric", options])
end
end
test "raises when reporter options is invalid" do
assert_raise ArgumentError, fn ->
options = [reporter_options: [:avg]]
apply(Metrics, unquote(metric_type), ["my.metric", options])
end
end
test "returns #{metric_type} specification with default fields" do
name = "http.request.latency"
metric = apply(Metrics, unquote(metric_type), [name])
assert [:http, :request] == metric.event_name
assert [:http, :request, :latency] == metric.name
assert [] == metric.tags
assert nil == metric.description
assert :unit == metric.unit
assert :latency = metric.measurement
assert [] = metric.reporter_options
tag_values_fun = metric.tag_values
assert %{key: 1, another_key: 2} == tag_values_fun.(%{key: 1, another_key: 2})
end
test "returns #{metric_type} specification with overriden fields" do
name = "my.metric"
event_name = [:my, :event]
measurement = :other_value
tag_values = &%{:controller => &1.controller, "controller_action" => &1.action}
tags = [:controller, "controller_action"]
description = "a metric"
unit = :second
reporter_options = [sample_rate: 0.1]
options = [
event_name: event_name,
measurement: measurement,
tags: tags,
tag_values: tag_values,
description: description,
unit: unit,
reporter_options: reporter_options
]
metric = apply(Metrics, unquote(metric_type), [name, options])
assert event_name == metric.event_name
assert [:my, :metric] == metric.name
assert tags == metric.tags
assert description == metric.description
assert unit == metric.unit
assert :other_value = metric.measurement
assert reporter_options == metric.reporter_options
tag_values_fun = metric.tag_values
assert %{:controller => UserController, "controller_action" => "create"} ==
tag_values_fun.(%{controller: UserController, action: "create"})
end
test "return normalized metric and event name in the specification" do
metric =
apply(Metrics, unquote(metric_type), [
"http.requests.count",
[event_name: "http.request"]
])
assert [:http, :request] == metric.event_name
assert [:http, :requests, :count] == metric.name
end
test "tag_values default returns identity function in metric spec" do
metric =
apply(Metrics, unquote(metric_type), [
"my.event.value"
])
tag_values_fun = metric.tag_values
event_metadata = %{controller: UserController, action: "create"}
assert event_metadata == tag_values_fun.(event_metadata)
end
test "setting function as tag_values returns that function in metric spec" do
metric =
apply(Metrics, unquote(metric_type), [
"my.event.value",
[tag_values: fn _ -> %{constant: "metadata"} end]
])
tag_values_fun = metric.tag_values
event_metadata = %{controller: UserController, action: "create"}
assert %{constant: "metadata"} == tag_values_fun.(event_metadata)
end
test "setting function as filter returns that function in metric spec" do
keep_metric =
apply(Metrics, unquote(metric_type), [
"my.repo.query",
[
keep: &match?(%{repo: :my_app_read_only_repo}, &1)
]
])
drop_metric =
apply(Metrics, unquote(metric_type), [
"my.repo.query",
[
drop: &match?(%{repo: :my_app_read_only_repo}, &1)
]
])
keep_filter_fun = keep_metric.keep
assert keep_filter_fun.(%{repo: :my_app_read_only_repo})
refute keep_filter_fun.(%{repo: :my_app_repo})
drop_filter_fun = drop_metric.keep
refute drop_filter_fun.(%{repo: :my_app_read_only_repo})
assert drop_filter_fun.(%{repo: :my_app_repo})
end
test "setting both keep and drop options raises" do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"my.event.value",
[
keep: &match?(%{some: :value}, &1),
drop: &match?(%{some: :other_value}, &1)
]
])
end
end
test "using metric name with leading, trailing or subsequent dots raises" do
for name <- [".metric.name", "metric.name.", "metric..name"] do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
name
])
end
end
end
test "using event name with leading, trailing or subsequent dots raises" do
for event_name <- [".event.value", "event.value.", "event..name"] do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"my.metric",
[event_name: event_name]
])
end
end
end
test "tag_values fun can leave other keys than in metadata" do
tags = [:action, :some_tag]
tag_values_fun = fn metadata -> Map.put(metadata, :some_tag, "some_value") end
event_metadata = %{controller: UserController, action: :create}
metric =
apply(Metrics, unquote(metric_type), [
"my.event:value",
[tags: tags, tag_values: tag_values_fun]
])
tag_values = metric.tag_values.(event_metadata)
refute tags == Map.keys(tag_values)
end
test "setting term as measurement returns function returning value under that term in metric spec" do
metric =
apply(Metrics, unquote(metric_type), [
[:my, :event],
[measurement: :value]
])
assert :value == metric.measurement
end
test "setting unary function as measurement returns that function in metric spec" do
metric =
apply(Metrics, unquote(metric_type), [
[:my, :event],
[measurement: fn _ -> 42 end]
])
measurement_fun = metric.measurement
event_measurements = %{value: 3, other_value: 2}
assert 42 == measurement_fun.(event_measurements)
end
test "setting binary function as measurement returns that function in metric spec" do
metric =
apply(Metrics, unquote(metric_type), [
[:my, :event],
[measurement: fn _measurement, metadata -> length(metadata.messages) end]
])
measurement_fun = metric.measurement
event_measurements = %{value: 3, other_value: 2}
assert 42 ==
measurement_fun.(event_measurements, %{messages: List.duplicate("message", 42)})
end
test "metric name can be a list of atoms" do
metric =
apply(Metrics, unquote(metric_type), [
[:my, :event, :value]
])
assert [:my, :event, :value] == metric.name
assert [:my, :event] == metric.event_name
assert :value == metric.measurement
end
test "metric name can be a string" do
metric =
apply(Metrics, unquote(metric_type), [
"my.event.value"
])
assert [:my, :event, :value] == metric.name
assert [:my, :event] == metric.event_name
assert :value = metric.measurement
end
test "raises when metric name is empty" do
for name <- [[], ""] do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
name
])
end
end
end
test "raises when metric name is not a string or list of atoms" do
for name <- [nil, [nil]] do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [name])
end
end
end
test "raises when event name derived from metric name is empty" do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"latency"
])
end
end
test "raises when event name is empty" do
for event_name <- [[], ""] do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[event_name: event_name]
])
end
end
end
test "raises when event filter is not a function with an arity of 2" do
Enum.each([keep: fn -> true end, drop: fn -> true end], fn filter ->
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"ecto.query.queue_time",
[filter]
])
end
end)
end
test "raises when first element of unit-conversion tuple is not a valid time unit" do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:byte, :millisecond}]
])
end
end
test "raises when second element of unit-conversion tuple is not a valid time unit" do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:millisecond, :byte}]
])
end
end
test "raises when unit-conversion tuple is not a two-element tuple" do
assert_raise ArgumentError, fn ->
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:native, :millisecond, :nanosecond}]
])
end
end
test "sets the unit in the definition to the second element of the unit-conversion tuple" do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:native, :millisecond}]
])
assert metric.unit == :millisecond
end
test "does not raise when unit-conversion tuple is provided but measurement is nil" do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:native, :millisecond}]
])
assert metric.measurement.(%{latency: nil}) == nil
end
test "does not raise when unit-conversion tuple is provided but measurement is missing" do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.missing_measurement",
[unit: {:native, :millisecond}]
])
assert metric.measurement.(%{}) == nil
end
test "raises when unit-conversion tuple is provided but measurement is not a number" do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:native, :millisecond}]
])
assert_raise ArithmeticError, fn ->
metric.measurement.(%{latency: :not_a_number})
end
end
test "raises when unit-conversion tuple is provided but measurement function doesn't return a number" do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {:native, :millisecond}, measurement: fn _ -> :not_a_number end]
])
assert_raise ArithmeticError, fn ->
metric.measurement.(%{latency: 250})
end
end
test "doesn't raise when measurement is not a number but no unit-conversion is required" do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: :millisecond, measurement: fn _ -> :not_a_number end]
])
assert metric.measurement.(%{latency: 250}) == :not_a_number
end
test "doesn't convert a unit if both units are the same" do
for unit <- [
:native,
:second,
:millisecond,
:microsecond,
:nanosecond,
:byte,
:kilobyte,
:megabyte
] do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {unit, unit}]
])
refute is_function(metric.measurement)
end
end
test "converts a measurement under key from one regular time unit to another" do
units = [:native, :second, :millisecond, :microsecond, :nanosecond]
measurement = :rand.uniform(10_000_000)
# We need to filter out cases where conversion doesn't change anything, because then the
# measurement inside metric definition is not a function but a key, and the test fails.
# We also can't simply filter using `from != to`, because native is approximately equal to
# one of the regular time units, and the conversion ratio would still be equal to 1.
for from <- units, to <- units, measurement != converted_unit(measurement, from, to) do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {from, to}]
])
measurements = %{latency: measurement}
assert metric.measurement.(measurements) == converted_unit(measurement, from, to)
end
end
test "converts a measurement under key from one byte unit to another" do
units = [
{{:byte, 76_000_000}, {:kilobyte, 76_000}},
{{:byte, 76_000_000}, {:megabyte, 76}},
{{:kilobyte, 76_000}, {:byte, 76_000_000}},
{{:kilobyte, 76_000}, {:megabyte, 76}},
{{:megabyte, 76}, {:byte, 76_000_000}},
{{:megabyte, 76}, {:kilobyte, 76_000}}
]
for {{from, original}, {to, converted}} <- units do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {from, to}]
])
measurements = %{latency: original}
assert metric.measurement.(measurements) == converted
end
end
test "converts a result of measurement function from one regular time unit to another" do
units = [:native, :second, :millisecond, :microsecond, :nanosecond]
measurement = :rand.uniform(10_000_000)
for from <- units, to <- units, from != to do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {from, to}, measurement: fn _ -> measurement end]
])
assert metric.measurement.(%{}) == converted_unit(measurement, from, to)
end
end
test "converts a result of binary measurement function from one regular time unit to another" do
units = [:native, :second, :millisecond, :microsecond, :nanosecond]
measurement = :rand.uniform(10_000_000)
for from <- units, to <- units, from != to do
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {from, to}, measurement: fn _measurements, _metadata -> measurement end]
])
assert metric.measurement.(%{}, %{}) == converted_unit(measurement, from, to)
end
end
test "converts a result of measurement function from one regular byte unit to another" do
units = [
{{:byte, 76_000_000}, {:kilobyte, 76_000}},
{{:byte, 76_000_000}, {:megabyte, 76}},
{{:kilobyte, 76_000}, {:byte, 76_000_000}},
{{:kilobyte, 76_000}, {:megabyte, 76}},
{{:megabyte, 76}, {:byte, 76_000_000}},
{{:megabyte, 76}, {:kilobyte, 76_000}}
]
for {{from, original}, {to, converted}} <- units do
measurement = fn _ -> original end
metric =
apply(Metrics, unquote(metric_type), [
"http.request.latency",
[unit: {from, to}, measurement: measurement]
])
assert metric.measurement.(%{}) == converted
end
end
end
end
defp converted_unit(measurement, from_unit, to_unit) do
measurement * conversion_ratio(from_unit, to_unit)
end
defp conversion_ratio(unit, unit), do: 1
defp conversion_ratio(from, to) when from == :native or to == :native do
case System.convert_time_unit(1, from, to) do
0 ->
1 / System.convert_time_unit(1, to, from)
ratio ->
ratio
end
end
# Make the conversion for regular units more explicit in tests, so that we're sure we get the
# correct results.
defp conversion_ratio(:second, :millisecond), do: 1_000
defp conversion_ratio(:second, :microsecond), do: 1_000_000
defp conversion_ratio(:second, :nanosecond), do: 1_000_000_000
defp conversion_ratio(:millisecond, :microsecond), do: 1_000
defp conversion_ratio(:millisecond, :nanosecond), do: 1_000_000
defp conversion_ratio(:microsecond, :nanosecond), do: 1_000
defp conversion_ratio(from, to), do: 1 / conversion_ratio(to, from)
end
| 33.415929
| 110
| 0.5759
|
93a7466e2f892d5799176142c2526b8fd5a74016
| 2,685
|
ex
|
Elixir
|
lib/conduit/accounts/aggregates/user.ex
|
rudyyazdi/conduit
|
8defa60962482fb81f5093ea5d58b71a160db3c4
|
[
"MIT"
] | null | null | null |
lib/conduit/accounts/aggregates/user.ex
|
rudyyazdi/conduit
|
8defa60962482fb81f5093ea5d58b71a160db3c4
|
[
"MIT"
] | 2
|
2022-01-15T02:09:30.000Z
|
2022-01-22T10:18:43.000Z
|
lib/conduit/accounts/aggregates/user.ex
|
rudyyazdi/conduit
|
8defa60962482fb81f5093ea5d58b71a160db3c4
|
[
"MIT"
] | null | null | null |
defmodule Conduit.Accounts.Aggregates.User do
defstruct [
:uuid,
:username,
:email,
:hashed_password,
]
alias Conduit.Accounts.Aggregates.User
alias Conduit.Accounts.Commands.{
RegisterUser,
UpdateUser,
}
alias Conduit.Accounts.Events.{
UserEmailChanged,
UsernameChanged,
UserPasswordChanged,
UserRegistered,
}
@doc """
Register a new user
"""
def execute(%User{uuid: nil}, %RegisterUser{} = register) do
%UserRegistered{
user_uuid: register.user_uuid,
username: register.username,
email: register.email,
hashed_password: register.hashed_password,
}
end
@doc """
Update a user's username, email, and password
"""
def execute(%User{} = user, %UpdateUser{} = update) do
Enum.reduce([&username_changed/2, &email_changed/2, &password_changed/2], [], fn (change, events) ->
case change.(user, update) do
nil -> events
event -> [event | events]
end
end)
end
# state mutators
def apply(%User{} = user, %UserRegistered{} = registered) do
%User{user |
uuid: registered.user_uuid,
username: registered.username,
email: registered.email,
hashed_password: registered.hashed_password,
}
end
def apply(%User{} = user, %UsernameChanged{username: username}) do
%User{user | username: username}
end
def apply(%User{} = user, %UserEmailChanged{email: email}) do
%User{user | email: email}
end
def apply(%User{} = user, %UserPasswordChanged{hashed_password: hashed_password}) do
%User{user | hashed_password: hashed_password}
end
# private helpers
defp username_changed(%User{}, %UpdateUser{username: ""}), do: nil
defp username_changed(%User{username: username}, %UpdateUser{username: username}), do: nil
defp username_changed(%User{uuid: user_uuid}, %UpdateUser{username: username}) do
%UsernameChanged{
user_uuid: user_uuid,
username: username,
}
end
defp email_changed(%User{}, %UpdateUser{email: ""}), do: nil
defp email_changed(%User{email: email}, %UpdateUser{email: email}), do: nil
defp email_changed(%User{uuid: user_uuid}, %UpdateUser{email: email}) do
%UserEmailChanged{
user_uuid: user_uuid,
email: email,
}
end
defp password_changed(%User{}, %UpdateUser{hashed_password: ""}), do: nil
defp password_changed(%User{hashed_password: hashed_password}, %UpdateUser{hashed_password: hashed_password}), do: nil
defp password_changed(%User{uuid: user_uuid}, %UpdateUser{hashed_password: hashed_password}) do
%UserPasswordChanged{
user_uuid: user_uuid,
hashed_password: hashed_password,
}
end
end
| 27.680412
| 120
| 0.678212
|
93a7b53ce21a48d3b5bb74719657b18590940a9f
| 870
|
ex
|
Elixir
|
hiyoko/lib/hiyoko/application.ex
|
rykawamu/phoenix_liveview_template
|
4a8c354d927aeedfc31acd8e71b3900e762f987f
|
[
"MIT"
] | null | null | null |
hiyoko/lib/hiyoko/application.ex
|
rykawamu/phoenix_liveview_template
|
4a8c354d927aeedfc31acd8e71b3900e762f987f
|
[
"MIT"
] | 1
|
2019-09-11T14:22:29.000Z
|
2019-09-11T14:22:29.000Z
|
hiyoko/lib/hiyoko/application.ex
|
rykawamu/phoenix_liveview_practice_01
|
e30ab2304473a995a3b36335ceb212a9bbed012f
|
[
"MIT"
] | null | null | null |
defmodule Hiyoko.Application do
# See https://hexdocs.pm/elixir/Application.html
# for more information on OTP Applications
@moduledoc false
use Application
def start(_type, _args) do
# List all child processes to be supervised
children = [
# Start the endpoint when the application starts
HiyokoWeb.Endpoint
# Starts a worker by calling: Hiyoko.Worker.start_link(arg)
# {Hiyoko.Worker, arg},
]
# See https://hexdocs.pm/elixir/Supervisor.html
# for other strategies and supported options
opts = [strategy: :one_for_one, name: Hiyoko.Supervisor]
Supervisor.start_link(children, opts)
end
# Tell Phoenix to update the endpoint configuration
# whenever the application is updated.
def config_change(changed, _new, removed) do
HiyokoWeb.Endpoint.config_change(changed, removed)
:ok
end
end
| 29
| 65
| 0.718391
|
93a7b8e14c87065de462965dd9f44342033bfb07
| 10,546
|
ex
|
Elixir
|
lib/mix/lib/mix/tasks/profile.fprof.ex
|
andrewtimberlake/elixir
|
a1c4ffc897f9407fe7e739e20e697805fbbff810
|
[
"Apache-2.0"
] | 1
|
2019-10-11T01:36:26.000Z
|
2019-10-11T01:36:26.000Z
|
lib/mix/lib/mix/tasks/profile.fprof.ex
|
andrewtimberlake/elixir
|
a1c4ffc897f9407fe7e739e20e697805fbbff810
|
[
"Apache-2.0"
] | 1
|
2015-06-09T15:52:43.000Z
|
2015-06-09T15:52:43.000Z
|
lib/mix/lib/mix/tasks/profile.fprof.ex
|
andrewtimberlake/elixir
|
a1c4ffc897f9407fe7e739e20e697805fbbff810
|
[
"Apache-2.0"
] | null | null | null |
defmodule Mix.Tasks.Profile.Fprof do
use Mix.Task
@shortdoc "Profiles the given file or expression with fprof"
@moduledoc """
Profiles the given file or expression using Erlang's `fprof` tool.
`fprof` can be useful when you want to discover the bottlenecks of a
sequential code.
Before running the code, it invokes the `app.start` task which compiles
and loads your project. Then the target expression is profiled, together
with all processes which are spawned by it. Other processes (e.g. those
residing in the OTP application supervision tree) are not profiled.
To profile the code, you can use syntax similar to the `mix run` task:
mix profile.fprof -e Hello.world
mix profile.fprof my_script.exs arg1 arg2 arg3
This task is automatically reenabled, so you can profile multiple times
in the same Mix invocation.
## Command line options
* `--callers` - prints detailed information about immediate callers and called functions
* `--details` - includes profile data for each profiled process
* `--sort key` - sorts the output by given key: `acc` (default) or `own`
* `--eval`, `-e` - evaluates the given code
* `--require`, `-r` - requires pattern before running the command
* `--parallel`, `-p` - makes all requires parallel
* `--no-compile` - does not compile even if files require compilation
* `--no-deps-check` - does not check dependencies
* `--no-archives-check` - does not check archives
* `--no-start` - does not start applications after compilation
* `--no-elixir-version-check` - does not check the Elixir version from mix.exs
* `--no-warmup` - does not execute code once before profiling
## Profile output
Example output:
# CNT ACC (ms) OWN (ms)
Total 200279 1972.188 1964.579
:fprof.apply_start_stop/4 0 1972.188 0.012
anonymous fn/0 in :elixir_compiler_2 1 1972.167 0.001
Test.run/0 1 1972.166 0.007
Test.do_something/1 3 1972.131 0.040
Test.bottleneck/0 1 1599.490 0.007
...
The default output contains data gathered from all profiled processes.
All times are wall clock milliseconds. The columns have the following meaning:
* CNT - total number of invocations of the given function
* ACC - total time spent in the function
* OWN - time spent in the function, excluding the time of called functions
The first row (Total) is the sum of all functions executed in all profiled
processes. For the given output, we had a total of 200279 function calls and spent
about 2 seconds running the code.
More detailed information is returned if you provide the `--callers` and
`--details` options.
When `--callers` option is specified, you'll see expanded function entries:
Mod.caller1/0 3 200.000 0.017
Mod.caller2/0 2 100.000 0.017
Mod.some_function/0 5 300.000 0.017 <--
Mod.called1/0 4 250.000 0.010
Mod.called2/0 1 50.000 0.030
Here, the arrow (`<--`) indicates the __marked__ function - the function
described by this paragraph. You also see its immediate callers (above) and
called functions (below).
All the values of caller functions describe the marked function. For example,
the first row means that `Mod.caller1/0` invoked `Mod.some_function/0` 3 times.
200ms of the total time spent in `Mod.some_function/0` was spent processing
calls from this particular caller.
In contrast, the values for the called functions describe those functions, but
in the context of the marked function. For example, the last row means that
`Mod.called2/0` was called once by `Mod.some_function/0`, and in that case
the total time spent in the function was 50ms.
For a detailed explanation it's worth reading the analysis in
[Erlang/OTP documentation for fprof](http://www.erlang.org/doc/man/fprof.html#analysis).
## Caveats
You should be aware that the code being profiled is running in an anonymous
function which is invoked by [`:fprof` module](http://wwww.erlang.org/doc/man/fprof.html).
Thus, you'll see some additional entries in your profile output,
such as `:fprof` calls, an anonymous
function with high ACC time, or an `:undefined` function which represents
the outer caller (non-profiled code which started the profiler).
Also, keep in mind that profiling might significantly increase the running time
of the profiled processes. This might skew your results if, for example, those
processes perform some I/O operations, since running time of those operations
will remain unchanged, while CPU bound operations of the profiled processes
might take significantly longer. Thus, when profiling some intensive program,
try to reduce such dependencies, or be aware of the resulting bias.
Finally, it's advised to profile your program with the `prod` environment, since
this should provide more realistic insights into bottlenecks.
"""
@switches [
parallel: :boolean,
require: :keep,
eval: :keep,
config: :keep,
compile: :boolean,
deps_check: :boolean,
start: :boolean,
archives_check: :boolean,
details: :boolean,
callers: :boolean,
sort: :string,
elixir_version_check: :boolean,
warmup: :boolean,
parallel_require: :keep
]
@aliases [r: :require, p: :parallel, e: :eval, c: :config]
@impl true
def run(args) do
{opts, head} = OptionParser.parse_head!(args, aliases: @aliases, strict: @switches)
Mix.Task.reenable("profile.fprof")
Mix.Tasks.Run.run(
["--no-mix-exs" | args],
opts,
head,
&profile_code(&1, opts),
&profile_code(File.read!(&1), opts)
)
end
# Profiling functions
defp profile_code(code_string, opts) do
content =
quote do
unquote(__MODULE__).profile(
fn ->
unquote(Code.string_to_quoted!(code_string))
end,
unquote(Macro.escape(Enum.map(opts, &parse_opt/1)))
)
end
# Use compile_quoted since it leaves less noise than eval_quoted
Code.compile_quoted(content)
end
defp parse_opt({:sort, "acc"}), do: {:sort, :acc}
defp parse_opt({:sort, "own"}), do: {:sort, :own}
defp parse_opt({:sort, other}), do: Mix.raise("Invalid sort option: #{other}")
defp parse_opt(other), do: other
@doc """
Allows to programmatically run the `fprof` profiler on expression in `fun`.
## Options
* `:callers` - prints detailed information about immediate callers and called functions
* `:details` - includes profile data for each profiled process
* `:sort` - sorts the output by given key: `:acc` (default) or `:own`
"""
def profile(fun, opts \\ []) when is_function(fun, 0) do
fun
|> profile_and_analyse(opts)
|> print_output
end
defp profile_and_analyse(fun, opts) do
if Keyword.get(opts, :warmup, true) do
IO.puts("Warmup...")
fun.()
end
{:ok, tracer} = :fprof.profile(:start)
:fprof.apply(fun, [], tracer: tracer)
{:ok, analyse_dest} = StringIO.open("")
try do
:fprof.analyse(
dest: analyse_dest,
totals: true,
details: Keyword.get(opts, :details, false),
callers: Keyword.get(opts, :callers, false),
sort: Keyword.get(opts, :sort, :acc)
)
else
:ok ->
{_in, analysis_output} = StringIO.contents(analyse_dest)
String.to_charlist(analysis_output)
after
StringIO.close(analyse_dest)
end
end
defp print_output(analysis_output) do
{_analysis_options, analysis_output} = next_term(analysis_output)
{total_row, analysis_output} = next_term(analysis_output)
print_total_row(total_row)
Stream.unfold(analysis_output, &next_term/1)
|> Enum.each(&print_analysis_result/1)
end
defp next_term(charlist) do
case :erl_scan.tokens([], charlist, 1) do
{:done, result, leftover} ->
case result do
{:ok, tokens, _} ->
{:ok, term} = :erl_parse.parse_term(tokens)
{term, leftover}
{:eof, _} ->
nil
end
_ ->
nil
end
end
defp print_total_row([{:totals, count, acc, own}]) do
IO.puts("")
print_row(["s", "s", "s", "s", "s"], ["", "CNT", "ACC (ms)", "OWN (ms)", ""])
print_row(["s", "B", ".3f", ".3f", "s"], ["Total", count, acc, own, ""])
end
# Represents the "PID" entry
defp print_analysis_result([{pid_atom, count, :undefined, own} | info]) do
print_process(pid_atom, count, own)
if spawned_by = info[:spawned_by] do
IO.puts(" spawned by #{spawned_by}")
end
if spawned_as = info[:spawned_as] do
IO.puts(" as #{function_text(spawned_as)}")
end
if initial_calls = info[:initial_calls] do
IO.puts(" initial calls:")
Enum.each(initial_calls, &IO.puts(" #{function_text(&1)}"))
end
IO.puts("")
end
# The function entry, when --callers option is provided
defp print_analysis_result({callers, function, subcalls}) do
IO.puts("")
Enum.each(callers, &print_function/1)
print_function(function, " ", "<--")
Enum.each(subcalls, &print_function(&1, " "))
end
# The function entry in the total section, and when --callers option is not
# provided
defp print_analysis_result({_fun, _count, _acc, _own} = function) do
print_function(function, "", "")
end
defp print_process(pid_atom, count, own) do
IO.puts([?\n, String.duplicate("-", 100)])
print_row(["s", "B", "s", ".3f", "s"], ["#{pid_atom}", count, "", own, ""])
end
defp print_function({fun, count, acc, own}, prefix \\ "", suffix \\ "") do
text = "#{prefix}#{function_text(fun)}"
print_row(["s", "B", ".3f", ".3f", "s"], [text, count, acc, own, suffix])
end
defp function_text({module, function, arity}) do
Exception.format_mfa(module, function, arity)
end
defp function_text(other), do: inspect(other)
@columns [-60, 10, 12, 12, 5]
defp print_row(formats, data) do
Stream.zip(@columns, formats)
|> Stream.map(fn {width, format} -> "~#{width}#{format}" end)
|> Enum.join()
|> :io.format(data)
IO.puts("")
end
end
| 34.92053
| 92
| 0.639389
|
93a7c543acdc8e83d3e7ad89eaea8fe0274a9ad8
| 3,507
|
ex
|
Elixir
|
lib/codes/codes_h46.ex
|
badubizzle/icd_code
|
4c625733f92b7b1d616e272abc3009bb8b916c0c
|
[
"Apache-2.0"
] | null | null | null |
lib/codes/codes_h46.ex
|
badubizzle/icd_code
|
4c625733f92b7b1d616e272abc3009bb8b916c0c
|
[
"Apache-2.0"
] | null | null | null |
lib/codes/codes_h46.ex
|
badubizzle/icd_code
|
4c625733f92b7b1d616e272abc3009bb8b916c0c
|
[
"Apache-2.0"
] | null | null | null |
defmodule IcdCode.ICDCode.Codes_H46 do
alias IcdCode.ICDCode
def _H4600 do
%ICDCode{full_code: "H4600",
category_code: "H46",
short_code: "00",
full_name: "Optic papillitis, unspecified eye",
short_name: "Optic papillitis, unspecified eye",
category_name: "Optic papillitis, unspecified eye"
}
end
def _H4601 do
%ICDCode{full_code: "H4601",
category_code: "H46",
short_code: "01",
full_name: "Optic papillitis, right eye",
short_name: "Optic papillitis, right eye",
category_name: "Optic papillitis, right eye"
}
end
def _H4602 do
%ICDCode{full_code: "H4602",
category_code: "H46",
short_code: "02",
full_name: "Optic papillitis, left eye",
short_name: "Optic papillitis, left eye",
category_name: "Optic papillitis, left eye"
}
end
def _H4603 do
%ICDCode{full_code: "H4603",
category_code: "H46",
short_code: "03",
full_name: "Optic papillitis, bilateral",
short_name: "Optic papillitis, bilateral",
category_name: "Optic papillitis, bilateral"
}
end
def _H4610 do
%ICDCode{full_code: "H4610",
category_code: "H46",
short_code: "10",
full_name: "Retrobulbar neuritis, unspecified eye",
short_name: "Retrobulbar neuritis, unspecified eye",
category_name: "Retrobulbar neuritis, unspecified eye"
}
end
def _H4611 do
%ICDCode{full_code: "H4611",
category_code: "H46",
short_code: "11",
full_name: "Retrobulbar neuritis, right eye",
short_name: "Retrobulbar neuritis, right eye",
category_name: "Retrobulbar neuritis, right eye"
}
end
def _H4612 do
%ICDCode{full_code: "H4612",
category_code: "H46",
short_code: "12",
full_name: "Retrobulbar neuritis, left eye",
short_name: "Retrobulbar neuritis, left eye",
category_name: "Retrobulbar neuritis, left eye"
}
end
def _H4613 do
%ICDCode{full_code: "H4613",
category_code: "H46",
short_code: "13",
full_name: "Retrobulbar neuritis, bilateral",
short_name: "Retrobulbar neuritis, bilateral",
category_name: "Retrobulbar neuritis, bilateral"
}
end
def _H462 do
%ICDCode{full_code: "H462",
category_code: "H46",
short_code: "2",
full_name: "Nutritional optic neuropathy",
short_name: "Nutritional optic neuropathy",
category_name: "Nutritional optic neuropathy"
}
end
def _H463 do
%ICDCode{full_code: "H463",
category_code: "H46",
short_code: "3",
full_name: "Toxic optic neuropathy",
short_name: "Toxic optic neuropathy",
category_name: "Toxic optic neuropathy"
}
end
def _H468 do
%ICDCode{full_code: "H468",
category_code: "H46",
short_code: "8",
full_name: "Other optic neuritis",
short_name: "Other optic neuritis",
category_name: "Other optic neuritis"
}
end
def _H469 do
%ICDCode{full_code: "H469",
category_code: "H46",
short_code: "9",
full_name: "Unspecified optic neuritis",
short_name: "Unspecified optic neuritis",
category_name: "Unspecified optic neuritis"
}
end
end
| 30.495652
| 64
| 0.59424
|
93a7f27c874056f5cd315a511820da29d2b1c978
| 196
|
ex
|
Elixir
|
test/support/conn_case.ex
|
liberumed/authable
|
6db9951aa07000b358f16ffe413a13aa9aa89192
|
[
"Unlicense"
] | null | null | null |
test/support/conn_case.ex
|
liberumed/authable
|
6db9951aa07000b358f16ffe413a13aa9aa89192
|
[
"Unlicense"
] | null | null | null |
test/support/conn_case.ex
|
liberumed/authable
|
6db9951aa07000b358f16ffe413a13aa9aa89192
|
[
"Unlicense"
] | 1
|
2021-01-12T00:55:56.000Z
|
2021-01-12T00:55:56.000Z
|
defmodule Authable.ConnCase do
@moduledoc """
Conveniences for testing Plug endpoints
"""
@doc false
defmacro __using__(_) do
quote do
use Authable.ConnTest
end
end
end
| 15.076923
| 41
| 0.683673
|
93a804d355ed6690b14af0b78d049312af952dcc
| 397
|
ex
|
Elixir
|
test/examples/type/record.ex
|
esl/gradient
|
822da399872a38b77440858971f4147694e85fac
|
[
"Apache-2.0"
] | 75
|
2021-11-17T11:55:13.000Z
|
2022-03-28T04:35:04.000Z
|
test/examples/type/record.ex
|
esl/gradient
|
822da399872a38b77440858971f4147694e85fac
|
[
"Apache-2.0"
] | 48
|
2021-11-15T13:56:14.000Z
|
2022-03-31T15:55:47.000Z
|
test/examples/type/record.ex
|
esl/gradient
|
822da399872a38b77440858971f4147694e85fac
|
[
"Apache-2.0"
] | 6
|
2021-12-22T20:41:27.000Z
|
2022-03-09T09:07:38.000Z
|
defmodule RecordType do
require Record
Record.defrecord(:user, name: "john", age: 25)
@type user :: record(:user, name: String.t(), age: integer)
@spec ret_wrong_record() :: user()
def ret_wrong_record(), do: :ok
@spec ret_wrong_record2() :: user()
def ret_wrong_record2(), do: user(name: 12)
@spec ret_wrong_atom() :: atom()
def ret_wrong_atom(), do: user(name: "Kate")
end
| 24.8125
| 61
| 0.667506
|
93a81a9426e536576a435456bdcb923f62da8378
| 2,722
|
ex
|
Elixir
|
clients/access_approval/lib/google_api/access_approval/v1/model/enrolled_service.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"Apache-2.0"
] | null | null | null |
clients/access_approval/lib/google_api/access_approval/v1/model/enrolled_service.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"Apache-2.0"
] | null | null | null |
clients/access_approval/lib/google_api/access_approval/v1/model/enrolled_service.ex
|
jechol/elixir-google-api
|
0290b683dfc6491ca2ef755a80bc329378738d03
|
[
"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.EnrolledService do
@moduledoc """
Represents the enrollment of a cloud resource into a specific service.
## Attributes
* `cloudProduct` (*type:* `String.t`, *default:* `nil`) - The product for which Access Approval will be enrolled. Allowed values are listed below (case-sensitive): * all * App Engine * BigQuery * Cloud Bigtable * Cloud Key Management Service * Compute Engine * Cloud Dataflow * Cloud Identity and Access Management * Cloud Logging * Cloud Pub/Sub * Cloud Spanner * Cloud Storage * Persistent Disk Note: These values are supported as input for legacy purposes, but will not be returned from the API. * all * appengine.googleapis.com * bigquery.googleapis.com * bigtable.googleapis.com * cloudkms.googleapis.com * compute.googleapis.com * dataflow.googleapis.com * iam.googleapis.com * logging.googleapis.com * pubsub.googleapis.com * spanner.googleapis.com * storage.googleapis.com Calls to UpdateAccessApprovalSettings using 'all' or any of the XXX.googleapis.com will be translated to the associated product name ('all', 'App Engine', etc.). Note: 'all' will enroll the resource in all products supported at both 'GA' and 'Preview' levels. More information about levels of support is available at https://cloud.google.com/access-approval/docs/supported-services
* `enrollmentLevel` (*type:* `String.t`, *default:* `nil`) - The enrollment level of the service.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:cloudProduct => String.t() | nil,
:enrollmentLevel => String.t() | nil
}
field(:cloudProduct)
field(:enrollmentLevel)
end
defimpl Poison.Decoder, for: GoogleApi.AccessApproval.V1.Model.EnrolledService do
def decode(value, options) do
GoogleApi.AccessApproval.V1.Model.EnrolledService.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AccessApproval.V1.Model.EnrolledService do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 54.44
| 1,166
| 0.753123
|
93a81b2492235e0c0e5863d13f03eb6f69cadc83
| 3,498
|
ex
|
Elixir
|
messages/elixir/lib/cucumber_messages/writer.ex
|
alvivi/cucumber
|
647e4c9a46d441fb6d86b22138ad44580d500f75
|
[
"MIT"
] | 1
|
2020-12-14T07:17:55.000Z
|
2020-12-14T07:17:55.000Z
|
messages/elixir/lib/cucumber_messages/writer.ex
|
alvivi/cucumber
|
647e4c9a46d441fb6d86b22138ad44580d500f75
|
[
"MIT"
] | 19
|
2020-10-12T19:50:12.000Z
|
2022-01-10T02:52:01.000Z
|
messages/elixir/lib/cucumber_messages/writer.ex
|
alvivi/cucumber
|
647e4c9a46d441fb6d86b22138ad44580d500f75
|
[
"MIT"
] | null | null | null |
defmodule CucumberMessages.Writer do
@moduledoc false
# This is a temporary writer up until Protox supports json encoding
alias CucumberMessages.Envelope
alias CucumberMessages.Location
alias CucumberMessages.Pickle.PickleStep
alias CucumberMessages.GherkinDocument.Feature.FeatureChild
alias CucumberMessages.PickleStepArgument.{PickleDocString, PickleTable}
defp unstruct(%Location{column: 0} = map, acc) do
map |> Map.from_struct() |> Map.delete(:column) |> unstruct(acc)
end
defp unstruct(%{__struct__: _} = map, acc) when is_map(map) do
map |> Map.from_struct() |> unstruct(acc)
end
defp unstruct(%{__uf__: _} = map, acc) when is_map(map) do
map |> Map.delete(:__uf__) |> unstruct(acc)
end
defp unstruct(map, acc) when is_map(map) do
Enum.reduce(map, acc, fn
:ignore, acc ->
acc
{_k, nil}, acc ->
acc
{_k, ""}, acc ->
acc
{_k, :ignore}, acc ->
acc
{_k, []}, acc ->
acc
{_k, {new_key, v}}, acc when is_map(v) or is_list(v) ->
Map.put(acc, lower_camelcase(new_key), unstruct(v, %{}))
{k, v}, acc when is_map(v) or is_list(v) ->
Map.put(acc, lower_camelcase(k), unstruct(v, %{}))
{k, data}, acc ->
Map.put(acc, lower_camelcase(k), unstruct(data, %{}))
end)
end
defp unstruct([], %{}) do
:ignore
end
defp unstruct(list, acc) when is_list(list) do
list
|> Enum.map(fn
%FeatureChild{} = el ->
el.value
%PickleStep{argument: %PickleTable{}} = el ->
Map.put(el, :argument, %{dataTable: el.argument}) |> Map.delete(:__struct__)
%PickleStep{argument: %PickleDocString{}} = el ->
Map.put(el, :argument, %{docString: el.argument}) |> Map.delete(:__struct__)
other_el ->
other_el
end)
|> Enum.reduce(acc, fn
{_new_key, nil}, acc ->
acc
{new_key, value}, acc when is_map(acc) ->
# Map.put(acc, lower_camelcase(new_key), unstruct(value, %{}))
[Map.put(acc, lower_camelcase(new_key), unstruct(value, %{}))]
{new_key, value}, acc when is_list(acc) ->
unstructed = unstruct(value, %{})
case unstructed do
:ignore -> acc
_ -> acc ++ [Map.put(%{}, lower_camelcase(new_key), unstructed)]
end
map, acc when is_map(acc) and acc == %{} ->
unstructed = unstruct(map, %{})
case unstructed do
:ignore -> acc
_ -> [unstruct(map, %{})]
end
map, acc ->
unstructed = unstruct(map, %{})
case unstructed do
:ignore -> acc
_ -> acc ++ [unstruct(map, %{})]
end
end)
end
defp unstruct({k, v}, acc) when not is_tuple(v),
do: Map.put(acc, lower_camelcase(k), unstruct(v, %{}))
defp unstruct(just_data, _acc) when not is_tuple(just_data), do: just_data
def envelope_to_ndjson!(%Envelope{} = message) do
# This is sort of a sanity check to see whether the constructed message is
# proto compliant
# As soon as Protox supports json encoding, this is no longer necessary
message |> Protox.Encode.encode!()
unstruct(message, %{})
end
defp lower_camelcase(atom) when is_atom(atom), do: atom |> Atom.to_string() |> lower_camelcase()
defp lower_camelcase(string) when is_binary(string) do
{to_be_downcased, camelcased} = string |> Macro.camelize() |> String.split_at(1)
String.downcase(to_be_downcased) <> camelcased
end
end
| 27.984
| 98
| 0.604345
|
93a828f2050013cc811e9be870fe80b1b20a2c0e
| 1,136
|
ex
|
Elixir
|
apps/ex_wire/lib/ex_wire/kademlia/config.ex
|
wolflee/mana
|
db66dac85addfaad98d40da5bd4082b3a0198bb1
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 152
|
2018-10-27T04:52:03.000Z
|
2022-03-26T10:34:00.000Z
|
apps/ex_wire/lib/ex_wire/kademlia/config.ex
|
wolflee/mana
|
db66dac85addfaad98d40da5bd4082b3a0198bb1
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 270
|
2018-04-14T07:34:57.000Z
|
2018-10-25T18:10:45.000Z
|
apps/ex_wire/lib/ex_wire/kademlia/config.ex
|
wolflee/mana
|
db66dac85addfaad98d40da5bd4082b3a0198bb1
|
[
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 25
|
2018-10-27T12:15:13.000Z
|
2022-01-25T20:31:14.000Z
|
defmodule ExWire.Kademlia.Config do
@moduledoc """
Contains params related to Kademlia algorithm.
https://pdos.csail.mit.edu/~petar/papers/maymounkov-kademlia-lncs.pdf
"""
# k
@bucket_size 16
# alpha
@concurrency 3
# key size. 0 <= i < @id_size - number of buckets
@id_size 256
# b
@bits_per_hop 8
# in ms
@eviction_check_interval 75
# in ms
@request_timeout 300
# in s
@bucket_refresh_interval 3600
@spec bucket_size() :: unquote(@bucket_size)
def bucket_size, do: @bucket_size
@spec concurrency() :: unquote(@concurrency)
def concurrency, do: @concurrency
@spec id_size() :: unquote(@id_size)
def id_size, do: @id_size
@spec bits_per_hop() :: unquote(@bits_per_hop)
def bits_per_hop, do: @bits_per_hop
@spec eviction_check_interval() :: unquote(@eviction_check_interval)
def eviction_check_interval, do: @eviction_check_interval
@spec request_timeout() :: unquote(@request_timeout)
def request_timeout, do: @request_timeout
@spec bucket_refresh_interval() :: unquote(@bucket_refresh_interval)
def bucket_refresh_interval, do: @bucket_refresh_interval
end
| 22.72
| 71
| 0.727113
|
93a832cd759b0c4914c077bd7e74fb43591d52d2
| 578
|
exs
|
Elixir
|
memory-master/test/memory_web/views/error_view_test.exs
|
Wycode-fish/WEBDEV-MEMORY-GAME
|
1b04f995fb1a545781206a7fd01de0a1bb75d86c
|
[
"MIT"
] | null | null | null |
memory-master/test/memory_web/views/error_view_test.exs
|
Wycode-fish/WEBDEV-MEMORY-GAME
|
1b04f995fb1a545781206a7fd01de0a1bb75d86c
|
[
"MIT"
] | null | null | null |
memory-master/test/memory_web/views/error_view_test.exs
|
Wycode-fish/WEBDEV-MEMORY-GAME
|
1b04f995fb1a545781206a7fd01de0a1bb75d86c
|
[
"MIT"
] | null | null | null |
defmodule MemoryWeb.ErrorViewTest do
use MemoryWeb.ConnCase, async: true
# Bring render/3 and render_to_string/3 for testing custom views
import Phoenix.View
test "renders 404.html" do
assert render_to_string(MemoryWeb.ErrorView, "404.html", []) ==
"Page not found"
end
test "render 500.html" do
assert render_to_string(MemoryWeb.ErrorView, "500.html", []) ==
"Internal server error"
end
test "render any other" do
assert render_to_string(MemoryWeb.ErrorView, "505.html", []) ==
"Internal server error"
end
end
| 26.272727
| 67
| 0.681661
|
93a83eb2e74ff242750154b3a4a8758fee753688
| 4,673
|
exs
|
Elixir
|
test/surface/components/dynamic/live_component_test.exs
|
RudolfMan/surface
|
ee8c1546b77c91fe08e7360e64666c613bc5a900
|
[
"MIT"
] | null | null | null |
test/surface/components/dynamic/live_component_test.exs
|
RudolfMan/surface
|
ee8c1546b77c91fe08e7360e64666c613bc5a900
|
[
"MIT"
] | null | null | null |
test/surface/components/dynamic/live_component_test.exs
|
RudolfMan/surface
|
ee8c1546b77c91fe08e7360e64666c613bc5a900
|
[
"MIT"
] | null | null | null |
defmodule Surface.Components.Dynamic.LiveComponentTest do
use Surface.ConnCase, async: true
alias Surface.Components.Dynamic.LiveComponent
import ExUnit.CaptureIO
defmodule StatefulComponent do
use Surface.LiveComponent
data label, :string, default: "Initial stateful"
data assigned_in_update, :any
def update(_assigns, socket) do
{:ok, assign(socket, assigned_in_update: "Assigned in update/2")}
end
def render(assigns) do
~F"""
<div :on-click="click" id="theDiv">{@label} - {@assigned_in_update}</div>
"""
end
def handle_event("click", _, socket) do
{:noreply, assign(socket, label: "Updated stateful")}
end
end
defmodule StatefulComponentWithDefaultSlot do
use Surface.LiveComponent
slot default
prop label, :string
def render(assigns) do
~F"""
<div id="theDiv">
<#slot/>
{@label}
</div>
"""
end
end
defmodule StatefulComponentWithEvent do
use Surface.LiveComponent
prop click, :event
def render(assigns) do
~F"""
<div :on-click={@click}/>
"""
end
end
defmodule View do
use Surface.LiveView
alias Surface.Components.Dynamic.LiveComponent
def render(assigns) do
module = StatefulComponent
~F"""
<LiveComponent module={module} id="comp"/>
"""
end
def handle_event("click", _, socket) do
{:noreply, assign(socket, label: "Updated stateless")}
end
end
defmodule ViewWithInnerContent do
use Surface.LiveView
alias Surface.Components.Dynamic.LiveComponent
def render(assigns) do
module = StatefulComponentWithDefaultSlot
~F"""
<LiveComponent module={module} id="comp" label="my label">
<span>Inner</span>
</LiveComponent>
"""
end
end
test "render LiveComponent" do
{:ok, _view, html} = live_isolated(build_conn(), View)
assert html =~ "Initial stateful"
end
test "render LiveComponent and check props" do
{:ok, _view, html} = live_isolated(build_conn(), ViewWithInnerContent)
assert html =~ "my label"
end
test "render LiveComponent with default slot" do
{:ok, _view, html} = live_isolated(build_conn(), ViewWithInnerContent)
assert html =~ "Inner"
end
test "render data assigned in update/2" do
{:ok, _view, html} = live_isolated(build_conn(), View)
assert html =~ "Assigned in update/2"
end
test "attribute values are still converted according to their types but only at runtime" do
html =
render_surface do
~F"""
<LiveComponent module={StatefulComponentWithEvent} id="comp" click={"ok", target: "#comp"}/>
"""
end
event = Phoenix.HTML.Engine.html_escape(~S([["push",{"event":"ok","target":"#comp"}]]))
assert html =~ """
<div phx-click="#{event}"></div>
"""
end
test "at runtime, warn on unknown attributes at the component definition's file/line " do
file = Path.relative_to_cwd(__ENV__.file)
line = __ENV__.line + 8
output =
capture_io(:standard_error, fn ->
assigns = %{mod: StatefulComponentWithEvent}
render_surface do
~F"""
<LiveComponent
module={@mod}
id="comp"
unknown_attr="123"
/>
"""
end
end)
assert output =~ ~r"""
Unknown property "unknown_attr" for component <Surface.Components.Dynamic.LiveComponentTest.StatefulComponentWithEvent>
#{file}:#{line}: Surface.Components.Dynamic.LiveComponentTest \(module\)\
"""
end
test "at runtime, warn on unknown attributes as expr at the component definition's file/line " do
file = Path.relative_to_cwd(__ENV__.file)
line = __ENV__.line + 8
output =
capture_io(:standard_error, fn ->
assigns = %{mod: StatefulComponentWithEvent, var: 123}
render_surface do
~F"""
<LiveComponent
module={@mod}
id="comp"
unknown_attr={@var}
/>
"""
end
end)
assert output =~ ~r"""
Unknown property "unknown_attr" for component <Surface.Components.Dynamic.LiveComponentTest.StatefulComponentWithEvent>
#{file}:#{line}: Surface.Components.Dynamic.LiveComponentTest \(module\)\
"""
end
# TODO: Uncomment when update to LV v0.17.6
# test "handle events in LiveComponent (handled by the component itself)" do
# {:ok, view, _html} = live_isolated(build_conn(), View)
# assert render_click(element(view, "#theDiv")) =~ "Updated stateful"
# end
end
| 25.961111
| 130
| 0.623154
|
93a85b57bb40edc2cd4fc05fbf2bf23bde6031cb
| 932
|
ex
|
Elixir
|
debian/postrm.ex
|
catalyst/gotiller
|
409007c3abc99e0ac5c227f17cdeac1fc3b74da1
|
[
"MIT"
] | null | null | null |
debian/postrm.ex
|
catalyst/gotiller
|
409007c3abc99e0ac5c227f17cdeac1fc3b74da1
|
[
"MIT"
] | null | null | null |
debian/postrm.ex
|
catalyst/gotiller
|
409007c3abc99e0ac5c227f17cdeac1fc3b74da1
|
[
"MIT"
] | null | null | null |
#!/bin/sh
# postrm script for gotiller
#
# see: dh_installdeb(1)
set -e
# summary of how this script can be called:
# * <postrm> `remove'
# * <postrm> `purge'
# * <old-postrm> `upgrade' <new-version>
# * <new-postrm> `failed-upgrade' <old-version>
# * <new-postrm> `abort-install'
# * <new-postrm> `abort-install' <old-version>
# * <new-postrm> `abort-upgrade' <old-version>
# * <disappearer's-postrm> `disappear' <overwriter>
# <overwriter-version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package
case "$1" in
purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear)
;;
*)
echo "postrm called with unknown argument \`$1'" >&2
exit 1
;;
esac
# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.
#DEBHELPER#
exit 0
| 24.526316
| 78
| 0.628755
|
93a85ca66d9d36ee1e050841d5749fb4b9a048b6
| 878
|
ex
|
Elixir
|
lib/halloween.ex
|
ajfAfg/HaLLoween
|
bbf762f1764c495561eb73eafb6cc88713ad5cb6
|
[
"MIT"
] | null | null | null |
lib/halloween.ex
|
ajfAfg/HaLLoween
|
bbf762f1764c495561eb73eafb6cc88713ad5cb6
|
[
"MIT"
] | null | null | null |
lib/halloween.ex
|
ajfAfg/HaLLoween
|
bbf762f1764c495561eb73eafb6cc88713ad5cb6
|
[
"MIT"
] | null | null | null |
defmodule Halloween do
@low_border 20
@high_border 100
@moduledoc """
Documentation for `Halloween`.
"""
def to_halloween(text, halloween) do
text
|> String.split("\n")
|> Enum.map(fn line ->
line
|> String.split()
|> Enum.map(&halloween_with_halloween(&1, halloween))
|> Enum.join(" ")
end)
|> Enum.join("\n")
end
def halloween_with_halloween(str, halloween) do
if rand() <= halloween do
halloween |> to_halloween_level() |> halloween()
else
str
end
end
def to_halloween_level(n) when n <= @low_border, do: :low
def to_halloween_level(n) when @high_border <= n, do: :high
def to_halloween_level(_), do: :midium
def halloween(:low), do: "HALLOWEEN"
def halloween(:midium), do: "HALLOWEEN!"
def halloween(:high), do: "HALLOWEEN..."
defp rand(), do: Enum.random(1..100)
end
| 22.512821
| 61
| 0.626424
|
93a868716e275a27b6d17fde4abb7213e11c2f68
| 3,040
|
ex
|
Elixir
|
lib/quadquizaminos_web/live/admin_live.ex
|
sparrell/quizquadaminos
|
6388252b7c32aa4101486cbf45d0d57d4e3a79da
|
[
"MIT"
] | 1
|
2022-01-11T20:06:31.000Z
|
2022-01-11T20:06:31.000Z
|
lib/quadquizaminos_web/live/admin_live.ex
|
sFractal-Podii/quizquadaminos
|
4c9023b9c6212a92741b0f21d9eb05871aa73916
|
[
"MIT"
] | 484
|
2021-02-15T18:43:40.000Z
|
2022-03-29T12:27:24.000Z
|
lib/quadquizaminos_web/live/admin_live.ex
|
sFractal-Podii/quizquadaminos
|
4c9023b9c6212a92741b0f21d9eb05871aa73916
|
[
"MIT"
] | 8
|
2021-02-15T19:12:51.000Z
|
2021-12-15T03:02:46.000Z
|
defmodule QuadquizaminosWeb.AdminLive do
use Phoenix.LiveView
alias Quadquizaminos.Accounts
import Phoenix.HTML, only: [raw: 1]
def mount(_param, _session, socket) do
{:ok,
socket
|> assign(
by_config: selected?("by_config"),
oauth_login: selected?("oauth_login"),
anonymous_login: selected?("anonymous_login"),
login_levels: ["by_config", "oauth_login", "anonymous_login"],
cleared?: false
)}
end
def render(assigns) do
~L"""
<div class="container">
<h1>users level of login</h1>
<section class="phx-hero">
<h3><%= notification(assigns) %></h3>
</section>
<form phx-change="login_levels">
<label>
<input type="radio" id="by_config" name="login_levels" value="by_config" <%= if @by_config, do: 'checked' %>> by_config
</label>
<label>
<input type="radio" id="oauth_login" name="login_levels" value="oauth_login" <%= if @oauth_login, do: 'checked' %>> oauth_login
</label>
<label>
<input type="radio" id="anonymous_login" name="login_levels" value="anonymous_login" <%= if @anonymous_login, do: 'checked' %>>anonymous_login
</label>
</form>
<%= if @cleared? do %>
<div class="alert-info" >
<p> Game score records have been cleared </p>
</div>
<% end %>
<h2> Reset game table </h2>
<%= raw reset_game_table_button() %>
</div>
"""
end
defp reset_game_table_button do
"""
<button phx-click="reset-game-table" data-confirm="Are you sure you want to reset all scores?">Reset All Scores</button>
"""
end
def handle_event("reset-game-table", _, socket) do
{_count, _} = Quadquizaminos.Repo.delete_all(Quadquizaminos.GameBoard)
{:noreply, socket |> assign(cleared?: true)}
end
def handle_event("login_levels", %{"login_levels" => selected_level}, socket) do
initially_selected_level = initially_selected_level(selected_level, socket)
{:noreply, update_login_level(socket, selected_level, initially_selected_level)}
end
defp update_login_level(socket, selected_level, initially_selected_level) do
case Accounts.update_login_level(selected_level, initially_selected_level) do
{:ok, _} ->
socket
|> assign(to_atom(initially_selected_level), false)
|> assign(to_atom(selected_level), true)
_ ->
socket
end
end
defp notification(assigns) do
~L"""
<%= if @by_config, do: "by_config is active" %>
<%= if @oauth_login, do: "oauth_login is active" %>
<%= if @anonymous_login, do: "anonymous_login is active" %>
"""
end
defp selected?(level) do
Accounts.get_login_level(level).active
end
defp initially_selected_level(selected_level, socket) do
[first_level | [second_level]] = socket.assigns.login_levels -- [selected_level]
case Map.get(socket.assigns, String.to_atom(first_level)) do
true -> first_level
_ -> second_level
end
end
defp to_atom(login_level) do
String.to_atom(login_level)
end
end
| 29.803922
| 146
| 0.657895
|
93a872446f9a8b61f6298e7ae9603fc82c8e5a47
| 1,173
|
ex
|
Elixir
|
lib/ecto/fixtures.ex
|
bcardarella/elixir-fixtures
|
2c49e0af3713bd912dc7bb639324da423d155299
|
[
"MIT"
] | 139
|
2016-02-07T12:28:18.000Z
|
2022-02-15T11:39:58.000Z
|
lib/ecto/fixtures.ex
|
bcardarella/elixir-fixtures
|
2c49e0af3713bd912dc7bb639324da423d155299
|
[
"MIT"
] | 17
|
2016-05-16T18:59:26.000Z
|
2020-09-11T16:53:53.000Z
|
lib/ecto/fixtures.ex
|
bcardarella/elixir-fixtures
|
2c49e0af3713bd912dc7bb639324da423d155299
|
[
"MIT"
] | 10
|
2016-02-23T09:25:09.000Z
|
2020-02-29T14:21:21.000Z
|
defmodule EctoFixtures do
def read(file_path), do: {String.to_atom(file_path), File.read!(file_path)}
def parse(content), do: EctoFixtures.Parser.process(content)
def condition(data, opts \\ []), do: EctoFixtures.Conditioner.process(data, opts)
def insert(data, can_insert), do: EctoFixtures.Insertion.process(data, can_insert)
def normalize(data), do: EctoFixtures.Normalizer.process(data)
def fixtures(name) do
fixtures(name, insert: true)
end
def fixtures(name, %{}=override) do
fixtures(name, insert: true, override: override)
end
def fixtures(name, opts) do
source = "test/fixtures/#{name}.exs"
read(source)
|> parse
|> condition(source: String.to_atom(source), override: opts[:override])
|> insert(opts[:insert])
end
defmacro __using__([]) do
quote do
import EctoFixtures, only: [fixtures: 1, fixtures: 2]
setup context do
data =
context[:fixtures]
|> List.wrap()
|> Enum.reduce(%{}, fn(source, data) ->
EctoFixtures.Utils.deep_merge(data, EctoFixtures.fixtures(source))
end)
{:ok, [data: data]}
end
end
end
end
| 27.928571
| 84
| 0.647911
|
93a877e5bef45e8971707f18ac1dd72a17e05b4c
| 2,008
|
ex
|
Elixir
|
lib/termDirectory/modules/module.ex
|
nliechti/termDirectory
|
267b3025c14e26575c7a9483692e94a7bf29e5fe
|
[
"MIT"
] | 1
|
2019-03-15T15:40:24.000Z
|
2019-03-15T15:40:24.000Z
|
lib/termDirectory/modules/module.ex
|
nliechti/termDirectory
|
267b3025c14e26575c7a9483692e94a7bf29e5fe
|
[
"MIT"
] | null | null | null |
lib/termDirectory/modules/module.ex
|
nliechti/termDirectory
|
267b3025c14e26575c7a9483692e94a7bf29e5fe
|
[
"MIT"
] | null | null | null |
defmodule TermDirectory.Modules.Module do
@moduledoc """
Schema and funtions to the module "object"
"""
use Ecto.Schema
import Ecto.Changeset
alias TermDirectory.Repo
alias TermDirectory.User.Teacher
alias TermDirectory.Modules
require Logger
schema "modules" do
many_to_many :module_workers, Teacher, join_through: Modules.ModuleWorker, on_replace: :delete
field :shortName, :string
field :subject, :string
belongs_to :responsible_teacher, Teacher
has_many :facts, Modules.Fact
timestamps()
end
@doc false
def changeset(module, attrs) do
preloaded_attrs = preload_attrs(attrs)
preloaded_attrs |> inspect |> Logger.info
module
|> Repo.preload(:responsible_teacher)
|> Repo.preload(:module_workers)
|> cast(preloaded_attrs, [:subject, :shortName, :responsible_teacher_id])
|> validate_required([:subject, :shortName, :responsible_teacher_id])
|> foreign_key_constraint(:responsible_teacher_id)
|> cast_assoc(:responsible_teacher)
|> put_assoc(:module_workers, preloaded_attrs["module_workers"], required: false)
end
# Preload needed attributes to the module that should be loaded
defp preload_attrs(attrs) do
attrs
|> preload_module_workers
end
# Preload the module workers that belong to the given module
defp preload_module_workers(%{"module_workers" => module_worker_ids} = attrs) do
Map.put(attrs, "module_workers", preload_module_worker([], module_worker_ids))
end
# Is used when an no module_worker attribute is given,
# as put_assoc expects an emtpy list in this casse
defp preload_module_workers(attrs) do
Map.put(attrs, "module_workers", [])
end
defp preload_module_worker(module_workers, [module_worker_id | module_workers_ids]) do
module_workers
|> List.insert_at(0, Repo.get(Teacher, module_worker_id))
|> preload_module_worker(module_workers_ids)
end
defp preload_module_worker(module_workers, []) do
module_workers
end
end
| 30.424242
| 98
| 0.739044
|
93a8f575bc6b81fd6b2ddbfa964f9655a5b4eef9
| 1,501
|
exs
|
Elixir
|
config/config.exs
|
deadtrickster/prometheus-plugs-example
|
aa7ff1ba276d935ed6a8b9aa7a309b5891b08629
|
[
"MIT"
] | 1
|
2016-05-17T09:57:02.000Z
|
2016-05-17T09:57:02.000Z
|
config/config.exs
|
deadtrickster/prometheus-plugs-example
|
aa7ff1ba276d935ed6a8b9aa7a309b5891b08629
|
[
"MIT"
] | 1
|
2016-08-24T06:51:00.000Z
|
2016-08-24T06:51:00.000Z
|
config/config.exs
|
deadtrickster/prometheus-plugs-example
|
aa7ff1ba276d935ed6a8b9aa7a309b5891b08629
|
[
"MIT"
] | 10
|
2016-08-24T00:44:33.000Z
|
2022-02-09T13:17:00.000Z
|
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :prometheus_plug_example, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:prometheus_plug_example, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
config :prometheus, PlugsInstrumenter,
labels: [:status_class, :method, :host, :scheme, {:request_path, MyPlugLables}],
duration_buckets: [10, 100, 1_000, 10_000, 100_000,
300_000, 500_000, 750_000, 1_000_000],
registry: :default
config :prometheus, PlugsExporter,
path: "/metrics",
format: :text,
registry: :default
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 35.738095
| 82
| 0.740173
|
93a90867b9e86d8e2905b3e911d12130fc9e555a
| 2,771
|
ex
|
Elixir
|
lib/slack/sends.ex
|
albert-io/Elixir-Slack
|
830fcbf1b260b8fc014de33ba9e4cdf273c88e98
|
[
"MIT"
] | null | null | null |
lib/slack/sends.ex
|
albert-io/Elixir-Slack
|
830fcbf1b260b8fc014de33ba9e4cdf273c88e98
|
[
"MIT"
] | null | null | null |
lib/slack/sends.ex
|
albert-io/Elixir-Slack
|
830fcbf1b260b8fc014de33ba9e4cdf273c88e98
|
[
"MIT"
] | null | null | null |
defmodule Slack.Sends do
@moduledoc "Utility functions for sending slack messages"
alias Slack.Lookups
@doc """
Sends `text` to `channel` for the given `slack` connection. `channel` can be
a string in the format of `"#CHANNEL_NAME"`, `"@USER_NAME"`, or any ID that
Slack understands.
"""
def send_message(text, channel = "#" <> channel_name, slack) do
channel_id = Lookups.lookup_channel_id(channel, slack)
if channel_id do
send_message(text, channel_id, slack)
else
raise ArgumentError, "channel ##{channel_name} not found"
end
end
def send_message(text, user_id = "U" <> _user_id, slack) do
user_name = Slack.Lookups.lookup_user_name(user_id, slack)
send_message(text, user_name, slack)
end
def send_message(text, user = "@" <> _user_name, slack) do
direct_message_id = Lookups.lookup_direct_message_id(user, slack)
if direct_message_id do
send_message(text, direct_message_id, slack)
else
open_im_channel(
slack.token,
Lookups.lookup_user_id(user, slack),
fn id -> send_message(text, id, slack) end,
fn reason -> reason end
)
end
end
def send_message(text, channel, slack) do
%{
type: "message",
text: text,
channel: channel
}
|> Poison.encode!()
|> send_raw(slack)
end
@doc """
Notifies Slack that the current user is typing in `channel`.
"""
def indicate_typing(channel, slack) do
%{
type: "typing",
channel: channel
}
|> Poison.encode!()
|> send_raw(slack)
end
@doc """
Notifies slack that the current `slack` user is typing in `channel`.
"""
def send_ping(data \\ %{}, slack) do
%{
type: "ping"
}
|> Map.merge(Map.new(data))
|> Poison.encode!()
|> send_raw(slack)
end
@doc """
Subscribe to presence notifications for the user IDs in `ids`.
"""
def subscribe_presence(ids \\ [], slack) do
%{
type: "presence_sub",
ids: ids
}
|> Poison.encode!()
|> send_raw(slack)
end
@doc """
Sends raw JSON to a given socket.
"""
def send_raw(json, %{process: pid, client: client}) do
client.cast(pid, {:text, json})
end
defp open_im_channel(token, user_id, on_success, on_error) do
url = Application.get_env(:slack, :url, "https://slack.com")
im_open = HTTPoison.post(
url <> "/api/im.open",
{:form, [token: token, user: user_id]}
)
case im_open do
{:ok, response} ->
case Poison.Parser.parse!(response.body, keys: :atoms) do
%{ok: true, channel: %{id: id}} -> on_success.(id)
e = %{error: error_message} -> on_error.(e)
end
{:error, reason} -> on_error.(reason)
end
end
end
| 25.897196
| 79
| 0.611693
|
93a91d427acfbdb7621ab13b3eda9eb1aa06ce3c
| 575
|
ex
|
Elixir
|
lib/ex_twilio/resources/task_router/workspace_statistic.ex
|
paulanthonywilson/ex_twilio
|
4f58cb13ae8e4ba61237369bc29669724f9491ff
|
[
"MIT"
] | 1
|
2017-03-23T08:03:58.000Z
|
2017-03-23T08:03:58.000Z
|
lib/ex_twilio/resources/task_router/workspace_statistic.ex
|
paulanthonywilson/ex_twilio
|
4f58cb13ae8e4ba61237369bc29669724f9491ff
|
[
"MIT"
] | 1
|
2019-09-02T15:15:39.000Z
|
2019-09-03T04:28:09.000Z
|
lib/ex_twilio/resources/task_router/workspace_statistic.ex
|
paulanthonywilson/ex_twilio
|
4f58cb13ae8e4ba61237369bc29669724f9491ff
|
[
"MIT"
] | 2
|
2022-03-08T22:05:17.000Z
|
2022-03-09T05:29:46.000Z
|
defmodule ExTwilio.TaskRouter.WorkspaceStatistic do
@moduledoc """
Provides real time and historical statistics for Workspaces.
- [Twilio docs](https://www.twilio.com/docs/api/taskrouter/workspace-statistics)
"""
defstruct realtime: nil,
cumulative: nil,
account_sid: nil,
workspace_sid: nil,
workflow_sid: nil
use ExTwilio.Resource, import: [:stream, :all]
def parents, do: [%ExTwilio.Parent{module: ExTwilio.TaskRouter.Workspace, key: :workspace}]
def children, do: [:minutes, :start_date, :end_date]
end
| 30.263158
| 93
| 0.686957
|
93a92e00b751260c5c5605b37fa7f62bb62b538a
| 13,800
|
ex
|
Elixir
|
lib/qh.ex
|
fidr/qh
|
14d392c5612889c7ed9e88cf558e677ac06b39f4
|
[
"MIT"
] | 5
|
2022-01-10T10:57:44.000Z
|
2022-01-22T18:15:05.000Z
|
lib/qh.ex
|
fidr/qh
|
14d392c5612889c7ed9e88cf558e677ac06b39f4
|
[
"MIT"
] | null | null | null |
lib/qh.ex
|
fidr/qh
|
14d392c5612889c7ed9e88cf558e677ac06b39f4
|
[
"MIT"
] | null | null | null |
defmodule Qh do
@moduledoc """
Query helper for iex
`.iex.exs`:
```
use Qh
Qh.configure(app: :my_app)
```
## Example:
iex>q User.where(age > 20 and age < 50).order(name).first
%MyApp.User%{id: 123, age: 21, name: "Anna"}
"""
defmacro __using__(_) do
quote do
require Qh
import Qh, only: [q: 1, q: 2]
end
end
defmacro q(query, opts \\ []) do
Qh.query(query, opts, __CALLER__)
end
def configure(opts) do
Enum.each(opts, fn {k, v} ->
Application.put_env(:qh, k, v)
end)
end
@doc """
Run a query
Examples:
# First/last
q User.first
q User.first(10)
q User.last
q User.last(1)
# Custom order
q User.order(name).last(3)
q User.order(name: :asc, age: :desc).last
q User.order("lower(?)", name).last
# Conditions
q User.where(age > 20 and age <= 30).count
q User.where(age > 20 and age <= 30).limit(10).all
q User.where(age > 20 or name == "Bob").all
q User.where(age > 20 and (name == "Bob" or name == "Anna")).all
q User.where(age: 20, name: "Bob").count
q User.where("nicknames && ?", ["Bobby", "Bobi"]).count
q User.where("? = ANY(?)", age, [20, 30, 40]).count
# Opional binding
q User.where([u], u.age > 20 and u.age <= 30).count
# Find
q User.get!(21)
# or
q User.find(21)
# Alias for where(...).first
q User.find_by(name: "Bob Foo")
q User.find_by(name == "Bob" or name == "Anna")
# Aggregations
q User.group_by("length(name)").count
q User.group_by(name).avg(age)
# Select stats
q User.select(count(), avg(age), min(age), max(age)).all
# Aggregate stats grouped by column
q User.group_by(name).aggr(%{count: count(), avg: avg(age), min: min(age), max: max(age)})
# Count number of messages per user
q User.left_join(:messages).group_by(id).count([u, m], m.id)
# Grab only users that have messages
q User.distinct(id).join(:messages).all
# Custom join logic
q User.join([u], u in MyApp.Messages, on: u.id == m.sent_by_id, as: :m)
"""
def query(q, opts \\ [], caller \\ __ENV__) do
[schema | rest] = unwrap_nested(q)
code =
if is_atom(schema) && !first_uppercase?(schema) do
quote do
require Ecto.Query
query = unquote({schema, [if_undefined: :apply], nil})
end
else
quote do
require Ecto.Query
query = Qh.lookup_schema(unquote(schema), unquote(opts))
end
end
# aliases
rest =
Enum.flat_map(rest, fn
{:order, _, params} ->
[{:order_by, [], params}]
{:find, _, params} ->
[{:get, [], params}]
{:find_by, _, params} ->
[{:where, [], params}, {:first, [], []}]
{fun, _, params} when fun in [:count, :sum, :avg, :min, :max] ->
if first_param_binding?(params) do
[binding | params] = params
[{:aggr, [], [binding, {fun, [], params}]}]
else
[{:aggr, [], [{fun, [], params}]}]
end
other ->
[other]
end)
code =
[code] ++
Enum.map(rest, fn
# Ecto.Query functions /3 (with binding)
{fun, _, params}
when fun in [
:distinct,
:where,
:select,
:select_merge,
:group_by,
:having,
:lock,
:or_having,
:or_where,
:order_by,
:preload,
:windows,
:limit
] ->
transform_with_binding(fun, params)
# Ecto.Query functions /2
{fun, _, params}
when fun in [
:except,
:except_all,
:exclude,
:intersect,
:intersect_all,
:union,
:union_all
] ->
quote do
query = Ecto.Query.unquote(fun)(query, unquote_splicing(params))
end
# Ecto.Query functions /1
{fun, _, []}
when fun in [
:reverse_order
] ->
quote do
query = Ecto.Query.unquote(fun)(query)
end
# Repo functions /1
{fun, _, []} when fun in [:all, :one, :stream, :exists?] ->
quote do
Qh.repo(unquote(opts)).unquote(fun)(query)
end
# Quick or custom join
{join, _, params}
when join in [
:join,
:inner_join,
:left_join,
:right_join,
:cross_join,
:full_join,
:inner_lateral_join,
:left_lateral_join
] ->
transform_join(join, params)
# Aggregrate respecting group_bys
{:aggr, _, params} ->
transform_aggr(params, caller, opts)
# Return a queryable
{:query, _, []} ->
quote do
query = Ecto.Queryable.to_query(query)
end
# First/last
{:first, _, []} ->
quote do
Ecto.Query.limit(query, 1)
|> Qh.default_primary_order()
|> Qh.repo(unquote(opts)).one()
end
{:first, _, [n]} ->
quote do
Ecto.Query.limit(query, unquote(n))
|> Qh.default_primary_order()
|> Qh.repo(unquote(opts)).all()
end
{:last, _, []} ->
quote do
Ecto.Query.reverse_order(query)
|> Ecto.Query.limit(1)
|> Qh.default_primary_order()
|> Qh.repo(unquote(opts)).one()
end
{:last, _, [n]} ->
quote do
Ecto.Query.reverse_order(query)
|> Ecto.Query.limit(unquote(n))
|> Qh.default_primary_order()
|> Qh.repo(unquote(opts)).all()
|> Enum.reverse()
end
{:new, _, []} ->
quote do
schema = Qh.get_schema(query)
struct(schema)
end
{:new, _, [params]} ->
quote do
schema = Qh.get_schema(query)
struct(schema, unquote(params))
end
end)
code =
quote do
(unquote_splicing(code))
end
#IO.puts(Macro.to_string(code))
code
end
# Transform
def transform_join(fun, params) do
type =
case String.split(to_string(fun), "_", parts: 2) do
["join"] -> :inner
[type, "join"] -> String.to_atom(type)
end
case params do
[target] when is_atom(target) ->
quote do
query = Ecto.Query.join(query, unquote(type), [t], assoc(t, unquote(target)))
end
[target, as] when is_atom(target) and is_atom(as) ->
quote do
query =
Ecto.Query.join(query, unquote(type), [t], assoc(t, unquote(target)),
as: unquote(as)
)
end
[target, {as, _, nil}] when is_atom(target) and is_atom(as) ->
quote do
query =
Ecto.Query.join(query, unquote(type), [t], assoc(t, unquote(target)),
as: unquote(as)
)
end
params ->
{binding_provided, binding, params} = Qh.split_optional_binding(params)
params = Qh.Expr.maybe_deep_prefix_binding(binding_provided, params)
quote do
query =
Ecto.Query.join(
query,
unquote(type),
unquote(binding),
unquote_splicing(params)
)
end
end
end
def transform_aggr(original_params, caller, opts) do
{binding_provided, binding, params} = Qh.split_optional_binding(original_params)
{_, binding} =
Ecto.Query.Builder.escape_binding(quote(do: %Ecto.Query{}), binding, caller)
prefixed_params = unwrap_single(params)
prefixed_params = Qh.Expr.maybe_deep_prefix_binding(binding_provided, prefixed_params)
{prefixed_params, _take} =
Ecto.Query.Builder.Select.escape(prefixed_params, binding, caller)
call_select = transform_with_binding(:select, original_params)
quote do
query =
if Qh.has_group_by?(query) do
query
|> Qh.group_by_and_aggregate(unquote(prefixed_params))
|> Qh.repo(unquote(opts)).all()
else
unquote(call_select)
|> Qh.repo(unquote(opts)).one()
end
end
end
def group_by_and_aggregate(query, target) do
{first_group_by, joined_expr} =
case query.group_bys do
[group_by] ->
{group_by, unwrap_single(group_by.expr)}
[first | _] = list ->
{first, Enum.map(list, fn group_by -> unwrap_single(group_by.expr) end)}
end
target = expr_to_funcs(target)
expr = {:{}, [], [joined_expr, target]}
select = %Ecto.Query.SelectExpr{
expr: expr,
file: first_group_by.file,
line: first_group_by.line
}
Map.put(query, :select, select)
end
def transform_with_binding(fun, params) do
{binding_provided, binding, params} = Qh.split_optional_binding(params)
params = replace_fragments(params)
params = unwrap_single(params)
params = maybe_replace_order(fun, params)
new_params = Qh.Expr.maybe_deep_prefix_binding(binding_provided, params)
if !binding_provided and params == new_params do
quote do
query = Ecto.Query.unquote(fun)(query, unquote(new_params))
end
else
quote do
query = Ecto.Query.unquote(fun)(query, unquote(binding), unquote(new_params))
end
end
end
defp maybe_replace_order(:order_by, order) do
Enum.map(List.wrap(order), fn
{key, dir}
when dir in [
:asc,
:asc_nulls_last,
:asc_nulls_first,
:desc,
:desc_nulls_last,
:desc_nulls_first
] ->
{dir, key}
other ->
other
end)
end
defp maybe_replace_order(_fun, params) do
params
end
defp replace_fragments(list) do
case list do
[q | _] when is_binary(q) ->
quote do: fragment(unquote_splicing(list))
list ->
list
end
end
defp expr_to_funcs(expr) do
case expr do
list when is_list(list) -> Enum.map(list, fn sub_expr -> expr_to_funcs(sub_expr) end)
{fun, arg} -> {fun, [], [{{:., [], [{:&, [], [0]}, arg]}, [], []}]}
fun when is_atom(fun) -> {fun, [], []}
expr -> expr
end
end
#
def has_group_by?(%{group_bys: list}) when length(list) > 0, do: true
def has_group_by?(_query), do: false
def default_primary_order(schema) when is_atom(schema) do
require Ecto.Query
primary_key = schema.__schema__(:primary_key)
Ecto.Query.order_by(schema, ^primary_key)
end
def default_primary_order(%{from: %{source: {_, schema}}, order_bys: []} = query) do
require Ecto.Query
primary_key = schema.__schema__(:primary_key)
Ecto.Query.order_by(query, ^primary_key)
end
def default_primary_order(unknown), do: unknown
def get_schema(schema) when is_atom(schema) do
schema
end
def get_schema(%{from: %{source: {_, schema}}}) do
schema
end
def split_optional_binding(params) do
if first_param_binding?(params) do
[binding | params] = params
{true, binding, params}
else
binding = quote do: [t]
{false, binding, params}
end
end
defp first_param_binding?([maybe_binding | _]), do: is_binding?(maybe_binding)
defp first_param_binding?(_), do: false
defp is_binding?(list) do
is_list(list) &&
Enum.all?(list, fn
{key, _, nil} when is_atom(key) -> true
{alias, {key, _, nil}} when is_atom(alias) and is_atom(key) -> true
_other -> false
end)
end
def repo(opts \\ []) do
repo_mod(opts)
end
def repo_mod(opts) do
opts[:repo] || Application.get_env(:qh, :repo) || Module.concat(app_mod(opts), Repo)
end
def app_mod(opts) do
opts[:app_mod] || maybe_camelize(opts[:app]) || Application.get_env(:qh, :app_mod) ||
maybe_camelize(Application.get_env(:qh, :app))
end
def lookup_schema(schema, opts \\ []) do
app_mod = app_mod(opts)
cond do
is_atom(schema) and first_uppercase?(schema) and ensure_compiled?(schema) ->
schema
first_uppercase?(schema) ->
module = Module.concat(app_mod, schema)
module_or_raise!(module, schema)
true ->
schema
end
end
defp module_or_raise!(module, schema) do
if ensure_compiled?(module) do
module
else
raise "unable to find schema for #{inspect(schema)}, #{inspect(module)} does not exist"
end
end
defp ensure_compiled?(module) do
case Code.ensure_compiled(module) do
{:module, _} ->
true
{:error, _} ->
false
end
end
defp first_uppercase?(val) do
String.at(to_string(val), 0) == String.capitalize(String.at(to_string(val), 0))
end
defp maybe_camelize(nil), do: nil
defp maybe_camelize(val), do: Macro.camelize(to_string(val))
def unwrap_single([item]), do: item
def unwrap_single(other), do: other
defp unwrap_nested({{:., _, [left, right]}, opts, children}) do
parens = if opts[:no_parens], do: false, else: true
unwrap_nested(left) ++ [{right, [parens: parens], children}]
end
defp unwrap_nested({k, _, nil}), do: [k]
defp unwrap_nested(v), do: [v]
end
| 25.508318
| 96
| 0.537681
|
93a9460b166f396658fec1ef607a6363c3a289b9
| 1,021
|
ex
|
Elixir
|
test/support/generate_language_tag.ex
|
KineticCafe/cldr
|
7b84cd85564bca4a2c4e01c02ee0aa284bf07367
|
[
"Apache-2.0"
] | 179
|
2019-06-16T09:16:00.000Z
|
2022-03-30T04:04:55.000Z
|
test/support/generate_language_tag.ex
|
KineticCafe/cldr
|
7b84cd85564bca4a2c4e01c02ee0aa284bf07367
|
[
"Apache-2.0"
] | 46
|
2019-06-09T02:35:58.000Z
|
2022-03-08T10:39:08.000Z
|
test/support/generate_language_tag.ex
|
KineticCafe/cldr
|
7b84cd85564bca4a2c4e01c02ee0aa284bf07367
|
[
"Apache-2.0"
] | 14
|
2020-03-03T16:35:50.000Z
|
2022-02-27T14:01:40.000Z
|
defmodule GenerateLanguageTag do
require ExUnitProperties
@known_territories Cldr.Validity.all_valid(:territories)
@known_scripts Cldr.Validity.all_valid(:scripts)
@known_languages Cldr.Validity.all_valid(:languages)
def valid_language_tag do
ExUnitProperties.gen all(
language <-
StreamData.member_of(@known_languages),
script <-
StreamData.one_of([
StreamData.member_of(@known_scripts),
StreamData.constant(nil)
]),
region <-
StreamData.one_of([
StreamData.member_of(@known_territories),
StreamData.constant(nil)
])
) do
[language, script, region]
|> Enum.reject(&is_nil/1)
|> Enum.join("-")
end
end
end
| 35.206897
| 72
| 0.475024
|
93a9610abe9f2b64d38dedca563b5ba1164f8832
| 3,972
|
exs
|
Elixir
|
test/epicenter/extra/map_test.exs
|
geometricservices/epi-viewpoin
|
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
|
[
"Apache-2.0"
] | 5
|
2021-02-25T18:43:09.000Z
|
2021-02-27T06:00:35.000Z
|
test/epicenter/extra/map_test.exs
|
geometricservices/epi-viewpoint
|
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
|
[
"Apache-2.0"
] | 3
|
2021-12-13T17:52:47.000Z
|
2021-12-17T01:35:31.000Z
|
test/epicenter/extra/map_test.exs
|
geometricservices/epi-viewpoint
|
ecb5316ea0f3f7299d5ff63e2de588539005ac1c
|
[
"Apache-2.0"
] | 1
|
2022-01-27T23:26:38.000Z
|
2022-01-27T23:26:38.000Z
|
defmodule Epicenter.Extra.MapTest do
use Epicenter.SimpleCase, async: false
alias Epicenter.Extra
describe "delete_in" do
test "removes the value at the keypath" do
%{a: %{b: %{c: 1, d: 2}, e: 3}} |> Extra.Map.delete_in([:a, :b, :c]) |> assert_eq(%{a: %{b: %{d: 2}, e: 3}})
end
test "does nothing if there is nothing at the keypath" do
%{a: %{b: 1}} |> Extra.Map.delete_in([:a, :b, :c]) |> assert_eq(%{a: %{b: 1}})
end
end
describe "get_in" do
test "gets the value at the keypath" do
%{a: %{b: [1, 2]}} |> Extra.Map.get_in([:a, :b]) |> assert_eq([1, 2])
%{"a" => %{"b" => [1, 2]}} |> Extra.Map.get_in(["a", "b"]) |> assert_eq([1, 2])
end
test "returns nil if there is nothing at the keypath" do
%{a: %{b: [1, 2]}} |> Extra.Map.get_in([:a, :c]) |> assert_eq(nil)
%{a: %{b: 1}} |> Extra.Map.get_in([:a, :b, :c]) |> assert_eq(nil)
end
end
describe "put_in" do
test "with :replace, if the new value is already in the map, does nothing" do
%{a: %{b: 1}} |> Extra.Map.put_in([:a, :b], 1, on_conflict: :replace) |> assert_eq(%{a: %{b: 1}})
end
test "with :replace, if the keypath doesn't exist, the new value is added at the keypath" do
%{} |> Extra.Map.put_in([:x, :y], 10, on_conflict: :replace) |> assert_eq(%{x: %{y: 10}})
%{a: %{b: 1}} |> Extra.Map.put_in([:x, :y], 10, on_conflict: :replace) |> assert_eq(%{a: %{b: 1}, x: %{y: 10}})
end
test "with :replace, if a value exists at the keypath, it is replaced" do
%{a: %{b: 1}} |> Extra.Map.put_in([:a, :b], 10, on_conflict: :replace) |> assert_eq(%{a: %{b: 10}})
%{a: %{b: [1, 2]}} |> Extra.Map.put_in([:a, :b], 10, on_conflict: :replace) |> assert_eq(%{a: %{b: 10}})
end
test "with :list_append, if the existing value contains the new value, nothing is changed" do
%{a: %{b: [1, 2]}} |> Extra.Map.put_in([:a, :b], 1, on_conflict: :list_append) |> assert_eq(%{a: %{b: [1, 2]}})
end
test "with :list_append, if the keypath exists, its value is replaced with a list containing the old value and the new value" do
%{a: %{b: 1}} |> Extra.Map.put_in([:a, :b], 10, on_conflict: :list_append) |> assert_eq(%{a: %{b: [1, 10]}})
end
test "with :list_append, if the keypath exists and its value is a list, the new value is appended" do
%{a: %{b: [1, 2]}} |> Extra.Map.put_in([:a, :b], 10, on_conflict: :list_append) |> assert_eq(%{a: %{b: [1, 2, 10]}})
end
end
describe "has_key? with :coerce_key_to_existing_atom" do
test "looks for the key when the map has a key of type atom, and the parameter is an atom" do
map = %{key: "value"}
assert Extra.Map.has_key?(map, :key, :coerce_key_to_existing_atom)
refute Extra.Map.has_key?(map, :not_key, :coerce_key_to_existing_atom)
end
test "coerces to atom and looks for the key when the map has a key of type atom, and the parameter is a string" do
map = %{key: "value"}
assert Extra.Map.has_key?(map, "key", :coerce_key_to_existing_atom)
refute Extra.Map.has_key?(map, "not_key", :coerce_key_to_existing_atom)
end
test "returns false when the map has key of type string, no matter the parameter type" do
map = %{"key" => "value"}
refute Extra.Map.has_key?(map, :key, :coerce_key_to_existing_atom)
refute Extra.Map.has_key?(map, "key", :coerce_key_to_existing_atom)
end
end
describe "to_list :depth_first" do
test "converts a map of 'key -> value' or 'key -> values' into a list by alphabetizing keys and traversing depth-first" do
%{"z" => "z1", "a" => "a1"} |> Extra.Map.to_list(:depth_first) |> assert_eq(["a", "a1", "z", "z1"])
%{"z" => ["z1", "z2"], "a" => "a1"} |> Extra.Map.to_list(:depth_first) |> assert_eq(["a", "a1", "z", "z1", "z2"])
%{"z" => ["z1", "z2"], "a" => ["a1", "a2"]} |> Extra.Map.to_list(:depth_first) |> assert_eq(["a", "a1", "a2", "z", "z1", "z2"])
end
end
end
| 47.285714
| 133
| 0.586103
|
93a96b909d09918c2c62f78276f58c6dc3c68f83
| 515
|
ex
|
Elixir
|
lib/prm/entities/msp.ex
|
EDENLABLLC/prm.api
|
86743f26874f47ce3d48010ccf5d2cd596a3474b
|
[
"Apache-2.0"
] | 1
|
2017-07-27T16:03:28.000Z
|
2017-07-27T16:03:28.000Z
|
lib/prm/entities/msp.ex
|
EDENLABLLC/prm.api
|
86743f26874f47ce3d48010ccf5d2cd596a3474b
|
[
"Apache-2.0"
] | null | null | null |
lib/prm/entities/msp.ex
|
EDENLABLLC/prm.api
|
86743f26874f47ce3d48010ccf5d2cd596a3474b
|
[
"Apache-2.0"
] | null | null | null |
defmodule PRM.Entities.MSP do
@moduledoc false
use Ecto.Schema
import Ecto.Changeset, warn: false
@primary_key {:id, :binary_id, autogenerate: true}
schema "medical_service_providers" do
field :accreditation, :map
field :licenses, {:array, :map}
belongs_to :legal_entity, PRM.Entities.LegalEntity, type: Ecto.UUID
timestamps()
end
def changeset(%PRM.Entities.MSP{} = doc, attrs) do
fields = ~W(
accreditation
licenses
)
cast(doc, attrs, fields)
end
end
| 19.807692
| 71
| 0.679612
|
93a9911d5e9f79c38266f22f18e2b65050fe5e0c
| 2,156
|
ex
|
Elixir
|
test/support/fixtures.ex
|
exterm/scripture
|
eec53d2626f8484c03ad0545feffc73ec276fcab
|
[
"MIT"
] | null | null | null |
test/support/fixtures.ex
|
exterm/scripture
|
eec53d2626f8484c03ad0545feffc73ec276fcab
|
[
"MIT"
] | 30
|
2016-08-21T18:33:11.000Z
|
2020-04-12T23:16:18.000Z
|
test/support/fixtures.ex
|
exterm/scripture
|
eec53d2626f8484c03ad0545feffc73ec276fcab
|
[
"MIT"
] | null | null | null |
# for more functionality, read http://blog.danielberkompas.com/elixir/2015/07/16/fixtures-for-ecto.html
defmodule Scripture.Fixtures do
alias Scripture.Repo
alias Scripture.{User, Article, Comment}
def build_fixture(module) do
build_fixture(module, %{})
end
def build_fixture(module, key) when is_atom(key) do
build_fixture(module, key, %{})
end
def build_fixture(module, params) do
build_fixture(module, module, params)
end
def build_fixture(module, fixture_name, params) do
changeset = fixture_changeset(module, Map.merge(fixture_defaults(fixture_name), params))
Map.merge(module.__struct__, changeset.changes)
end
def persist_fixture(module) do
persist_fixture(module, %{})
end
def persist_fixture(module, key) when is_atom(key) do
persist_fixture(module, key, %{})
end
def persist_fixture(module, params) do
persist_fixture(module, module, params)
end
def persist_fixture(module, fixture_name, params) do
changeset = fixture_changeset(module, Map.merge(fixture_defaults(fixture_name), params))
Repo.insert!(changeset)
end
def fixture_defaults(User) do
basic_defaults = %{first_name: "Bernd",
last_name: "Berndes",
email: "bernd@example.com",
role: "reader",
group: "acquaintances"}
Map.merge(basic_defaults, User.new_login_token)
end
def fixture_defaults(:admin) do
basic_defaults = %{first_name: "Philip",
last_name: "Müller",
email: "philip@example.com",
role: "admin",
group: "close family"}
Map.merge(basic_defaults, User.new_login_token)
end
def fixture_defaults(Article) do
%{title: "Die 33 besten Artikel-Headlines",
content: "Buzzfeed hat angerufen.",
published: true}
end
def fixture_defaults(Comment) do
%{message: "Best article evar",
user_id: 1,
article_id: 1}
end
# private
defp fixture_changeset(module, params) do
case module do
User -> User.admin_changeset(module.__struct__, params)
_ -> module.changeset(module.__struct__, params)
end
end
end
| 30.366197
| 103
| 0.680891
|
93a99c9aec44263092c7ae5b18f0edb19069f176
| 477
|
ex
|
Elixir
|
lib/syn_osc/pan.ex
|
camshaft/syn_osc_ex
|
c7ed257f2ea772f197096d356467e812a0d5e59a
|
[
"MIT"
] | 1
|
2020-12-08T01:44:03.000Z
|
2020-12-08T01:44:03.000Z
|
lib/syn_osc/pan.ex
|
camshaft/syn_osc_ex
|
c7ed257f2ea772f197096d356467e812a0d5e59a
|
[
"MIT"
] | null | null | null |
lib/syn_osc/pan.ex
|
camshaft/syn_osc_ex
|
c7ed257f2ea772f197096d356467e812a0d5e59a
|
[
"MIT"
] | null | null | null |
defmodule SynOSC.Pan do
defstruct id: nil,
relative: false,
x: nil,
y: nil,
z: nil
end
defimpl OSC.Encoder, for: SynOSC.Pan do
use SynOSC
def encode(message, options) do
message
|> call("PAN")
|> set_arguments(format_arguments(message))
|> OSC.Encoder.encode(options)
end
defp format_arguments(%{relative: relative} = message) do
[relative | format_pan(message)]
end
def flag(_), do: []
end
| 19.08
| 59
| 0.60587
|
93a9a4b44fb1cfea2ade490029e29f9dae51048d
| 779
|
ex
|
Elixir
|
apps/engine/lib/engine/repo/monitor/child.ex
|
omgnetwork/omg-childchain-v2
|
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
|
[
"Apache-2.0"
] | 4
|
2020-11-30T17:38:57.000Z
|
2021-01-23T21:29:41.000Z
|
apps/engine/lib/engine/repo/monitor/child.ex
|
omgnetwork/omg-childchain-v2
|
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
|
[
"Apache-2.0"
] | 24
|
2020-11-30T17:32:48.000Z
|
2021-02-22T06:25:22.000Z
|
apps/engine/lib/engine/repo/monitor/child.ex
|
omgnetwork/omg-childchain-v2
|
31cc9cf9e42718fc3b9bd6668f24a627cac80b4f
|
[
"Apache-2.0"
] | null | null | null |
defmodule Engine.Repo.Monitor.Child do
@moduledoc """
This implements the restart logic of the Monitor
"""
require Logger
@type t :: %__MODULE__{pid: pid(), spec: Supervisor.child_spec()}
defstruct pid: nil, spec: nil
@spec start(t() | Supervisor.child_spec()) :: t()
def start(child) when is_struct(child) do
case Process.alive?(child.pid) do
true ->
child
false ->
%{id: _name, start: {child_module, function, args}} = child.spec
{:ok, pid} = apply(child_module, function, args)
%__MODULE__{pid: pid, spec: child.spec}
end
end
def start(%{id: _name, start: {child_module, function, args}} = spec) do
{:ok, pid} = apply(child_module, function, args)
%__MODULE__{pid: pid, spec: spec}
end
end
| 27.821429
| 74
| 0.63543
|
93a9ac9e2d994a59e48332f2f141a6527df6e992
| 3,108
|
ex
|
Elixir
|
lib/distillery/releases/shell.ex
|
arikai/distillery
|
65ddbcc143f2849a6ed5574e8c397a68ca92eb81
|
[
"MIT"
] | 3,097
|
2016-07-18T13:59:00.000Z
|
2022-03-29T00:27:23.000Z
|
lib/distillery/releases/shell.ex
|
arikai/distillery
|
65ddbcc143f2849a6ed5574e8c397a68ca92eb81
|
[
"MIT"
] | 672
|
2016-07-18T18:25:29.000Z
|
2022-02-24T17:39:30.000Z
|
lib/distillery/releases/shell.ex
|
arikai/distillery
|
65ddbcc143f2849a6ed5574e8c397a68ca92eb81
|
[
"MIT"
] | 483
|
2016-07-22T14:08:49.000Z
|
2022-03-21T09:35:23.000Z
|
defmodule Distillery.Releases.Shell do
@moduledoc """
This module provides conveniences for writing output to the shell.
"""
use Distillery.Releases.Shell.Macros
@type verbosity :: :silent | :quiet | :normal | :verbose
# The order of these levels is from least important to most important
# When comparing log levels with `gte`, this ordering is what determines their total ordering
deflevel(:debug, prefix: "==> ", color: :cyan)
deflevel(:info, prefix: "==> ", color: [:bright, :cyan])
deflevel(:notice, color: :yellow)
deflevel(:success, prefix: "==> ", color: [:bright, :green])
deflevel(:warn, prefix: "==> ", color: :yellow, error: :warnings_as_errors)
deflevel(:error, prefix: "==> ", color: :red)
@doc """
Configure the logging verbosity of the release logger.
Valid verbosity settings are:
* `:silent` - no output except errors
* `:quiet` - no output except warnings/errors
* `:normal` - no debug output (default)
* `:verbose` - all output
"""
@spec configure(verbosity) :: :ok
def configure(verbosity) when is_atom(verbosity) do
Application.put_env(:mix, :release_logger_verbosity, verbosity)
end
@default_answer_pattern ~r/^(y(es)?)?$/i
@doc """
Ask the user to confirm an action using the given message.
The confirmation prompt will default to "[Yn]: ", and the
regex for determining whether the action was confirmed will
default to #{inspect(Regex.source(@default_answer_pattern))}.
Use confirm/3 to provide your own prompt and answer regex.
"""
@spec confirm?(String.t()) :: boolean
def confirm?(message) do
confirm?(message, "[Yn]: ", @default_answer_pattern)
end
@doc """
Same as confirm/1, but takes a custom prompt and answer regex pattern.
If the pattern matches the response, the action is considered confirmed.
"""
@spec confirm?(String.t(), String.t(), Regex.t()) :: boolean
def confirm?(message, prompt, answer_pattern) do
IO.puts(IO.ANSI.format([:yellow]))
answer = IO.gets("#{message} #{prompt}") |> String.trim_trailing("\n")
IO.puts(IO.ANSI.format([:reset]))
answer =~ answer_pattern
end
@doc """
Prints an error message, then terminates the VM with a non-zero status code
"""
@spec fail!(iodata) :: no_return
def fail!(message) do
error(message)
System.halt(1)
end
@doc "Write the given iodata directly, bypassing the log level"
def write(message),
do: IO.write(message)
@doc "Write the given iodata, wrapped in the given color, but bypassing the log level"
def writef(message, color),
do: write(colorf(message, color))
@doc "Write a debug level message, but with minimal formatting. Default color is same as debug level"
def debugf(message, color \\ :cyan) do
data = verbosityf(:debug, colorf(message, color))
IO.write(data)
end
## Color helpers
# Formats a message with a given color
# Can use shorthand atoms for colors, or pass the ANSI directly
@doc """
Wraps a message in the given color
"""
def colorf(message, color), do: IO.ANSI.format([color, message, :reset])
end
| 34.153846
| 103
| 0.682432
|
93aa1a51a1f3d0696b8f61fc10a3ae1db7af8db3
| 24,381
|
ex
|
Elixir
|
lib/ex_doc/formatter/html/autolink.ex
|
cryic/ex_doc
|
a331a27f76742d162961afcdd616bab96e446dd0
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
lib/ex_doc/formatter/html/autolink.ex
|
cryic/ex_doc
|
a331a27f76742d162961afcdd616bab96e446dd0
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
lib/ex_doc/formatter/html/autolink.ex
|
cryic/ex_doc
|
a331a27f76742d162961afcdd616bab96e446dd0
|
[
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null |
defmodule ExDoc.Formatter.HTML.Autolink do
@moduledoc false
import ExDoc.Formatter.HTML.Templates, only: [h: 1, enc_h: 1]
@type language :: :elixir | :erlang | :markdown
@type kind :: :function | :module | :mix_task
@type link_type :: :normal | :custom
@backtick_token "<B706848484895T>"
@elixir_docs "https://hexdocs.pm/"
@erlang_docs "http://www.erlang.org/doc/man/"
@basic_types_page "typespecs.html#basic-types"
@basic_types_link_title "Basic types — Typespecs"
@built_in_types_page "typespecs.html#built-in-types"
@built_in_types_link_title "Built-in types — Typespecs"
@basic_types [
any: 0,
none: 0,
atom: 0,
map: 0,
pid: 0,
port: 0,
reference: 0,
struct: 0,
tuple: 0,
integer: 0,
float: 0,
neg_integer: 0,
non_neg_integer: 0,
pos_integer: 0,
list: 1,
nonempty_list: 1,
improper_list: 2,
maybe_improper_list: 2
]
@built_in_types [
term: 0,
arity: 0,
as_boolean: 1,
binary: 0,
bitstring: 0,
boolean: 0,
byte: 0,
char: 0,
charlist: 0,
nonempty_charlist: 0,
fun: 0,
function: 0,
identifier: 0,
iodata: 0,
iolist: 0,
keyword: 0,
keyword: 1,
list: 0,
nonempty_list: 0,
maybe_improper_list: 0,
nonempty_maybe_improper_list: 0,
mfa: 0,
module: 0,
no_return: 0,
node: 0,
number: 0,
struct: 0,
timeout: 0
]
kernel_exports = Kernel.__info__(:functions) ++ Kernel.__info__(:macros)
special_form_exports = Kernel.SpecialForms.__info__(:macros)
@basic_type_strings for {f, a} <- @basic_types, do: "t:#{f}/#{a}"
@built_in_type_strings for {f, a} <- @built_in_types, do: "t:#{f}/#{a}"
@kernel_function_strings for {f, a} <- kernel_exports, do: "#{f}/#{a}"
@special_form_strings for {f, a} <- special_form_exports, do: "#{f}/#{a}"
@doc """
Compiles information used during autolinking.
"""
def compile(modules, extension, config) do
aliases = Enum.map(modules, & &1.module)
modules_refs = Enum.map(aliases, &inspect/1)
types_refs =
for module <- modules,
type <- module.typespecs,
do: "t:" <> module.id <> "." <> type.id
docs_refs =
for module <- modules,
doc <- module.docs,
prefix = doc_prefix(doc),
entry <- [doc.id | doc.defaults],
do: prefix <> module.id <> "." <> entry
lib_dirs = config.deps ++ default_lib_dirs()
%{
aliases: aliases,
docs_refs: docs_refs ++ types_refs,
extension: extension,
lib_dirs: lib_dirs,
modules_refs: modules_refs,
skip_undefined_reference_warnings_on: config.skip_undefined_reference_warnings_on
}
end
@regexes [
{:module, :elixir, :normal},
{:module, :elixir, :custom},
{:function, :elixir, :normal},
{:function, :elixir, :custom},
{:function, :erlang, :normal},
{:function, :erlang, :custom},
{:mix_task, :elixir, :normal}
]
@doc """
Autolinks any documentation in the project.
This is the main API to autolink any project documentation.
"""
def project_doc(nil, _id, _compiled), do: nil
def project_doc(string, id, compiled) when is_binary(string) and is_map(compiled) do
config =
compiled
|> Map.put(:id, id)
|> Map.put_new(:module_id, nil)
|> Map.put_new(:locals, [])
string = preprocess(string)
string =
Enum.reduce(@regexes, string, fn {kind, language, link_type}, acc ->
link(acc, language, kind, link_type, config)
end)
postprocess(string)
end
@doc """
Autolinks all module nodes.
This is the main API to autolink any module nodes.
"""
def all(modules, compiled) do
opts = [timeout: :infinity]
modules
|> Task.async_stream(&(&1 |> all_docs(compiled) |> all_typespecs(compiled)), opts)
|> Enum.map(&elem(&1, 1))
end
defp all_docs(module, compiled) do
funs =
for doc <- module.docs,
prefix = doc_prefix(doc),
entry <- [doc.id | doc.defaults],
do: prefix <> entry
types = Enum.map(module.typespecs, &("t:" <> &1.id))
compiled =
compiled
|> Map.put(:module_id, module.id)
|> Map.put(:locals, funs ++ types)
moduledoc = project_doc(module.doc, id(module, nil), compiled)
docs =
for node <- module.docs do
doc = project_doc(node.doc, id(module, node), compiled)
%{node | doc: doc}
end
typedocs =
for node <- module.typespecs do
doc = project_doc(node.doc, id(module, node), compiled)
%{node | doc: doc}
end
%{module | doc: moduledoc, docs: docs, typespecs: typedocs}
end
defp id(%{id: id}, nil), do: id
defp id(%{id: mod_id}, %ExDoc.FunctionNode{id: id, type: :callback}), do: "c:#{mod_id}.#{id}"
defp id(%{id: mod_id}, %ExDoc.FunctionNode{id: id}), do: "#{mod_id}.#{id}"
defp id(%{id: mod_id}, %ExDoc.TypeNode{id: id}), do: "t:#{mod_id}.#{id}"
defp all_typespecs(module, compiled) do
%{aliases: aliases, lib_dirs: lib_dirs} = compiled
module_name = module.title
locals =
Enum.map(module.typespecs, fn
%ExDoc.TypeNode{name: name, arity: arity} -> {name, arity}
end)
typespecs =
for typespec <- module.typespecs do
%{typespec | spec: typespec(typespec.spec, locals, module_name, aliases, lib_dirs)}
end
docs =
for module_node <- module.docs do
%{
module_node
| specs:
Enum.map(module_node.specs, &typespec(&1, locals, module_name, aliases, lib_dirs))
}
end
%{module | typespecs: typespecs, docs: docs}
end
@doc """
Helper function for autolinking typespecs.
It converts the given `ast` to string while linking
the locals given by `typespecs` as HTML.
"""
def typespec(ast, typespecs, module_name, aliases \\ [], lib_dirs \\ default_lib_dirs()) do
{formatted, placeholders} =
format_and_extract_typespec_placeholders(ast, typespecs, module_name, aliases, lib_dirs)
replace_placeholders(formatted, placeholders)
end
@doc false
def format_and_extract_typespec_placeholders(ast, typespecs, module_name, aliases, lib_dirs) do
ref = make_ref()
elixir_docs = get_elixir_docs(aliases, lib_dirs)
{formatted_ast, placeholders} =
Macro.prewalk(ast, %{}, fn
{:::, _, [{name, meta, args}, right]}, placeholders
when is_atom(name) and is_list(args) ->
{{:::, [], [{{ref, name}, meta, args}, right]}, placeholders}
# Consume this form so that we don't autolink `foo` in `foo :: bar`
{{^ref, name}, _, args}, placeholders when is_atom(name) and is_list(args) ->
{{name, [], args}, placeholders}
{name, _, args} = form, placeholders when is_atom(name) and is_list(args) ->
arity = length(args)
cond do
{name, arity} in @basic_types ->
url = elixir_docs <> @basic_types_page
put_placeholder(form, url, @basic_types_link_title, placeholders)
{name, arity} in @built_in_types ->
url = elixir_docs <> @built_in_types_page
put_placeholder(form, url, @built_in_types_link_title, placeholders)
{name, arity} in typespecs ->
n = enc_h("#{name}")
url = "#t:#{n}/#{arity}"
title = "t:#{module_name}.#{n}/#{arity}"
put_placeholder(form, url, title, placeholders)
true ->
{form, placeholders}
end
{{:., _, [alias, name]}, _, args} = form, placeholders
when is_atom(name) and is_list(args) ->
alias = expand_alias(alias)
if source = get_source(alias, aliases, lib_dirs) do
url = type_remote_url(source, alias, name, args)
title = type_remote_link_title(source, alias, name, args)
put_placeholder(form, url, title, placeholders)
else
{form, placeholders}
end
form, placeholders ->
{form, placeholders}
end)
{format_ast(formatted_ast), placeholders}
end
defp type_remote_url(@erlang_docs = source, module, name, _args) do
module = enc_h("#{module}")
name = enc_h("#{name}")
"#{source}#{module}.html#type-#{name}"
end
defp type_remote_url(source, alias, name, args) do
name = enc_h("#{name}")
"#{source}#{enc_h(inspect(alias))}.html#t:#{name}/#{length(args)}"
end
defp type_remote_link_title(@erlang_docs, module, name, _args) do
"#{module}:#{name}"
end
defp type_remote_link_title(_source, alias, name, args) do
"t:#{inspect(alias)}.#{name}/#{length(args)}"
end
defp typespec_string_to_link(string, url, title) do
{string_to_link, _string_with_parens} = split_string_to_link(string)
~s[<a href="#{url}" title="#{title}">#{h(string_to_link)}</a>]
end
defp put_placeholder(form, url, title, placeholders) do
string = Macro.to_string(form)
link = typespec_string_to_link(string, url, title)
case Enum.find(placeholders, fn {_key, value} -> value == link end) do
{placeholder, _} ->
form = put_elem(form, 0, placeholder)
{form, placeholders}
nil ->
count = map_size(placeholders) + 1
placeholder = placeholder(string, count)
form = put_elem(form, 0, placeholder)
{form, Map.put(placeholders, placeholder, link)}
end
end
defp placeholder(string, count) do
[name | _] = String.split(string, "(", trim: true)
name_size = String.length(name)
int_size = count |> Integer.digits() |> length()
underscores_size = 2
pad = String.duplicate("p", max(name_size - int_size - underscores_size, 1))
:"_#{pad}#{count}_"
end
defp replace_placeholders(string, placeholders) do
Regex.replace(~r"_p+\d+_", string, &Map.fetch!(placeholders, String.to_atom(&1)))
end
defp format_ast(ast) do
ast
|> Macro.to_string()
|> Code.format_string!(line_length: 80)
|> IO.iodata_to_binary()
end
# Helper function for autolinking functions and modules.
#
# It autolinks all links for a certain `language` and of a certain `kind`.
#
# `language` can be: `:elixir`, `:erlang` or `:markdown`.
#
# `kind` is either `:function`, `:module`, or `:mix_task`.
#
# It accepts a list of `options` used in the replacement functions.
# - `:aliases
# - `:docs_refs`
# - `:extension` - Default value is `".html"`
# - `:lib_dirs`
# - `:locals` - A list of local functions
# - `:module_id` - Module of the current doc. Default value is `nil`
# - `:modules_refs` - List of modules available
#
# Internal options:
# - `:preprocess?` - `true` or `false`. Do preprocessing and postprocessing, such as replacing backticks
# with a token
defp link(string, language, kind, link_type, options) when is_map(options) do
regex = re_kind_language_link_type(kind, language, link_type)
replace_fun = replace_fun(kind, language, link_type, options)
Regex.replace(regex, string, replace_fun)
end
defp preprocess(string) do
regex = ~r{
\[([^\]]*?`[^\]]*?)\]
\(([^\)]*?)\)
}x
Regex.replace(regex, string, fn _all, text, link ->
new_text = String.replace(text, :binary.compile_pattern("`"), @backtick_token)
"[#{new_text}](#{link})"
end)
end
defp postprocess(string) do
String.replace(string, :binary.compile_pattern(@backtick_token), "`")
end
# The heart of the autolinking logic
defp replace_fun(kind, :erlang, link_type, options) do
lib_dirs = options[:lib_dirs] || default_lib_dirs(:erlang)
module_id = options[:module_id] || nil
fn all, text, match ->
pmfa = {_prefix, module, function, arity} = split_match(kind, match)
text = default_text(":", link_type, pmfa, text)
title = default_title({":", module, function, arity}, module_id)
if doc = module_docs(:erlang, module, lib_dirs) do
case kind do
:module ->
"[#{text}](#{doc}#{module}.html '#{title}')"
:function ->
"[#{text}](#{doc}#{module}.html##{function}-#{arity} '#{title}')"
end
else
all
end
end
end
defp replace_fun(:module, :elixir, link_type, options) do
extension = options[:extension] || ".html"
lib_dirs = options[:lib_dirs] || default_lib_dirs(:elixir)
module_id = options[:module_id] || nil
modules_refs = options[:modules_refs] || []
fn all, text, match ->
pmfa = split_match(:module, match)
text = default_text("", link_type, pmfa, text)
cond do
match == module_id ->
"[#{text}](#content '#{match} module')"
match in modules_refs ->
"[#{text}](#{match}#{extension} '#{match} module')"
doc = module_docs(:elixir, match, lib_dirs) ->
"[#{text}](#{doc}#{match}.html '#{match} module')"
true ->
all
end
end
end
defp replace_fun(:function, :elixir, link_type, options) do
aliases = options[:aliases] || []
docs_refs = options[:docs_refs] || []
modules_refs = options[:modules_refs] || []
extension = options[:extension] || ".html"
lib_dirs = options[:lib_dirs] || default_lib_dirs(:elixir)
locals = options[:locals] || []
elixir_docs = get_elixir_docs(aliases, lib_dirs)
id = options[:id]
module_id = options[:module_id]
skip_warnings_on = options[:skip_undefined_reference_warnings_on] || []
fn all, text, match ->
pmfa = {prefix, module, function, arity} = split_match(:function, match)
text = default_text("", link_type, pmfa, text)
title = default_title(pmfa, module_id)
cond do
match in locals ->
"[#{text}](##{prefix}#{enc_h(function)}/#{arity} '#{title}')"
match in docs_refs ->
"[#{text}](#{module}#{extension}##{prefix}#{enc_h(function)}/#{arity} '#{title}')"
match in @basic_type_strings ->
"[#{text}](#{elixir_docs}#{@basic_types_page} '#{@basic_types_link_title}')"
match in @built_in_type_strings ->
"[#{text}](#{elixir_docs}#{@built_in_types_page} '#{@built_in_types_link_title}')"
match in @kernel_function_strings ->
"[#{text}](#{elixir_docs}Kernel#{extension}##{prefix}#{enc_h(function)}/#{arity}" <>
" 'Kernel.#{function}/#{arity}')"
match in @special_form_strings ->
"[#{text}](#{elixir_docs}Kernel.SpecialForms" <>
"#{extension}##{prefix}#{enc_h(function)}/#{arity}" <>
" 'Kernel.SpecialForms.#{function}/#{arity}')"
module in modules_refs ->
if module_id not in skip_warnings_on and id not in skip_warnings_on do
IO.warn(
"documentation references #{match} but it doesn't exist " <>
"or it's listed as @doc false (parsing #{id} docs)",
[]
)
end
all
doc = module_docs(:elixir, module, lib_dirs) ->
"[#{text}](#{doc}#{module}.html##{prefix}#{enc_h(function)}/#{arity} '#{title}')"
true ->
all
end
end
end
defp replace_fun(:mix_task, :elixir, :normal, options) do
extension = options[:extension] || ".html"
lib_dirs = options[:lib_dirs] || default_lib_dirs(:elixir)
module_id = options[:module_id] || nil
modules_refs = options[:modules_refs] || []
fn all, text, "mix " <> task_name ->
match = task_module(task_name)
cond do
match == module_id ->
"[#{text}](#content '#{match}')"
match in modules_refs ->
"[#{text}](#{match}#{extension} '#{match}')"
doc = module_docs(:elixir, match, lib_dirs) ->
"[#{text}](#{doc}#{match}.html '#{match}')"
true ->
all
end
end
end
defp task_module("help " <> task_name) do
task_module(task_name)
end
defp task_module(task_name) do
task_module =
task_name
|> String.split(".")
|> Enum.map(&Macro.camelize/1)
|> Enum.join(".")
"Mix.Tasks." <> task_module
end
## Helpers
defp default_text(module_prefix, link_type, pmfa, link_text)
defp default_text(_, :custom, _, link_text),
do: link_text
defp default_text(_, _, {_, "", fun, arity}, _link_text),
do: "`#{fun}/#{arity}`"
defp default_text(module_prefix, _, {_, module, "", ""}, _link_text),
do: "`#{module_prefix}#{module}`"
defp default_text(module_prefix, _, {_, module, fun, arity}, _link_text),
do: "`#{module_prefix}#{module}.#{fun}/#{arity}`"
defp default_title(pmfa, module_id)
defp default_title({prefix, "", fun, arity}, nil), do: "#{prefix}#{fun}/#{arity}"
defp default_title({prefix, "", fun, arity}, module_id),
do: "#{prefix}#{module_id}.#{fun}/#{arity}"
defp default_title({prefix, module, fun, arity}, _),
do: "#{prefix}#{module}.#{fun}/#{arity}"
defp default_lib_dirs(),
do: default_lib_dirs(:elixir) ++ default_lib_dirs(:erlang)
defp default_lib_dirs(:elixir),
do: elixir_lib_dirs() ++ hex_lib_dirs()
defp default_lib_dirs(:erlang),
do: erlang_lib_dirs()
defp module_docs(:elixir, module, lib_dirs),
do: lib_dirs_to_doc("Elixir." <> module, lib_dirs)
defp module_docs(:erlang, module, lib_dirs),
do: lib_dirs_to_doc(module, lib_dirs)
@doc false
defp split_match(:module, string), do: {"", string, "", ""}
defp split_match(:function, string), do: split_function(string)
defp split_function("c:" <> string) do
{_, mod, fun, arity} = split_function(string)
{"c:", mod, fun, arity}
end
defp split_function("t:" <> string) do
{_, mod, fun, arity} = split_function(string)
{"t:", mod, fun, arity}
end
defp split_function(":" <> string) do
split_function(string)
end
defp split_function(string) do
string
|> String.split("/")
|> split_function_list()
end
defp split_function_list([modules, arity]) do
{mod, name} =
modules
# this handles the case of the ".." function
|> String.replace(~r{([^\.])\.}, "\\1 ")
|> String.split(" ")
|> Enum.split(-1)
{"", Enum.join(mod, "."), hd(name), arity}
end
# handles "/" function
defp split_function_list([modules, "", arity]) when is_binary(modules) do
split_function_list([modules <> "/", arity])
end
defp doc_prefix(%{type: c}) when c in [:callback, :macrocallback], do: "c:"
defp doc_prefix(%{type: _}), do: ""
defp lib_dirs_to_doc(module, lib_dirs) do
case :code.where_is_file('#{module}.beam') do
:non_existing ->
nil
path ->
path = path |> List.to_string() |> Path.expand()
lib_dirs
|> Enum.filter(fn {lib_dir, _} -> String.starts_with?(path, lib_dir) end)
|> Enum.sort_by(fn {lib_dir, _} -> -byte_size(lib_dir) end)
|> case do
[{_, doc} | _] -> doc
_ -> nil
end
end
end
defp elixir_lib_dirs do
case Application.fetch_env(:ex_doc, :elixir_lib_dirs) do
{:ok, lib_dirs} ->
lib_dirs
:error ->
lib_dirs =
for app <- ~w(elixir eex iex logger mix ex_unit) do
{elixir_lib_dir(app), @elixir_docs <> app <> "/"}
end
Application.put_env(:ex_doc, :elixir_lib_dirs, lib_dirs)
lib_dirs
end
end
defp elixir_lib_dir(app) do
path =
case :code.where_is_file('Elixir.Kernel.beam') do
:non_existing -> ""
path -> path |> List.to_string() |> Path.expand()
end
if File.exists?(path) do
elixir_root_lib =
path
|> Path.dirname()
|> Path.dirname()
|> Path.dirname()
elixir_root_lib <> "/" <> app <> "/ebin"
else
# if beam file doesn't exists it's likely an escript
Path.dirname(path)
end
end
defp hex_lib_dirs() do
if Application.spec(:hex, :vsn) do
[{Application.app_dir(:hex, "ebin"), @elixir_docs <> "hex/"}]
else
# if Hex is not loaded it's likely an escript
[]
end
end
defp erlang_lib_dirs do
case Application.fetch_env(:ex_doc, :erlang_lib_dirs) do
{:ok, lib_dirs} ->
lib_dirs
:error ->
lib_dirs = [{Path.expand(:code.lib_dir()), @erlang_docs}]
Application.put_env(:ex_doc, :erlang_lib_dirs, lib_dirs)
lib_dirs
end
end
defp split_string_to_link(string) do
case :binary.split(string, "(") do
[head, tail] -> {head, "(" <> tail}
[head] -> {head, ""}
end
end
defp expand_alias({:__aliases__, _, [h | t]}) when is_atom(h), do: Module.concat([h | t])
defp expand_alias(atom) when is_atom(atom), do: atom
defp expand_alias(_), do: nil
defp get_source(alias, aliases, lib_dirs) do
cond do
is_nil(alias) -> nil
alias in aliases -> ""
doc = lib_dirs_to_doc(alias, lib_dirs) -> doc
true -> nil
end
end
defp get_elixir_docs(aliases, lib_dirs) do
get_source(Kernel, aliases, lib_dirs)
end
@doc false
def backtick_token(), do: @backtick_token
## REGULAR EXPRESSION HELPERS
# Returns a the string source of a regular expression,
# given the `name` and `language`
defp re_source(name, language \\ :elixir) do
Regex.source(re(name, language))
end
# Returns a regular expression
# given the `name` and `language`
defp re(:prefix, :elixir) do
~r{
[ct]: # c:, t:
}x
end
defp re(:m, :elixir) do
~r{
( [A-Z] # start with uppercase letter
[_a-zA-Z0-9]*\.? # followed by optional letter, number or underscore
)+ # this pattern could be repeated
(?<!\.) # it must not end with a "."
}x
end
defp re(:m, :erlang) do
~r{
: # prefix
[A-Za-z_]+ # module_name
}x
end
defp re(:f, :elixir) do
~r{
([a-z_][_a-zA-Z0-9]*[\\?\\!]?) # regular function_name
| # OR
[\{\}=&\\|\\.<>~*^@\\+\\%\\!-\/]+ # special_form
}x
end
defp re(:f, :erlang) do
~r{
([a-z_][_a-zA-Z0-9]*[\\?\\!]?)
}x
end
defp re(:fa, language) when language in [:elixir, :erlang] do
~r{
(#{re_source(:f, language)}) # function_name
/\d+ # /arity
}x
end
defp re(:mfa, :elixir) do
~r{
(#{re_source(:prefix)})? # optional callback/type identifier or ":"
(
(#{re_source(:m)}\.)
#{re_source(:fa)}
)
}x
end
defp re(:mfa, :erlang) do
~r{
#{re_source(:m, :erlang)} # module_name
\. # "."
#{re_source(:fa, :erlang)} # function_name/arity
}x
end
defp re(:local, :elixir) do
~r{
(#{re_source(:prefix)})? # optional callback or type identifier
#{re_source(:fa)} # function_name/arity
}x
end
defp re_kind_language(:module, :elixir) do
~r{
#{re_source(:m)}
}x
end
defp re_kind_language(:module, :erlang) do
~r{
#{re_source(:m, :erlang)}
}x
end
defp re_kind_language(:function, :elixir) do
~r{
(#{re_source(:local)}) | (#{re_source(:mfa)})
}x
end
defp re_kind_language(:function, :erlang) do
~r{
#{re_source(:mfa, :erlang)}
}x
end
defp re_kind_language(:mix_task, :elixir) do
~r{
mix\ (help\ )?([a-z][a-z0-9\._]*)
}x
end
defp re_kind_language_link_type(kind, language, link_type) do
source = Regex.source(re_kind_language(kind, language))
case link_type do
:normal ->
# Capture 1 is ignored
~r{
(?<!\]\() # it shouldn't be preceded by "]("
(?<!``)
(`\s* # leading backtick
(#{source}) # CAPTURE 2
\s*`) # trailing backtick
(?!`)
# (?!\)\]) # it shouldn't be followed by ")]"
}x
:custom ->
~r{
\[(.*?)\] # CAPTURE 1
\(`(#{source})`\) # CAPTURE 2
}x
end
end
end
| 28.515789
| 106
| 0.577458
|
93aa3bada46a581e05d24cb9f2b7cf2460609eef
| 1,356
|
ex
|
Elixir
|
golden/lib/element.ex
|
NduatiK/marker
|
a0af6f083feba029ae02221b0ab44cfe865c43bb
|
[
"Apache-2.0"
] | null | null | null |
golden/lib/element.ex
|
NduatiK/marker
|
a0af6f083feba029ae02221b0ab44cfe865c43bb
|
[
"Apache-2.0"
] | null | null | null |
golden/lib/element.ex
|
NduatiK/marker
|
a0af6f083feba029ae02221b0ab44cfe865c43bb
|
[
"Apache-2.0"
] | null | null | null |
defmodule Element do
use Marker
require Marker.HTML
def merge_attr(default_attrs, assigns) do
imported_attrs =
assigns
|> Map.to_list()
|> Enum.filter(fn
{:__content__, v} -> false
{k, v} -> true
end)
attrs =
Keyword.merge(default_attrs, imported_attrs, fn
k, v1, v2 when is_binary(v1) and is_binary(v2) ->
v1 <> " " <> v2
_, _, v2 ->
v2
end)
end
Marker.component :column do
default_attrs = [class: (@class || "") <> " flex flex-col"]
attrs = merge_attr(default_attrs, assigns)
div attrs do
@__content__
end
end
Marker.component :row do
default_attrs = [class: (@class || "") <> " flex flex-row items-center"]
attrs = merge_attr(default_attrs, assigns)
div attrs do
@__content__
end
end
# defmodule Attributes do
def shrink(), do: "flex-initial"
defmacro spacing_x(space) when is_integer(space), do: quote(do: unquote(" space-x-#{space} "))
defmacro spacing_y(space) when is_integer(space), do: quote(do: unquote(" space-y-#{space} "))
defmacro spacing(space) when is_integer(space),
do: quote(do: unquote(" space-x-#{space} space-y-#{space} "))
defmacro spacing_xy(x, y) when is_integer(x) and is_integer(y),
do: quote(do: unquote(" space-x-#{x} space-y-#{y} "))
end
| 24.654545
| 96
| 0.610619
|
93aa4d6bf730fd3f698ba9023ee4e8d7905b1bd4
| 2,183
|
ex
|
Elixir
|
clients/content/lib/google_api/content/v21/model/account_ads_link.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v21/model/account_ads_link.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/content/lib/google_api/content/v21/model/account_ads_link.ex
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V21.Model.AccountAdsLink do
@moduledoc """
## Attributes
* `adsId` (*type:* `String.t`, *default:* `nil`) - Customer ID of the Ads account.
* `status` (*type:* `String.t`, *default:* `nil`) - Status of the link between this Merchant Center account and the Ads account. Upon retrieval, it represents the actual status of the link and can be either `active` if it was approved in Google Ads or `pending` if it's pending approval. Upon insertion, it represents the intended status of the link. Re-uploading a link with status `active` when it's still pending or with status `pending` when it's already active will have no effect: the status will remain unchanged. Re-uploading a link with deprecated status `inactive` is equivalent to not submitting the link at all and will delete the link if it was active or cancel the link request if it was pending.
Acceptable values are:
- "`active`"
- "`pending`"
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:adsId => String.t(),
:status => String.t()
}
field(:adsId)
field(:status)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V21.Model.AccountAdsLink do
def decode(value, options) do
GoogleApi.Content.V21.Model.AccountAdsLink.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V21.Model.AccountAdsLink do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.425926
| 714
| 0.728355
|
93aa516b5ac36ea56c9bf75ece994fb87ca42c83
| 1,231
|
exs
|
Elixir
|
mix.exs
|
junsumida/exvcr
|
0f8aeeb19e5164917302ce257a2a1c324e02ff3b
|
[
"MIT"
] | null | null | null |
mix.exs
|
junsumida/exvcr
|
0f8aeeb19e5164917302ce257a2a1c324e02ff3b
|
[
"MIT"
] | null | null | null |
mix.exs
|
junsumida/exvcr
|
0f8aeeb19e5164917302ce257a2a1c324e02ff3b
|
[
"MIT"
] | 1
|
2018-10-10T05:57:37.000Z
|
2018-10-10T05:57:37.000Z
|
defmodule ExVCR.Mixfile do
use Mix.Project
def project do
[ app: :exvcr,
version: "0.9.0",
elixir: "~> 1.3",
deps: deps(),
description: description(),
package: package(),
test_coverage: [tool: ExCoveralls],
preferred_cli_env: [coveralls: :test]
]
end
# Configuration for the OTP application
def application do
[applications: [:meck, :exactor, :exjsx]]
end
# Returns the list of dependencies in the format:
# { :foobar, "~> 0.1", git: "https://github.com/elixir-lang/foobar.git" }
def deps do
[
{:meck, "~> 0.8.3"},
{:exactor, "~> 2.2"},
{:exjsx, "~> 4.0"},
{:ibrowse, "~> 4.4", optional: true},
{:httpotion, "~> 3.0", optional: true},
{:httpoison, "~> 0.13", optional: true},
{:excoveralls, "~> 0.7", only: :test},
{:http_server, github: "parroty/http_server", only: [:dev, :test]},
{:ex_doc, ">= 0.0.0", only: :dev}
]
end
defp description do
"""
HTTP request/response recording library for elixir, inspired by VCR.
"""
end
defp package do
[ maintainers: ["parroty"],
licenses: ["MIT"],
links: %{"GitHub" => "https://github.com/parroty/exvcr"} ]
end
end
| 25.122449
| 75
| 0.56052
|
93aa52a134c169d482ad7cd990aa2bb98c779601
| 857
|
exs
|
Elixir
|
test/whistler_news_reader/feed_test.exs
|
fdietz/whistler_news_reader
|
501f3f95e1ba3a684da8b34b60e426da85e7852d
|
[
"MIT"
] | 8
|
2016-06-12T20:11:26.000Z
|
2017-05-02T04:36:41.000Z
|
test/whistler_news_reader/feed_test.exs
|
fdietz/whistler_news_reader
|
501f3f95e1ba3a684da8b34b60e426da85e7852d
|
[
"MIT"
] | 2
|
2016-06-12T15:49:06.000Z
|
2016-06-12T20:00:02.000Z
|
test/whistler_news_reader/feed_test.exs
|
fdietz/whistler_news_reader
|
501f3f95e1ba3a684da8b34b60e426da85e7852d
|
[
"MIT"
] | null | null | null |
defmodule WhistlerNewsReader.FeedTest do
use WhistlerNewsReader.ModelCase
alias WhistlerNewsReader.Feed
@valid_attrs %{
title: "The Verge",
feed_url: "http://www.theverge.com/rss/frontpage",
site_url: "http://www.theverge.com"
}
@invalid_attrs %{}
test "changeset with valid attributes" do
changeset = Feed.changeset(%Feed{}, @valid_attrs)
assert changeset.valid?
end
test "changeset with invalid attributes" do
changeset = Feed.changeset(%Feed{}, @invalid_attrs)
refute changeset.valid?
end
test "fails if feed exists already for feed_url" do
%Feed{}
|> Feed.changeset(@valid_attrs)
|> Repo.insert!
feed = %Feed{}
|> Feed.changeset(@valid_attrs)
assert {:error, changeset} = Repo.insert(feed)
assert changeset.errors[:feed_url] == {"has already been taken", []}
end
end
| 23.805556
| 72
| 0.683781
|
93aaa328d212edbad39068d7acd0a08cdc545ee2
| 415
|
ex
|
Elixir
|
test/support/pages/mastery/show_page.ex
|
ktornwall/elixir_conf_2016_demo
|
5a0adf832773714ba7743c049964623262ee7a13
|
[
"MIT"
] | 27
|
2016-09-02T19:26:16.000Z
|
2017-11-30T02:27:16.000Z
|
test/support/pages/mastery/show_page.ex
|
katzenbar/elixir_conf_2016_demo
|
5a0adf832773714ba7743c049964623262ee7a13
|
[
"MIT"
] | 1
|
2016-10-23T18:24:59.000Z
|
2016-10-23T18:24:59.000Z
|
test/support/pages/mastery/show_page.ex
|
ktornwall/elixir_conf_2016_demo
|
5a0adf832773714ba7743c049964623262ee7a13
|
[
"MIT"
] | 4
|
2016-10-08T02:51:41.000Z
|
2017-12-05T02:02:40.000Z
|
defmodule ExConf.MasteryShowPage do
use ExConf.PageHelpers
def visit(mastery) do
navigate_to "/masteries/#{mastery.id}"
end
def current_page?(mastery) do
current_path == "/masteries/#{mastery.id}"
end
def has_mastery_name?(mastery) do
find_element(:class, "qa-name") |> visible_text == mastery.name
end
def has_skin?(skin) do
find_element(:class, "qa-skin-#{skin.id}")
end
end
| 20.75
| 67
| 0.691566
|
93aaaf2e85c85295ff9c26393e4e00e9d7d7f601
| 548
|
exs
|
Elixir
|
rest/mix.exs
|
jonasrichard/elixir-playground
|
1508f758d9f7a11cc37dae428345f88e3c9501fd
|
[
"Apache-2.0"
] | null | null | null |
rest/mix.exs
|
jonasrichard/elixir-playground
|
1508f758d9f7a11cc37dae428345f88e3c9501fd
|
[
"Apache-2.0"
] | null | null | null |
rest/mix.exs
|
jonasrichard/elixir-playground
|
1508f758d9f7a11cc37dae428345f88e3c9501fd
|
[
"Apache-2.0"
] | null | null | null |
defmodule Rest.MixProject do
use Mix.Project
def project do
[
app: :rest,
version: "0.1.0",
elixir: "~> 1.9",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger],
mod: {Rest, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:ecto, "~> 3.3.3"},
{:ecto_sql, "~> 3.0"},
{:postgrex, "~> 0.15.3"}
]
end
end
| 17.677419
| 59
| 0.525547
|
93aabf5c2e49520a5440252085780baa4b3f65ae
| 957
|
ex
|
Elixir
|
lib/livebook_web/live/explore_helpers.ex
|
chriskdon/livebook
|
b1b573b5f4b49b2e90585e8f511e7b261dcae550
|
[
"Apache-2.0"
] | 1,846
|
2021-04-13T14:46:36.000Z
|
2021-07-14T20:37:40.000Z
|
lib/livebook_web/live/explore_helpers.ex
|
chriskdon/livebook
|
b1b573b5f4b49b2e90585e8f511e7b261dcae550
|
[
"Apache-2.0"
] | 411
|
2021-07-15T07:41:54.000Z
|
2022-03-31T21:34:22.000Z
|
lib/livebook_web/live/explore_helpers.ex
|
chriskdon/livebook
|
b1b573b5f4b49b2e90585e8f511e7b261dcae550
|
[
"Apache-2.0"
] | 130
|
2021-04-13T15:43:55.000Z
|
2021-07-12T16:57:46.000Z
|
defmodule LivebookWeb.ExploreHelpers do
use Phoenix.Component
alias LivebookWeb.Router.Helpers, as: Routes
@doc """
Renders an explore notebook card.
"""
def notebook_card(assigns) do
~H"""
<div class="flex flex-col">
<%= live_redirect to: Routes.explore_path(@socket, :notebook, @notebook_info.slug),
class: "flex items-center justify-center p-6 border-2 border-gray-100 rounded-t-2xl h-[150px]" do %>
<img src={@notebook_info.details.cover_url} class="max-h-full max-w-[75%]" />
<% end %>
<div class="px-6 py-4 bg-gray-100 rounded-b-2xl grow">
<%= live_redirect @notebook_info.title,
to: Routes.explore_path(@socket, :notebook, @notebook_info.slug),
class: "text-gray-800 font-semibold cursor-pointer" %>
<p class="mt-2 text-sm text-gray-600">
<%= @notebook_info.details.description %>
</p>
</div>
</div>
"""
end
end
| 34.178571
| 112
| 0.62069
|
93ab00cccce4f4972cded9e9b4690163102af43b
| 772
|
ex
|
Elixir
|
test/support/fixtures/accounts_fixtures.ex
|
manojsamanta/stripe-single-product
|
d0af1cede55ce6ac71100b9f4b5473919c16c884
|
[
"MIT"
] | null | null | null |
test/support/fixtures/accounts_fixtures.ex
|
manojsamanta/stripe-single-product
|
d0af1cede55ce6ac71100b9f4b5473919c16c884
|
[
"MIT"
] | null | null | null |
test/support/fixtures/accounts_fixtures.ex
|
manojsamanta/stripe-single-product
|
d0af1cede55ce6ac71100b9f4b5473919c16c884
|
[
"MIT"
] | null | null | null |
defmodule SingleProduct.AccountsFixtures do
@moduledoc """
This module defines test helpers for creating
entities via the `SingleProduct.Accounts` context.
"""
def unique_user_email, do: "user#{System.unique_integer()}@example.com"
def valid_user_password, do: "hello world!"
def valid_user_attributes(attrs \\ %{}) do
Enum.into(attrs, %{
email: unique_user_email(),
password: valid_user_password()
})
end
def user_fixture(attrs \\ %{}) do
{:ok, user} =
attrs
|> valid_user_attributes()
|> SingleProduct.Accounts.register_user()
user
end
def extract_user_token(fun) do
{:ok, captured} = fun.(&"[TOKEN]#{&1}[TOKEN]")
[_, token, _] = String.split(captured.body, "[TOKEN]")
token
end
end
| 24.125
| 73
| 0.656736
|
93ab23f5e8f7710b048a05f08fa6fba71bb15aea
| 1,553
|
exs
|
Elixir
|
installer/test/phx_new_web_test.exs
|
tgxworld/phoenix
|
89b885591431170de73e372d9544d841bedca3db
|
[
"MIT"
] | 2
|
2020-07-24T08:34:36.000Z
|
2021-02-08T03:21:49.000Z
|
installer/test/phx_new_web_test.exs
|
tgxworld/phoenix
|
89b885591431170de73e372d9544d841bedca3db
|
[
"MIT"
] | null | null | null |
installer/test/phx_new_web_test.exs
|
tgxworld/phoenix
|
89b885591431170de73e372d9544d841bedca3db
|
[
"MIT"
] | null | null | null |
Code.require_file "mix_helper.exs", __DIR__
defmodule Mix.Tasks.Phx.New.WebTest do
use ExUnit.Case
import MixHelper
import ExUnit.CaptureIO
@app_name "phx_web"
setup do
# The shell asks to install deps.
# We will politely say not.
send self(), {:mix_shell_input, :yes?, false}
:ok
end
test "new without args" do
in_tmp_umbrella_project "new without args", fn ->
assert capture_io(fn -> Mix.Tasks.Phx.New.Web.run([]) end) =~
"Creates a new Phoenix web project within an umbrella project."
end
end
test "new outside umbrella", config do
in_tmp config.test, fn ->
assert_raise Mix.Error, ~r"The web task can only be run within an umbrella's apps directory", fn ->
Mix.Tasks.Phx.New.Web.run ["007invalid"]
end
end
end
test "new with defaults" do
in_tmp_umbrella_project "new with defaults", fn ->
Mix.Tasks.Phx.New.Web.run([@app_name])
assert_file "../config/config.exs", fn file ->
assert file =~ "generators: [context_app: false]"
end
assert_file "#{@app_name}/mix.exs", fn file ->
assert file =~ "{:jason, \"~> 1.0\"}"
end
# Install dependencies?
assert_received {:mix_shell, :yes?, ["\nFetch and install dependencies?"]}
# Instructions
assert_received {:mix_shell, :info, ["\nWe are almost there" <> _ = msg]}
assert msg =~ "$ cd phx_web"
assert msg =~ "$ mix deps.get"
assert_received {:mix_shell, :info, ["Start your Phoenix app" <> _]}
end
end
end
| 27.732143
| 105
| 0.630393
|
93ab4f0a2ea4f5114db32cc2448df106d8bf67b6
| 1,062
|
ex
|
Elixir
|
lib/grapevine/events/event.ex
|
shanesveller/grapevine
|
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
|
[
"MIT"
] | null | null | null |
lib/grapevine/events/event.ex
|
shanesveller/grapevine
|
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
|
[
"MIT"
] | null | null | null |
lib/grapevine/events/event.ex
|
shanesveller/grapevine
|
fe74ade1adff88dfe4c1ab55fee3902dbb4664fe
|
[
"MIT"
] | null | null | null |
defmodule Grapevine.Events.Event do
@moduledoc """
Event Schema
"""
use Ecto.Schema
import Ecto.Changeset
alias Grapevine.Games.Game
@type t :: %__MODULE__{}
schema "events" do
field(:title, :string)
field(:description, :string)
field(:start_date, :date)
field(:end_date, :date)
belongs_to(:game, Game)
timestamps()
end
def changeset(struct, params) do
struct
|> cast(params, [:title, :description, :start_date, :end_date])
|> validate_required([:title, :start_date, :end_date])
|> validate_start_before_end()
end
defp validate_start_before_end(changeset) do
with start_date when start_date != nil <- get_field(changeset, :start_date),
end_date when end_date != nil <- get_field(changeset, :end_date) do
case Timex.before?(start_date, end_date) || start_date == end_date do
true ->
changeset
false ->
add_error(changeset, :end_date, "must come after the start date")
end
else
_ ->
changeset
end
end
end
| 22.125
| 80
| 0.642185
|
93ab57337bcc1e7057502ddb68094ab813af0261
| 2,738
|
exs
|
Elixir
|
test/gradient/tokens_test.exs
|
rodrigues/gradient
|
c09245b42d8d01b2624ca07648c41cc1a2dee49c
|
[
"Apache-2.0"
] | null | null | null |
test/gradient/tokens_test.exs
|
rodrigues/gradient
|
c09245b42d8d01b2624ca07648c41cc1a2dee49c
|
[
"Apache-2.0"
] | null | null | null |
test/gradient/tokens_test.exs
|
rodrigues/gradient
|
c09245b42d8d01b2624ca07648c41cc1a2dee49c
|
[
"Apache-2.0"
] | null | null | null |
defmodule Gradient.TokensTest do
use ExUnit.Case
doctest Gradient.Tokens
alias Gradient.Tokens
import Gradient.TestHelpers
test "drop_tokens_while" do
tokens = example_tokens()
matcher = fn
{:atom, _, :ok} -> false
_ -> true
end
assert [] =
Tokens.drop_tokens_while(
tokens,
5,
matcher
)
refute [] ==
Tokens.drop_tokens_while(
tokens,
6,
matcher
)
refute [] ==
Tokens.drop_tokens_while(
tokens,
matcher
)
end
test "get_list_from_tokens" do
tokens = example_string_tokens()
ts = Tokens.drop_tokens_to_line(tokens, 4)
opts = [end_line: -1]
assert {:charlist, _} = Tokens.get_list(ts, opts)
ts = Tokens.drop_tokens_to_line(ts, 6)
assert {:list, _} = Tokens.get_list(ts, opts)
end
describe "get_conditional/1" do
test "case" do
{tokens, _ast} = load("/conditional/Elixir.Conditional.Case.beam", "/conditional/case.ex")
tokens = Tokens.drop_tokens_to_line(tokens, 2)
opts = [end_line: -1]
assert {:case, _} = Tokens.get_conditional(tokens, 4, opts)
tokens = Tokens.drop_tokens_to_line(tokens, 9)
assert {:case, _} = Tokens.get_conditional(tokens, 10, opts)
end
test "if" do
{tokens, _ast} = load("/conditional/Elixir.Conditional.If.beam", "/conditional/if.ex")
tokens = Tokens.drop_tokens_to_line(tokens, 2)
opts = [end_line: -1]
assert {:if, _} = Tokens.get_conditional(tokens, 4, opts)
tokens = Tokens.drop_tokens_to_line(tokens, 12)
assert {:if, _} = Tokens.get_conditional(tokens, 13, opts)
end
test "unless" do
{tokens, _ast} =
load("/conditional/Elixir.Conditional.Unless.beam", "/conditional/unless.ex")
tokens = Tokens.drop_tokens_to_line(tokens, 2)
opts = [end_line: -1]
assert {:unless, _} = Tokens.get_conditional(tokens, 3, opts)
end
test "cond" do
{tokens, _ast} = load("/conditional/Elixir.Conditional.Cond.beam", "/conditional/cond.ex")
tokens = Tokens.drop_tokens_to_line(tokens, 2)
opts = [end_line: -1]
assert {:cond, _} = Tokens.get_conditional(tokens, 4, opts)
tokens = Tokens.drop_tokens_to_line(tokens, 10)
assert {:cond, _} = Tokens.get_conditional(tokens, 13, opts)
end
test "with" do
{tokens, _ast} = load("/conditional/Elixir.Conditional.With.beam", "/conditional/with.ex")
tokens = Tokens.drop_tokens_to_line(tokens, 6)
opts = [end_line: -1]
assert {:with, _} = Tokens.get_conditional(tokens, 7, opts)
end
end
end
| 27.938776
| 96
| 0.605186
|
93ab942fc2ae425911f446bbc4bda3f6d91ffb89
| 10,709
|
exs
|
Elixir
|
test/scenic/primitive_test.exs
|
zacck/scenic
|
5f2170b7fba63b0af597ddeb3107fb1ffb79c2fe
|
[
"Apache-2.0"
] | null | null | null |
test/scenic/primitive_test.exs
|
zacck/scenic
|
5f2170b7fba63b0af597ddeb3107fb1ffb79c2fe
|
[
"Apache-2.0"
] | null | null | null |
test/scenic/primitive_test.exs
|
zacck/scenic
|
5f2170b7fba63b0af597ddeb3107fb1ffb79c2fe
|
[
"Apache-2.0"
] | null | null | null |
#
# Created by Boyd Multerer on 5/7/17.
# Copyright © 2017 Kry10 Industries. All rights reserved.
#
defmodule Scenic.PrimitiveTest do
use ExUnit.Case, async: true
doctest Scenic.Primitive
alias Scenic.Primitive
alias Scenic.Primitive.Group
# alias Scenic.Math.Matrix
# import IEx
defmodule TestStyle do
def get(_), do: :test_style_getter
end
# @identity Matrix.identity()
@tx_pin {10, 11}
@tx_rotate 0.1
@transforms %{pin: @tx_pin, rotate: @tx_rotate}
@styles %{fill: :yellow, stroke: {10, :green}}
# @parent_uid 123
@type_module Group
@data [1, 2, 3, 4, 5]
@primitive %Primitive{
module: @type_module,
# uid: nil,
# parent_uid: @parent_uid,
data: @data,
id: :test_id,
transforms: @transforms,
styles: @styles
}
@minimal_primitive %{
data: {Group, @data},
styles: %{
fill: {:color, {255, 255, 0, 255}},
stroke: {10, {:color, {0, 128, 0, 255}}}
},
transforms: %{pin: {10, 11}, rotate: 0.1},
id: :test_id
}
@boring_primitive %Primitive{
module: @type_module,
data: []
}
@minimal_boring_primitive %{
data: {Group, []},
transforms: %{}
}
# @primitive_2 %Primitive{
# module: @type_module,
# data: @data,
# id: {:test_id, 123},
# transforms: @transforms,
# styles: @styles,
# }
# ============================================================================
# build( data, module, opts \\ [] )
test "basic primitive build works" do
assert Primitive.build(Group, @data) == %{
__struct__: Primitive,
module: Group,
data: @data,
parent_uid: -1
}
end
# test "build sets the optional tag list" do
# assert Primitive.build(Group, @data, tags: [:one, "two"]) == %{
# __struct__: Primitive, module: Group, data: @data,
# tags: [:one, "two"]
# }
# end
test "build adds transform options" do
assert Primitive.build(Group, @data, pin: {10, 11}, rotate: 0.1) == %{
__struct__: Primitive,
module: Group,
data: @data,
transforms: @transforms,
parent_uid: -1
}
end
test "build adds the style opts" do
assert Primitive.build(Group, @data, fill: :yellow, stroke: {10, :green}) == %{
__struct__: Primitive,
module: Group,
data: @data,
styles: @styles,
parent_uid: -1
}
end
# test "build sets the optional state" do
# assert Primitive.build(Group, @data, state: @state) == %{
# __struct__: Primitive, module: Group, uid: nil, parent_uid: -1, data: @data,
# state: @state
# }
# end
test "build sets the optional id" do
assert Primitive.build(Group, @data, id: :test_id) == %{
__struct__: Primitive,
module: Group,
data: @data,
id: :test_id,
parent_uid: -1
}
end
test "build sets a non-atom id" do
assert Primitive.build(Group, @data, id: {:test_id, 123}) == %{
__struct__: Primitive,
module: Group,
data: @data,
id: {:test_id, 123},
parent_uid: -1
}
end
test "build raises on bad tx" do
assert_raise Primitive.Transform.FormatError, fn ->
Primitive.build(Group, @data, rotate: :invalid)
end
end
test "build raises on bad style" do
assert_raise Primitive.Style.FormatError, fn ->
Primitive.build(Group, @data, fill: :invalid)
end
end
# ============================================================================
# structure
# --------------------------------------------------------
# put
test "put updates a primitives data field" do
assert Primitive.put(@primitive, [1, 2, 5, 6]).data == [1, 2, 5, 6]
end
test "put rejects invalid data for a primitive" do
assert_raise Primitive.Error, fn ->
Primitive.put(@primitive, :banana)
end
end
test "put updates the options on a primitive" do
assert Primitive.put(@primitive, [1, 2, 5, 6], fill: :blue).styles == %{
fill: :blue,
stroke: {10, :green}
}
end
test "put rejects invalid style" do
assert_raise Primitive.Style.FormatError, fn ->
Primitive.put(@primitive, [1, 2, 5, 6], fill: :invalid)
end
end
test "put rejects invalid transform" do
assert_raise Primitive.Transform.FormatError, fn ->
Primitive.put(@primitive, [1, 2, 5, 6], rotate: :invalid)
end
end
# --------------------------------------------------------
# put
test "put_opts updates only the options on a primitive" do
assert Primitive.put_opts(@primitive, fill: :blue).styles == %{
fill: :blue,
stroke: {10, :green}
}
end
test "put_opts rejects invalid style" do
assert_raise Primitive.Style.FormatError, fn ->
Primitive.put_opts(@primitive, fill: :invalid)
end
end
test "put_opts rejects invalid transform" do
assert_raise Primitive.Transform.FormatError, fn ->
Primitive.put_opts(@primitive, rotate: :invalid)
end
end
# ============================================================================
# transform field
test "get_transforms returns the transforms" do
assert Primitive.get_transforms(@primitive) == @transforms
end
test "get_transform returns the transform" do
assert Primitive.get_transform(@primitive, :pin) == @tx_pin
end
test "put_transform sets the transform" do
p = Primitive.put_transform(@primitive, :pin, {987, 654})
assert Primitive.get_transform(p, :pin) == {987, 654}
end
test "put_transform puts a list of transforms" do
p = Primitive.put_transform(@primitive, pin: {1, 2}, scale: 1.2)
assert Primitive.get_transforms(p) == %{
pin: {1, 2},
scale: 1.2,
rotate: @tx_rotate
}
end
test "put_transform deletes the transform type if setting to nil" do
p = Primitive.put_transform(@primitive, :pin, nil)
assert Primitive.get_transforms(p) == %{rotate: @tx_rotate}
end
test "put_transforms sets the transform to nil" do
p = Primitive.put_transforms(@primitive, nil)
assert Map.get(p, :transforms) == nil
end
test "delete_transform removes a transform" do
assert Primitive.delete_transform(@primitive, :pin)
|> Primitive.get_transforms() == %{rotate: 0.1}
end
# ============================================================================
# style field
# --------------------------------------------------------
# styles
test "get_styles returns the transform list" do
assert Primitive.get_styles(@primitive) == @styles
end
test "get_style returns a style by key" do
assert Primitive.get_style(@primitive, :fill) == :yellow
end
test "get_style returns nil if missing by default" do
assert Primitive.get_style(@primitive, :missing) == nil
end
test "get_style returns default if missing" do
assert Primitive.get_style(@primitive, :missing, "default") == "default"
end
test "put_style adds to the style map" do
p = Primitive.put_style(@primitive, :font, :roboto)
assert Primitive.get_styles(p) == %{
font: :roboto,
fill: :yellow,
stroke: {10, :green}
}
end
test "put_style replaces a style in the style map" do
p =
@primitive
|> Primitive.put_style(:fill, :khaki)
|> Primitive.put_style(:fill, :cornsilk)
assert Primitive.get_styles(p) == %{fill: :cornsilk, stroke: {10, :green}}
end
test "put_style a list of styles" do
new_styles = %{fill: :magenta, stroke: {4, :green}}
p = Primitive.put_style(@primitive, fill: :magenta, stroke: {4, :green})
assert Primitive.get_styles(p) == new_styles
end
test "delete_style removes a style in the style list" do
assert Primitive.delete_style(@primitive, :fill)
|> Primitive.get_styles() == %{stroke: {10, :green}}
end
# ============================================================================
# data field
# --------------------------------------------------------
# compiled primitive-specific data
test "get_data returns the primitive-specific compiled data" do
assert Primitive.get(@primitive) == @data
end
test "put_data replaces the primitive-specific compiled data" do
new_data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
p = Primitive.put(@primitive, new_data)
assert Primitive.get(p) == new_data
end
# ============================================================================
# data for the viewport
# --------------------------------------------------------
# minimal
test "minimal returns the minimal version of the prmitive" do
assert Primitive.minimal(@primitive) == @minimal_primitive
end
test "minimal returns the minimal version of a boring primitive" do
assert Primitive.minimal(@boring_primitive) == @minimal_boring_primitive
end
# --------------------------------------------------------
# NOTE: KEEP THIS AROUND for now
# delta_script
# test "delta_script returns an empty list if there is no change" do
# assert Primitive.delta_script(@primitive, @primitive) == []
# end
# test "delta_script picks up change to data" do
# p = Primitive.put(@primitive, [1,2,3])
# assert Primitive.delta_script(@primitive, p) == [{:put, :data, {Group, [1, 2, 3]}}]
# end
# test "delta_script picks up change to module" do
# p = Map.put(@primitive, :module, Primitive.Line)
# assert Primitive.delta_script(@primitive, p) == [{:put, :data, {Scenic.Primitive.Line, [1, 2, 3, 4, 5]}}]
# end
# test "delta_script picks up addition to style" do
# p = Primitive.put_style(@primitive, :hidden, true)
# assert Primitive.delta_script(@primitive, p) == [{:put, {:styles, :hidden}, true}]
# end
# test "delta_script picks up style deletion" do
# p = Primitive.put_style(@primitive, :fill, nil)
# assert Primitive.delta_script(@primitive, p) == [{:del, {:styles, :fill}}]
# end
# test "delta_script picks up addition to transforms" do
# p = Primitive.put_transform(@primitive, :translate, {12,23})
# assert Primitive.delta_script(@primitive, p) == [{:put, {:transforms, :translate}, {12, 23}}]
# end
# test "delta_script picks up transform deletion" do
# p = Primitive.put_transform(@primitive, :translate, {12,23})
# pd = Primitive.put_transform(@primitive, :translate, nil)
# assert Primitive.delta_script(p, pd) == [del: {:transforms, :translate}]
# end
end
| 29.42033
| 111
| 0.570268
|
93ab955a3eb5595d6d8846c7023d5fadf72297a8
| 1,014
|
ex
|
Elixir
|
lib/nostrum/struct/guild/audit_log.ex
|
phereford/nostrum
|
3d273671f51d839eedac4d6e52ba9cf70720ac01
|
[
"MIT"
] | 637
|
2017-03-07T11:25:35.000Z
|
2022-03-31T13:37:51.000Z
|
lib/nostrum/struct/guild/audit_log.ex
|
phereford/nostrum
|
3d273671f51d839eedac4d6e52ba9cf70720ac01
|
[
"MIT"
] | 372
|
2017-03-07T20:42:03.000Z
|
2022-03-30T22:46:46.000Z
|
lib/nostrum/struct/guild/audit_log.ex
|
phereford/nostrum
|
3d273671f51d839eedac4d6e52ba9cf70720ac01
|
[
"MIT"
] | 149
|
2017-03-07T12:11:58.000Z
|
2022-03-19T22:11:51.000Z
|
defmodule Nostrum.Struct.Guild.AuditLog do
@moduledoc """
Represents a guild's audit log.
"""
alias Nostrum.Struct.Guild.AuditLogEntry
alias Nostrum.Struct.{User, Webhook}
alias Nostrum.Util
defstruct [:entries, :users, :webhooks]
@typedoc "Entries of this guild's audit log"
@type entries :: [AuditLogEntry.t()]
@typedoc "Users found in the audit log"
@type users :: [User.t()]
@typedoc "Webhooks found in the audit log"
@type webhooks :: [Webhook.t()]
@type t :: %__MODULE__{
entries: entries,
users: users,
webhooks: webhooks
}
@doc false
def to_struct(map) do
new =
map
|> Map.new(fn {k, v} -> {Util.maybe_to_atom(k), v} end)
|> Map.update(:audit_log_entries, nil, &Util.cast(&1, {:list, {:struct, AuditLogEntry}}))
|> Map.update(:users, nil, &Util.cast(&1, {:list, {:struct, User}}))
|> Map.update(:webhooks, nil, &Util.cast(&1, {:list, {:struct, Webhook}}))
struct(__MODULE__, new)
end
end
| 26
| 95
| 0.618343
|
93abe6b7b6f51251014f10fc150a905575dfb3d2
| 264
|
ex
|
Elixir
|
test/support/factory.ex
|
tineo/absinthe_ecto
|
55e31dfd4e7932c1e31c8beac7aa22d663fdc304
|
[
"MIT"
] | 132
|
2016-11-20T22:23:30.000Z
|
2021-07-18T18:16:19.000Z
|
test/support/factory.ex
|
tineo/absinthe_ecto
|
55e31dfd4e7932c1e31c8beac7aa22d663fdc304
|
[
"MIT"
] | 34
|
2016-11-24T05:06:57.000Z
|
2022-02-23T16:57:40.000Z
|
test/support/factory.ex
|
tineo/absinthe_ecto
|
55e31dfd4e7932c1e31c8beac7aa22d663fdc304
|
[
"MIT"
] | 36
|
2016-11-22T06:38:59.000Z
|
2022-03-09T11:32:53.000Z
|
defmodule Absinthe.Ecto.Factory do
use ExMachina.Ecto, repo: Absinthe.Ecto.TestRepo
def user_factory do
%Absinthe.Ecto.User{
username: "username",
}
end
def post_factory do
%Absinthe.Ecto.Post{
user: build(:user),
}
end
end
| 16.5
| 50
| 0.659091
|
93abec53a779de0ff455119d0dd6606c37cebd67
| 309
|
ex
|
Elixir
|
lib/pdf_party/reader/io_ex.ex
|
luisgabrielroldan/pdf_party
|
f26fd69a05a9050a1a8faaa226c0c3ad5ba1c6db
|
[
"MIT"
] | 4
|
2018-10-26T02:11:14.000Z
|
2019-04-25T20:59:52.000Z
|
lib/pdf_party/reader/io_ex.ex
|
luisgabrielroldan/pdf_party
|
f26fd69a05a9050a1a8faaa226c0c3ad5ba1c6db
|
[
"MIT"
] | 1
|
2018-10-26T21:20:40.000Z
|
2018-10-26T21:20:40.000Z
|
lib/pdf_party/reader/io_ex.ex
|
luisgabrielroldan/pdf_party
|
f26fd69a05a9050a1a8faaa226c0c3ad5ba1c6db
|
[
"MIT"
] | 1
|
2018-10-26T02:11:17.000Z
|
2018-10-26T02:11:17.000Z
|
defmodule PDFParty.Reader.IOEx do
def read_line(io_device, buffer \\ "") do
io_device
|> IO.binread(1)
|> case do
:eof ->
:eof
"\r" ->
read_line(io_device, buffer)
"\n" ->
buffer
c ->
read_line(io_device, buffer <> c)
end
end
end
| 15.45
| 43
| 0.504854
|
93abf6388e804f2aa6768f4e0bb8f1ae2a31e62d
| 578
|
exs
|
Elixir
|
languages/elixir/exercises/concept/conditionals/mix.exs
|
kmjones77/v3
|
f5d88bd5d1c191ae15cfe3effdcabe623f0d56ba
|
[
"MIT"
] | null | null | null |
languages/elixir/exercises/concept/conditionals/mix.exs
|
kmjones77/v3
|
f5d88bd5d1c191ae15cfe3effdcabe623f0d56ba
|
[
"MIT"
] | null | null | null |
languages/elixir/exercises/concept/conditionals/mix.exs
|
kmjones77/v3
|
f5d88bd5d1c191ae15cfe3effdcabe623f0d56ba
|
[
"MIT"
] | null | null | null |
defmodule LogLevel.MixProject do
use Mix.Project
def project do
[
app: :conditionals,
version: "0.1.0",
elixir: "~> 1.10",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:logger]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
# {:dep_from_hexpm, "~> 0.3.0"},
# {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"}
]
end
end
| 19.931034
| 87
| 0.581315
|
93ac05f8c803544a217f593ca74d94fb96988219
| 64
|
exs
|
Elixir
|
.workshop/prerequisite.exs
|
silesian-beamers/fun-with-the-processes
|
5276ab98a66f89896ca47e633a236e618353a64f
|
[
"MIT"
] | null | null | null |
.workshop/prerequisite.exs
|
silesian-beamers/fun-with-the-processes
|
5276ab98a66f89896ca47e633a236e618353a64f
|
[
"MIT"
] | null | null | null |
.workshop/prerequisite.exs
|
silesian-beamers/fun-with-the-processes
|
5276ab98a66f89896ca47e633a236e618353a64f
|
[
"MIT"
] | null | null | null |
defmodule Workshop.Prerequisite do
use Workshop.Validator
end
| 16
| 34
| 0.84375
|
93ac18fcb5299fc01d18eccd720145cb914d5139
| 488
|
ex
|
Elixir
|
lib/mysimplelist_web/live/user_live/show.ex
|
ScorpionResponse/mysimplelist
|
3c792373cc372ab5e196fe109b9dae68b97b7220
|
[
"Apache-2.0"
] | null | null | null |
lib/mysimplelist_web/live/user_live/show.ex
|
ScorpionResponse/mysimplelist
|
3c792373cc372ab5e196fe109b9dae68b97b7220
|
[
"Apache-2.0"
] | null | null | null |
lib/mysimplelist_web/live/user_live/show.ex
|
ScorpionResponse/mysimplelist
|
3c792373cc372ab5e196fe109b9dae68b97b7220
|
[
"Apache-2.0"
] | null | null | null |
defmodule MysimplelistWeb.UserLive.Show do
use MysimplelistWeb, :live_view
alias Mysimplelist.Accounts
@impl true
def mount(_params, _session, socket) do
{:ok, socket}
end
@impl true
def handle_params(%{"id" => id}, _, socket) do
{:noreply,
socket
|> assign(:page_title, page_title(socket.assigns.live_action))
|> assign(:user, Accounts.get_user!(id))}
end
defp page_title(:show), do: "Show User"
defp page_title(:edit), do: "Edit User"
end
| 22.181818
| 67
| 0.67623
|
93ac26a24e3fde6dd7c01cdab2df730a505f30e3
| 1,561
|
ex
|
Elixir
|
athasha_wui/lib/athasha_wui_web/views/error_helpers.ex
|
samuelventura/go-sdk
|
7209256f70d39d142a2a9859061ac7ec6c19b2bc
|
[
"Unlicense"
] | null | null | null |
athasha_wui/lib/athasha_wui_web/views/error_helpers.ex
|
samuelventura/go-sdk
|
7209256f70d39d142a2a9859061ac7ec6c19b2bc
|
[
"Unlicense"
] | null | null | null |
athasha_wui/lib/athasha_wui_web/views/error_helpers.ex
|
samuelventura/go-sdk
|
7209256f70d39d142a2a9859061ac7ec6c19b2bc
|
[
"Unlicense"
] | null | null | null |
defmodule Athasha.WuiWeb.ErrorHelpers do
@moduledoc """
Conveniences for translating and building error messages.
"""
use Phoenix.HTML
@doc """
Generates tag for inlined form input errors.
"""
def error_tag(form, field) do
Enum.map(Keyword.get_values(form.errors, field), fn error ->
content_tag(:span, translate_error(error),
class: "invalid-feedback",
phx_feedback_for: input_name(form, field)
)
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(Athasha.WuiWeb.Gettext, "errors", msg, msg, count, opts)
else
Gettext.dgettext(Athasha.WuiWeb.Gettext, "errors", msg, opts)
end
end
end
| 32.520833
| 80
| 0.66624
|
93ac27193f920f8a16d211751ac38194979a1d4c
| 2,193
|
ex
|
Elixir
|
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_server_status.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_server_status.ex
|
medikent/elixir-google-api
|
98a83d4f7bfaeac15b67b04548711bb7e49f9490
|
[
"Apache-2.0"
] | null | null | null |
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_server_status.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.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatus do
@moduledoc """
## Attributes
* `data` (*type:* `GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatusData.t`, *default:* `nil`) - Details of the server status.
* `errorCode` (*type:* `String.t`, *default:* `nil`) - ID that can be used to find errors in the log files.
* `message` (*type:* `String.t`, *default:* `nil`) - Description of the operation.
* `requestId` (*type:* `String.t`, *default:* `nil`) - ID that can be used to find request details in the log files.
* `status` (*type:* `String.t`, *default:* `nil`) - Status of the operation.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:data => GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatusData.t(),
:errorCode => String.t(),
:message => String.t(),
:requestId => String.t(),
:status => String.t()
}
field(:data, as: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatusData)
field(:errorCode)
field(:message)
field(:requestId)
field(:status)
end
defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatus do
def decode(value, options) do
GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatus.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1ServerStatus do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 37.169492
| 138
| 0.710442
|
93ac32a831994909af36acc3dd82b6d762ea379b
| 5,136
|
exs
|
Elixir
|
test/machinery_test.exs
|
paralax/machinery
|
ea62dd134cddb32bd8837436476692e8e2055add
|
[
"Apache-2.0"
] | 1
|
2018-02-19T20:28:53.000Z
|
2018-02-19T20:28:53.000Z
|
test/machinery_test.exs
|
jaimeiniesta/machinery
|
69fd0f77cf6b29efceb447dc82e03c9349ef4128
|
[
"Apache-2.0"
] | null | null | null |
test/machinery_test.exs
|
jaimeiniesta/machinery
|
69fd0f77cf6b29efceb447dc82e03c9349ef4128
|
[
"Apache-2.0"
] | null | null | null |
defmodule MachineryTest do
use ExUnit.Case, async: false
doctest Machinery
alias MachineryTest.Helper
alias MachineryTest.TestStruct
alias MachineryTest.TestStateMachine
alias MachineryTest.TestStateMachineWithGuard
test "All internal functions should be injected into AST" do
assert :erlang.function_exported(TestStateMachine, :_machinery_initial_state, 0)
assert :erlang.function_exported(TestStateMachine, :_machinery_states, 0)
assert :erlang.function_exported(TestStateMachine, :_machinery_transitions, 0)
end
test "Only the declared transitions should be valid" do
created_struct = %TestStruct{state: "created", missing_fields: false}
partial_struct = %TestStruct{state: "partial", missing_fields: false}
stateless_struct = %TestStruct{}
completed_struct = %TestStruct{state: "completed"}
assert {:ok, %TestStruct{state: "partial"}} = Machinery.transition_to(created_struct, TestStateMachine, "partial")
assert {:ok, %TestStruct{state: "completed", missing_fields: false}} = Machinery.transition_to(created_struct, TestStateMachine, "completed")
assert {:ok, %TestStruct{state: "completed", missing_fields: false}} = Machinery.transition_to(partial_struct, TestStateMachine, "completed")
assert {:error, "Transition to this state isn't declared."} = Machinery.transition_to(stateless_struct, TestStateMachine, "created")
assert {:error, "Transition to this state isn't declared."} = Machinery.transition_to(completed_struct, TestStateMachine, "created")
end
test "Guard functions should be executed before moving the resource to the next state" do
struct = %TestStruct{state: "created", missing_fields: true}
assert {:error, "Transition not completed, blocked by guard function."} = Machinery.transition_to(struct, TestStateMachineWithGuard, "completed")
end
test "Guard functions should allow or block transitions" do
allowed_struct = %TestStruct{state: "created", missing_fields: false}
blocked_struct = %TestStruct{state: "created", missing_fields: true}
assert {:ok, %TestStruct{state: "completed", missing_fields: false}} = Machinery.transition_to(allowed_struct, TestStateMachineWithGuard, "completed")
assert {:error, "Transition not completed, blocked by guard function."} = Machinery.transition_to(blocked_struct, TestStateMachineWithGuard, "completed")
end
test "The first declared state should be considered the initial one" do
stateless_struct = %TestStruct{}
assert {:ok, %TestStruct{state: "partial"}} = Machinery.transition_to(stateless_struct, TestStateMachine, "partial")
end
test "Modules without guard conditions should allow transitions by default" do
struct = %TestStruct{state: "created"}
assert {:ok, %TestStruct{state: "completed"}} = Machinery.transition_to(struct, TestStateMachine, "completed")
end
@tag :capture_log
test "Implict rescue on the guard clause internals should raise any other excepetion not strictly related to missing guard_tranistion/2 existence" do
wrong_struct = %TestStruct{state: "created", force_exception: true}
assert_raise UndefinedFunctionError, fn() ->
Machinery.transition_to(wrong_struct, TestStateMachineWithGuard, "completed")
end
end
test "after_transition/2 and before_transition/2 callbacks should be automatically executed" do
struct = %TestStruct{}
assert struct.missing_fields == nil
{:ok, partial_struct} = Machinery.transition_to(struct, TestStateMachine, "partial")
assert partial_struct.missing_fields == true
{:ok, completed_struct} = Machinery.transition_to(struct, TestStateMachine, "completed")
assert completed_struct.missing_fields == false
end
@tag :capture_log
test "Implict rescue on the callbacks internals should raise any other excepetion not strictly related to missing callbacks_fallback/2 existence" do
wrong_struct = %TestStruct{state: "created", force_exception: true}
assert_raise UndefinedFunctionError, fn() ->
Machinery.transition_to(wrong_struct, TestStateMachine, "partial")
end
end
test "Persist function should be called after the transition" do
struct = %TestStruct{state: "partial"}
assert {:ok, _} = Machinery.transition_to(struct, TestStateMachine, "completed")
end
@tag :capture_log
test "Persist function should still reaise errors if not related to the existence of persist/1 method" do
wrong_struct = %TestStruct{state: "created", force_exception: true}
assert_raise UndefinedFunctionError, fn() ->
Machinery.transition_to(wrong_struct, TestStateMachine, "completed")
end
end
@tag :capture_log
test "Machinery.Transitions GenServer should be started under the Machinery.Supervisor" do
transitions_pid = Process.whereis(Machinery.Transitions)
assert Process.alive?(transitions_pid)
end
@tag :capture_log
test "Machinery.Endpoint should be started under the Machinery.Supervisor if env var `interface` is set to true" do
Helper.mahcinery_interface()
endpoint_pid = Process.whereis(Machinery.Endpoint)
assert Process.alive?(endpoint_pid)
end
end
| 48.914286
| 157
| 0.764603
|
93ac8be8ba38d9ce56120e5abaa4c230500cbb15
| 659
|
exs
|
Elixir
|
test/echo_dispatcher_test.exs
|
HCA-Healthcare/elixir-mllp
|
31d402f5d5882b57aa172ec78ed450bf9df45755
|
[
"Apache-2.0"
] | 22
|
2018-10-08T18:37:23.000Z
|
2022-02-22T13:53:38.000Z
|
test/echo_dispatcher_test.exs
|
HCA-Healthcare/elixir-mllp
|
31d402f5d5882b57aa172ec78ed450bf9df45755
|
[
"Apache-2.0"
] | 27
|
2020-03-03T16:29:22.000Z
|
2022-03-16T20:09:59.000Z
|
test/echo_dispatcher_test.exs
|
HCA-Healthcare/elixir-mllp
|
31d402f5d5882b57aa172ec78ed450bf9df45755
|
[
"Apache-2.0"
] | 10
|
2019-03-29T04:19:59.000Z
|
2021-12-13T17:39:08.000Z
|
defmodule EchoDispatcherTest do
use ExUnit.Case
alias MLLP.EchoDispatcher
doctest EchoDispatcher
test "Default dispatcher accepts HL7, logs, and returns application_reject" do
state = %MLLP.FramingContext{}
message = HL7.Examples.wikipedia_sample_hl7()
expected_reply =
MLLP.Ack.get_ack_for_message(
message,
:application_reject,
"A real MLLP message dispatcher was not provided"
)
|> to_string()
|> MLLP.Envelope.wrap_message()
expected_state = %{state | reply_buffer: expected_reply}
assert {:ok, expected_state} == EchoDispatcher.dispatch(:mllp_hl7, message, state)
end
end
| 27.458333
| 86
| 0.705615
|
93acd2ebbdc78229b855a028114a1934a8e196a4
| 1,997
|
ex
|
Elixir
|
lib/core/counter.ex
|
maartenvanvliet/prom_ex
|
8eb4f86c169af3b184a1a45cf42e298af2b05816
|
[
"MIT"
] | null | null | null |
lib/core/counter.ex
|
maartenvanvliet/prom_ex
|
8eb4f86c169af3b184a1a45cf42e298af2b05816
|
[
"MIT"
] | null | null | null |
lib/core/counter.ex
|
maartenvanvliet/prom_ex
|
8eb4f86c169af3b184a1a45cf42e298af2b05816
|
[
"MIT"
] | null | null | null |
defmodule PromEx.TelemetryMetricsPrometheus.Core.Counter do
@moduledoc false
alias Telemetry.Metrics
alias PromEx.TelemetryMetricsPrometheus.Core.EventHandler
@type config :: %{
keep: Metrics.keep(),
measurement: atom(),
metric_name: String.t(),
name: Metrics.normalized_metric_name(),
table: atom(),
tags: Metrics.tags(),
tag_values_fun: Metrics.tag_values(),
type: :counter
}
@spec register(metric :: Metrics.Counter.t(), table_id :: atom(), owner :: pid()) ::
{:ok, :telemetry.handler_id()} | {:error, :already_exists}
def register(metric, table_id, owner) do
handler_id = EventHandler.handler_id(metric.name, owner)
with :ok <-
:telemetry.attach(
handler_id,
metric.event_name,
&__MODULE__.handle_event/4,
%{
keep: metric.keep,
metric_name: "",
name: metric.name,
table: table_id,
tags: metric.tags,
tag_values_fun: metric.tag_values,
type: :counter
}
) do
{:ok, handler_id}
else
{:error, :already_exists} = error ->
error
end
end
@spec handle_event(
:telemetry.event_name(),
:telemetry.event_measurements(),
:telemetry.event_metadata(),
config()
) :: :ok
def handle_event(_event, _measurements, metadata, config) do
with true <- EventHandler.keep?(config.keep, metadata),
mapped_values <- config.tag_values_fun.(metadata),
:ok <- EventHandler.validate_tags_in_tag_values(config.tags, mapped_values) do
labels = Map.take(mapped_values, config.tags)
key = {config.name, labels}
_res = :ets.update_counter(config.table, key, 1, {key, 0})
:ok
else
false -> :ok
error -> EventHandler.handle_event_error(error, config)
end
end
end
| 29.80597
| 87
| 0.578868
|
93ace1e6eb85fb5ce326c2c3219941e67c4f23ef
| 3,068
|
exs
|
Elixir
|
test/holofans/channels_test.exs
|
DaniruKun/holobot-
|
eb17450500ac991ff879a285890e6c478874da2d
|
[
"MIT"
] | 2
|
2021-01-02T04:09:17.000Z
|
2021-01-20T04:42:32.000Z
|
test/holofans/channels_test.exs
|
DaniruKun/holobot-
|
eb17450500ac991ff879a285890e6c478874da2d
|
[
"MIT"
] | 7
|
2021-07-20T22:25:59.000Z
|
2021-12-02T23:38:47.000Z
|
test/holofans/channels_test.exs
|
DaniruKun/holobot-tg
|
eb17450500ac991ff879a285890e6c478874da2d
|
[
"MIT"
] | null | null | null |
defmodule Holobot.Holofans.ChannelsTest do
use ExUnit.Case, async: false
import Mock
alias Holobot.Holofans.{Channel, Channels}
@valid_resp_body "{\"count\":2,\"total\":63,\"channels\":[{\"id\":5,\"yt_channel_id\":\"UC0TXe_LYZ4scaW2XMyi5_kw\",\"bb_space_id\":null,\"name\":\"AZKi Channel\",\"description\":\"AZKiです。音楽を通して一人一人と繋がって\\n一緒に世界を創って行きたくて転生しました。\\n\\nチャンネル登録や、動画や生放送で\\nいっぱいコメントしてくれると嬉しいです!\\n\\nタグ #AZKi\\nファンアート #AZKiART\\nファンの名前 #開拓者\\n\\n---------------------------------------------\\n\\n■Twitter■\\nhttps://twitter.com/AZKi_VDiVA\\n\\n■Youtube■\\nhttp://ur0.work/Nu8M\\n\\n■オフィシャルストア■\\nhttps://store.azki-official.com/\\n\\n■カバー株式会社■\\nhttp://cover-corp.com/\\n\\n---------------------------------------------\",\"photo\":\"https://yt3.ggpht.com/ytc/AAUvwnikIko_2aD91x5MOTT2tETPe4R-7ozz6eIige3z=s800-c-k-c0x00ffffff-no-rj\",\"published_at\":\"2018-11-05T12:16:27.000Z\",\"twitter_link\":\"AZKi_VDiVA\",\"view_count\":11447552,\"subscriber_count\":276000,\"video_count\":148,\"video_original\":169},{\"id\":19,\"yt_channel_id\":\"UCAoy6rzhSf4ydcYjJw3WoVg\",\"bb_space_id\":null,\"name\":\"Airani Iofifteen Channel hololive-ID\",\"description\":\"Nyo! 🎨\\n\\nIofi - Bukan Anak Alien biasa di sini~ Multilingual Vtuber asal luar angkasa dan sedang kuliah jurusan DKV di Bumi \\n\\nMohon bantuannya dan jangan lupa nyalakan telepathy kalian ya 人´∀`)\\n\\n【Support & Jajanin Iofi】\\nhttps://streamlabs.com/airaniiofifteenchannelhololive-id\\n\\n【Twitter】\\nTwitter → @airaniiofifteen\\nhttps://twitter.com/airaniiofifteen \\n【Instagram】\\nhttps://www.instagram.com/airani_iofifteen/\\n【Facebook Page】\\nhttps://www.facebook.com/Airani-Iofifteen-hololive-ID-111788127142691/\\n\\n【Mitsuki-MAMA】\\nYano Mitsuki (夜ノみつき)\\nhttps://twitter.com/mituk1\\n\\n\\n【Official cover website】\\nhttp://cover-corp.com/\\n【Official Twitter Hololive Indonesia】\\nhttps://twitter.com/hololive_Id\\n【Official Facebook Hololive Indonesia】\\nhttps://www.facebook.com/Hololive-Indonesia-108806367277672/\\n\\n【Hololive Indonesia】\\nAyunda Risu (アユンダ・リス)\\nhttps://www.youtube.com/channel/UCOyYb1c43VlX9rc_lT6NKQw\\nMoona Hoshinova (ムーナ・ホシノヴァ)\\nhttps://t.co/nwIx1O5CXU?amp=1\\nAirani Iofifteen (アイラニ・イオフィフティーン)\\nhttps://www.youtube.com/cha\",\"photo\":\"https://yt3.ggpht.com/ytc/AAUvwnh4NDjjjUAfPj8Aa4kjyQb4C85KzMWobSCaso-8=s800-c-k-c0x00ffffff-no-rj\",\"published_at\":\"2020-03-03T07:35:07.178Z\",\"twitter_link\":\"airaniiofifteen\",\"view_count\":5774051,\"subscriber_count\":254000,\"video_count\":139,\"video_original\":148}]}"
# setup_with_mocks([
# {HTTPoison, [],
# [get: fn _url -> {:ok, %HTTPoison.Response{status_code: 200, body: @valid_resp_body}} end]}
# ]) do
# start_supervised!(Channels)
# Process.sleep(1000)
# :ok
# end
# test "get_channels/0 returns a list of all channels" do
# end
describe "init" do
test "init/1 sets up mnesia and returns continue" do
{:ok, %{}, {:continue, :update}} = Channels.init("some args")
assert Memento.system(:tables) |> Enum.member?(Channel)
end
end
end
| 98.967742
| 2,399
| 0.699478
|
93acec1b324704e73144c26ec607d7beed01cda3
| 420
|
ex
|
Elixir
|
lib/open_pantry/web/views/stock_view.ex
|
neilfulwiler/open_pantry
|
4b705f2282c7b2365a784503c9f1bdd34c741798
|
[
"MIT"
] | 41
|
2017-10-04T00:33:46.000Z
|
2021-04-09T01:33:34.000Z
|
lib/open_pantry/web/views/stock_view.ex
|
openpantry/open_pantry
|
27d898a65dd6f44b325f48d41bc448bb486d9c6f
|
[
"MIT"
] | 74
|
2017-09-20T03:36:17.000Z
|
2018-11-20T20:46:16.000Z
|
lib/open_pantry/web/views/stock_view.ex
|
neilfulwiler/open_pantry
|
4b705f2282c7b2365a784503c9f1bdd34c741798
|
[
"MIT"
] | 12
|
2017-10-04T10:02:49.000Z
|
2021-12-28T22:57:20.000Z
|
defmodule OpenPantry.Web.StockView do
use OpenPantry.Web, :view
def food_list do
OpenPantry.Food.all([:food_group, :credit_types])
|> Enum.map(&({"#{&1.longdesc} - #{&1.food_group.foodgroup_desc}", &1.ndb_no}))
end
def facility_list do
OpenPantry.Facility.all()
|> Enum.map(&({&1.name, &1.id}))
end
def image_url(stock) do
OpenPantry.Image.url({:stock_image, stock}, :thumb)
end
end
| 23.333333
| 83
| 0.661905
|
93aced343f2995ef659a862fb571ee4d30a88260
| 596
|
ex
|
Elixir
|
lib/adam7.ex
|
SenecaSystems/adam7
|
a3224d332ab531ebda072ec204000c592603486f
|
[
"MIT"
] | null | null | null |
lib/adam7.ex
|
SenecaSystems/adam7
|
a3224d332ab531ebda072ec204000c592603486f
|
[
"MIT"
] | null | null | null |
lib/adam7.ex
|
SenecaSystems/adam7
|
a3224d332ab531ebda072ec204000c592603486f
|
[
"MIT"
] | null | null | null |
defmodule Adam7 do
@doc """
Merge the extracted seven passes into a corresponding image.
"""
def merge(passes, {width, height}) do
Enum.reduce(1..7, empty_image_rows(width, height), fn (pass, image_rows) ->
Adam7.Pass.merge(pass, {width, height}, Enum.at(passes, pass-1), image_rows)
end)
|> :array.to_list
|> Enum.map(&:array.to_list/1)
end
defp empty_image_rows(width, height) do
:array.new([
{:size, height},
{:fixed, true},
{:default, :array.new([
{:size, width},
{:fixed, true}
])
}
])
end
end
| 23.84
| 82
| 0.578859
|
93ad3135702ecc385eb12c816cc08e43be28f1f2
| 1,165
|
exs
|
Elixir
|
clients/service_consumer_management/config/config.exs
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | 1
|
2018-12-03T23:43:10.000Z
|
2018-12-03T23:43:10.000Z
|
clients/service_consumer_management/config/config.exs
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
clients/service_consumer_management/config/config.exs
|
matehat/elixir-google-api
|
c1b2523c2c4cdc9e6ca4653ac078c94796b393c3
|
[
"Apache-2.0"
] | null | null | null |
# This file is responsible for configuring your application
# and its dependencies with the aid of the Mix.Config module.
use Mix.Config
# This configuration is loaded before any dependency and is restricted
# to this project. If another project depends on this project, this
# file won't be loaded nor affect the parent project. For this reason,
# if you want to provide default values for your application for
# 3rd-party users, it should be done in your "mix.exs" file.
# You can configure for your application as:
#
# config :service_consumer_management_api, key: :value
#
# And access this configuration in your application as:
#
# Application.get_env(:service_consumer_management_api, :key)
#
# Or configure a 3rd-party app:
#
# config :logger, level: :info
#
# It is also possible to import configuration files, relative to this
# directory. For example, you can emulate configuration per environment
# by uncommenting the line below and defining dev.exs, test.exs and such.
# Configuration from the imported file will override the ones defined
# here (which is why it is important to import them last).
#
# import_config "#{Mix.env}.exs"
| 37.580645
| 73
| 0.761373
|
93ad820f2085d2b8954dc7f03683397b45f4454a
| 4,642
|
ex
|
Elixir
|
lib/cli/commands/add.ex
|
AnilRedshift/wand-cli
|
c364cf5397353fd61ba0e5fc33225575eb72ccda
|
[
"BSD-3-Clause"
] | 3
|
2018-07-01T05:31:02.000Z
|
2019-08-03T04:11:32.000Z
|
lib/cli/commands/add.ex
|
AnilRedshift/wand-cli
|
c364cf5397353fd61ba0e5fc33225575eb72ccda
|
[
"BSD-3-Clause"
] | 8
|
2018-06-28T07:30:04.000Z
|
2018-07-13T07:36:56.000Z
|
lib/cli/commands/add.ex
|
AnilRedshift/wand-cli
|
c364cf5397353fd61ba0e5fc33225575eb72ccda
|
[
"BSD-3-Clause"
] | null | null | null |
defmodule Wand.CLI.Commands.Add do
use Wand.CLI.Command
@moduledoc """
# Add
Add elixir packages to wand.json
### Usage
**wand** add [package] [package] ... [flags]
Wand can be used to add packages from three different places: hex, git, or the local filesystem. [package] can either be the name, or name@version.
If a version is provided, the `--around` and `--exact` flags determine how the version is used.
### Hex.pm
Examples:
```
wand add poison
wand add poison@3.1
```
### Git
Include the `--git` flag to pass a URI. The URI can be one of two base formats, and can end with an optional hash of the branch, tag, or ref to use
Examples:
```
wand add poison --git="https://github.com/devinus/poison.git"
wand add poison --git="git@github.com:devinus/poison"
wand add poison@3.1 --git="https://github.com/devinus/poison.git#test"
wand add poison --git="https://github.com/devinus/poison.git#3.1.0"
```
### Local Path
Local packages are described by passing in the `--path` flag corresponding to the path location
OR, for an umbrella application, when you need to include a sibling dependency, pass the app name, along with the `--in-umbrella` flag.
Examples:
```
wand add poison --path="/absolute/path/to/poison"
wand add poison --path="../../relative/path/"
wand add sibling_dependency --in-umbrella
```
## Options
The following flags are provided. They are boolean flags unless specified.
### Hex flags
```
--hex=NAME means that the local name of the dependency is different from its name on hex
E.g. wand add mypoison --hex=poison
--organization=ORGANIZATION corresponds to the private org to pull the package(s) from.
--repo=REPO An alternative repository to use. Configure with mix hex.repo. Default: hexpm
```
### Git flags
```
--sparse=FOLDER git checkout only a single folder, and use that
--submodules tells git to also initialize submodules
```
### Environment flags
Setting these flags specifies which environments to install the dependency. If none are provided, all environments are included.
```
--env=ENVIRONMENT where ENVIRONMENT is the environment to add. This flag can be added multiple times. Example: --env=prod --env=test
--dev is shorthand for --env=dev
--test is shorthand for --env=test
--prod is shorthand for --env=prod
--compile-env=ENVIRONMENT doesnt affect which environments the dependency is loaded from. Instead, it says "when compiling the dependency, which environment to use?". Defaults to --compile-env=prod
--optional will include the project for THIS project, but not reuire it should the main project be a dependency of another project.
```
### Dependency configuration
These flags deal with what happens with the dependency once configured
```
--runtime determines whether to start the dependency. Defaults to true
--read-app-file determines if the app file for the dependency is read. Defaults to true.
--download determines if mix deps.get is run after adding the package to wand.json. Defaults to true.
```
"""
defmodule Git do
@moduledoc false
defstruct git: nil,
ref: nil,
sparse: nil,
submodules: false
end
defmodule Hex do
@moduledoc false
defstruct hex: nil,
organization: nil,
repo: :hexpm
end
defmodule Path do
@moduledoc false
defstruct path: nil,
in_umbrella: false
end
defmodule Package do
@moduledoc false
@default_requirement Wand.Mode.get_requirement!(:caret, :latest)
defstruct compile_env: :prod,
details: %Hex{},
download: true,
only: nil,
name: nil,
optional: false,
override: false,
read_app_file: true,
requirement: @default_requirement,
runtime: true
end
@doc false
def moduledoc(), do: @moduledoc
@doc false
@impl true
def help(type), do: Wand.CLI.Commands.Add.Help.help(type)
@doc false
@impl true
def options() do
[
require_core: true,
load_wand_file: true
]
end
@doc false
@impl true
def validate(args), do: Wand.CLI.Commands.Add.Validate.validate(args)
@doc false
@impl true
def execute(packages, extras), do: Wand.CLI.Commands.Add.Execute.execute(packages, extras)
@doc false
@impl true
def after_save(packages), do: Wand.CLI.Commands.Add.Execute.after_save(packages)
@doc false
@impl true
def handle_error(key, data), do: Wand.CLI.Commands.Add.Error.handle_error(key, data)
end
| 28.133333
| 199
| 0.676863
|
93ad972c99edab553f59ab5eca63edc1f87a2756
| 8,724
|
ex
|
Elixir
|
lib/rmq/rpc.ex
|
nmbrone/rmq
|
1478c80f886116638bb0a7831fcd55f6570de18c
|
[
"MIT"
] | null | null | null |
lib/rmq/rpc.ex
|
nmbrone/rmq
|
1478c80f886116638bb0a7831fcd55f6570de18c
|
[
"MIT"
] | null | null | null |
lib/rmq/rpc.ex
|
nmbrone/rmq
|
1478c80f886116638bb0a7831fcd55f6570de18c
|
[
"MIT"
] | null | null | null |
defmodule RMQ.RPC do
@moduledoc """
RPC via RabbitMQ.
In short, it's a `GenServer` which implements a publisher and a consumer at once.
You can read more about how this works in the
[tutorial](https://www.rabbitmq.com/tutorials/tutorial-six-python.html).
## Configuration
* `:connection` - the connection module which implements `RMQ.Connection` behaviour;
* `:queue` - the queue name to which the module will be subscribed for consuming responses.
Also can be a tuple `{queue, options}`. See the options for `AMQP.Queue.declare/3`.
Defaults to `""` which means the broker will assign a name to the newly created queue by itself;
* `:exchange` - the exchange name to which `:queue` will be bound.
Please make sure the exchange exist. Defaults to `""` - the default exchange;
* `:consumer_tag` - a consumer tag for `:queue`. Defaults to the current module name;
* `:publishing_options` - any valid options for `AMQP.Basic.publish/5` except
`reply_to`, `correlation_id` - these will be set automatically and cannot be changed.
Defaults to `[]`;
* `:reconnect_interval` - a reconnect interval in milliseconds. It can be also a function that
accepts the current connection attempt as a number and returns a new interval.
Defaults to `5000`;
* `:filter_parameters` - a list of parameters that may contain sensitive data and have
to be filtered out when logging. Defaults to `["password"]`.
## Example
Application 1:
defmodule MyApp.RemoteResource do
use RMQ.RPC, publishing_options: [app_id: "MyApp"]
def find_by_id(id) do
call("remote-resource-finder", %{id: id})
end
end
Application 2:
defmodule MyOtherApp.Consumer do
use RMQ.Consumer, queue: "remote-resource-finder"
@impl RMQ.Consumer
def consume(chan, payload, meta) do
response =
payload
|> Jason.decode!()
|> Map.fetch!("id")
|> MyOtherApp.Resource.get()
|> Jason.encode!()
reply(chan, meta, response)
ack(chan, meta)
end
end
"""
use RMQ.Logger
import RMQ.Utils
@defaults [
connection: RMQ.Connection,
queue: "",
exchange: "",
publishing_options: [],
reconnect_interval: 5000,
filter_parameters: ["password"]
]
@doc """
A callback for dynamic configuration.
Will be called before `c:setup_queue/2`.
"""
@callback config() :: keyword()
@doc """
Does all the job on preparing the queue.
Whenever you need full control over configuring the queue you can implement this callback and
use `AMQP` library directly.
See `setup_queue/2` for the default implementation.
"""
@callback setup_queue(chan :: AMQP.Channel.t(), config :: keyword()) :: binary()
@doc false
def start_link(module, opts) do
GenServer.start_link(module, module, Keyword.put_new(opts, :name, module))
end
@doc """
Performs a call against the given module.
Here `options` is a keyword list which will be merged into `:publishing_options` during the call
and `timeout` is the timeout in milliseconds for the inner GenServer call.
The payload will be encoded by using `Jason.encode!/1`.
"""
@spec call(
module :: module(),
queue :: binary(),
payload :: any(),
options :: keyword(),
timeout :: integer()
) :: {:ok, any()} | {:error, :not_connected} | {:error, :timeout} | {:error, any()}
def call(module, queue, payload \\ %{}, options \\ [], timeout \\ 5000) do
GenServer.call(module, {:publish, queue, payload, options}, timeout)
catch
:exit, {:timeout, _} -> {:error, :timeout}
end
@doc """
The default implementation for `c:setup_queue/2` callback.
"""
@spec setup_queue(chan :: AMQP.Channel.t(), config :: keyword()) :: binary()
def setup_queue(chan, conf) do
{q, opts} = normalize_queue(conf[:queue])
{:ok, %{queue: queue}} =
AMQP.Queue.declare(chan, q, Keyword.merge([exclusive: true, auto_delete: true], opts))
unless conf[:exchange] == "" do
:ok = AMQP.Queue.bind(chan, queue, conf[:exchange], routing_key: queue)
end
{:ok, _} = AMQP.Basic.consume(chan, queue, nil, consumer_tag: conf[:consumer_tag])
queue
end
@doc false
def init(_module, _arg) do
Process.flag(:trap_exit, true)
send(self(), {:init, 1})
{:ok, %{chan: nil, queue: nil, pids: %{}, config: %{}}}
end
@doc false
def handle_call(_module, {:publish, _queue, _payload, _options}, _from, %{chan: nil} = state) do
{:reply, {:error, :not_connected}, state}
end
def handle_call(module, {:publish, queue, payload, options}, from, %{config: config} = state) do
correlation_id = UUID.uuid1()
options =
config[:publishing_options]
|> Keyword.merge(options)
|> Keyword.put(:reply_to, state.queue)
|> Keyword.put(:correlation_id, correlation_id)
log_debug(module, [
"Publishing >>> ",
"queue=#{inspect(queue)} ",
"payload=#{inspect(filter_values(payload, config[:filter_parameters]))}"
])
payload = encode_message(payload)
case AMQP.Basic.publish(state.chan, config[:exchange], queue, payload, options) do
:ok -> {:noreply, put_in(state.pids[correlation_id], from)}
{:error, reason} -> {:reply, {:error, reason}, state}
end
end
@doc false
def handle_info(module, {:init, attempt}, state) do
config = module_config(module)
with {:ok, conn} <- config[:connection].get_connection(),
{:ok, chan} <- AMQP.Channel.open(conn) do
Process.monitor(chan.pid)
queue = module.setup_queue(chan, config)
log_info("Ready")
{:noreply, %{state | chan: chan, queue: queue, config: config}}
else
error ->
time = reconnect_interval(config[:reconnect_interval], attempt)
log_error("No connection: #{inspect(error)}. Retrying in #{time}ms")
Process.send_after(self(), {:init, attempt + 1}, time)
{:noreply, %{state | config: config}}
end
end
# Confirmation sent by the broker after registering this process as a consumer
def handle_info(_module, {:basic_consume_ok, _meta}, state) do
{:noreply, state}
end
# Sent by the broker when the consumer is unexpectedly cancelled (such as after a queue deletion)
def handle_info(_module, {:basic_cancel, _meta}, state) do
{:stop, :normal, state}
end
# Confirmation sent by the broker to the consumer process after a Basic.cancel
def handle_info(_module, {:basic_cancel_ok, _meta}, state) do
{:noreply, state}
end
def handle_info(module, {:basic_deliver, payload, meta}, %{config: config} = state) do
{pid, state} = pop_in(state.pids[meta.correlation_id])
unless is_nil(pid) do
payload = decode_message(payload)
log_debug(module, [
"Consuming <<< ",
"payload=#{inspect(filter_values(payload, config[:filter_parameters]))}"
])
GenServer.reply(pid, {:ok, payload})
AMQP.Basic.ack(state.chan, meta.delivery_tag)
end
{:noreply, state}
end
def handle_info(module, {:DOWN, _ref, :process, _pid, reason}, state) do
log_error(module, "Connection lost: #{inspect(reason)}. Reconnecting...")
send(self(), {:init, 1})
{:noreply, %{state | chan: nil}}
end
def handle_info(module, :shutdown = reason, state) do
terminate(module, reason, state)
{:noreply, state}
end
@doc false
def terminate(_module, _reason, %{chan: chan}) do
close_channel(chan)
end
defp module_config(module) do
@defaults
|> Keyword.merge(module.config())
|> Keyword.put_new(:consumer_tag, to_string(module))
end
defmacro __using__(opts \\ []) do
quote location: :keep do
use GenServer
@behaviour RMQ.RPC
@config unquote(opts)
def start_link(opts), do: RMQ.RPC.start_link(__MODULE__, opts)
def call(queue, payload \\ %{}, options \\ [], timeout \\ 5000) do
RMQ.RPC.call(__MODULE__, queue, payload, options, timeout)
end
@impl RMQ.RPC
def config, do: @config
@impl RMQ.RPC
def setup_queue(chan, config), do: RMQ.RPC.setup_queue(chan, config)
@impl GenServer
def init(arg), do: RMQ.RPC.init(__MODULE__, arg)
@impl GenServer
def handle_call(msg, from, state), do: RMQ.RPC.handle_call(__MODULE__, msg, from, state)
@impl GenServer
def handle_info(msg, state), do: RMQ.RPC.handle_info(__MODULE__, msg, state)
@impl GenServer
def terminate(reason, state), do: RMQ.RPC.terminate(__MODULE__, reason, state)
defoverridable config: 0, setup_queue: 2
end
end
end
| 31.268817
| 102
| 0.644429
|
93ae039c4716e29c8c68e6b41fbd77306d9dd189
| 1,858
|
exs
|
Elixir
|
clients/source_repo/mix.exs
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | null | null | null |
clients/source_repo/mix.exs
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-12-18T09:25:12.000Z
|
2020-12-18T09:25:12.000Z
|
clients/source_repo/mix.exs
|
MasashiYokota/elixir-google-api
|
975dccbff395c16afcb62e7a8e411fbb58e9ab01
|
[
"Apache-2.0"
] | 1
|
2020-10-04T10:12:44.000Z
|
2020-10-04T10:12:44.000Z
|
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SourceRepo.Mixfile do
use Mix.Project
@version "0.15.2"
def project() do
[
app: :google_api_source_repo,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/source_repo"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.4"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
Cloud Source Repositories API client library. Accesses source code repositories hosted by Google.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/source_repo",
"Homepage" => "https://cloud.google.com/source-repositories/docs/apis"
}
]
end
end
| 27.731343
| 102
| 0.659311
|
93ae7a6cd20802600bc800a82785491a02cf927b
| 6,653
|
ex
|
Elixir
|
lib/helios/registry/tracker/interval_tree_clock.ex
|
exponentially/helios
|
3a7b66bd95a8c53c500272eb8a269a73e6de6d8a
|
[
"Apache-2.0"
] | 12
|
2018-09-20T21:33:07.000Z
|
2020-01-14T19:31:11.000Z
|
lib/helios/registry/tracker/interval_tree_clock.ex
|
exponentially/helios
|
3a7b66bd95a8c53c500272eb8a269a73e6de6d8a
|
[
"Apache-2.0"
] | null | null | null |
lib/helios/registry/tracker/interval_tree_clock.ex
|
exponentially/helios
|
3a7b66bd95a8c53c500272eb8a269a73e6de6d8a
|
[
"Apache-2.0"
] | null | null | null |
defmodule Helios.Registry.Tracker.IntervalTreeClock do
@moduledoc """
This is an implementation of an Interval Clock Tree, ported from
the implementation in Erlang written by Paulo Sergio Almeida <psa@di.uminho.pt>
found [here](https://github.com/ricardobcl/Interval-Tree-Clocks/blob/master/erlang/itc.erl).
"""
use Bitwise
import Kernel, except: [max: 2, min: 2]
@compile {:inline, [min: 2, max: 2, drop: 2, lift: 2, base: 1, height: 1]}
@type int_tuple :: {non_neg_integer, non_neg_integer}
@type t ::
int_tuple
| {int_tuple, non_neg_integer}
| {non_neg_integer, int_tuple}
| {int_tuple, int_tuple}
@doc """
Creates a new interval tree clock
"""
@spec seed() :: __MODULE__.t()
def seed(), do: {1, 0}
@doc """
Joins two forked clocks into a single clock with both causal histories,
used for retiring a replica.
"""
@spec join(__MODULE__.t(), __MODULE__.t()) :: __MODULE__.t()
def join({i1, e1}, {i2, e2}), do: {sum(i1, i2), join_ev(e1, e2)}
@doc """
Forks a clock containing a shared causal history, used for creating new replicas.
"""
@spec fork(__MODULE__.t()) :: __MODULE__.t()
def fork({i, e}) do
{i1, i2} = split(i)
{{i1, e}, {i2, e}}
end
@doc """
Gets a snapshot of a clock without its identity. Useful for sending the clock with messages,
but cannot be used to track events.
"""
@spec peek(__MODULE__.t()) :: __MODULE__.t()
def peek({_i, e}), do: {0, e}
@doc """
Records an event on the given clock
"""
@spec event(__MODULE__.t()) :: __MODULE__.t()
def event({i, e}) do
case fill(i, e) do
^e ->
{_, e1} = grow(i, e)
{i, e1}
e1 ->
{i, e1}
end
end
@doc """
Determines if the left-hand clock is causally dominated by the right-hand clock.
If the left-hand clock is LEQ than the right-hand clock, and vice-versa, then they are
causally equivalent.
"""
@spec leq(__MODULE__.t(), __MODULE__.t()) :: boolean
def leq({_, e1}, {_, e2}), do: leq_ev(e1, e2)
@doc """
Compares two clocks.
If :eq is returned, the two clocks are causally equivalent
If :lt is returned, the first clock is causally dominated by the second
If :gt is returned, the second clock is causally dominated by the first
If :concurrent is returned, the two clocks are concurrent (conflicting)
"""
@spec compare(__MODULE__.t(), __MODULE__.t()) :: :lt | :gt | :eq | :concurrent
def compare(a, b) do
a_leq = leq(a, b)
b_leq = leq(b, a)
cond do
a_leq and b_leq -> :eq
a_leq -> :lt
b_leq -> :gt
:else -> :concurrent
end
end
@doc """
Encodes the clock as a binary
"""
@spec encode(__MODULE__.t()) :: binary
def encode({i, e}), do: :erlang.term_to_binary({i, e})
@doc """
Decodes the clock from a binary
"""
@spec decode(binary) :: {:ok, __MODULE__.t()} | {:error, {:invalid_clock, term}}
def decode(b) when is_binary(b) do
case :erlang.binary_to_term(b) do
{_i, _e} = clock ->
clock
other ->
{:error, {:invalid_clock, other}}
end
end
@doc """
Returns the length of the encoded binary representation of the clock
"""
@spec len(__MODULE__.t()) :: non_neg_integer
def len(d), do: :erlang.size(encode(d))
## Private API
defp leq_ev({n1, l1, r1}, {n2, l2, r2}) do
n1 <= n2 and leq_ev(lift(n1, l1), lift(n2, l2)) and leq_ev(lift(n1, r1), lift(n2, r2))
end
defp leq_ev({n1, l1, r1}, n2) do
n1 <= n2 and leq_ev(lift(n1, l1), n2) and leq_ev(lift(n1, r1), n2)
end
defp leq_ev(n1, {n2, _, _}), do: n1 <= n2
defp leq_ev(n1, n2), do: n1 <= n2
defp norm_id({0, 0}), do: 0
defp norm_id({1, 1}), do: 1
defp norm_id(x), do: x
defp norm_ev({n, m, m}) when is_integer(m), do: n + m
defp norm_ev({n, l, r}) do
m = min(base(l), base(r))
{n + m, drop(m, l), drop(m, r)}
end
defp sum(0, x), do: x
defp sum(x, 0), do: x
defp sum({l1, r1}, {l2, r2}), do: norm_id({sum(l1, l2), sum(r1, r2)})
defp split(0), do: {0, 0}
defp split(1), do: {{1, 0}, {0, 1}}
defp split({0, i}) do
{i1, i2} = split(i)
{{0, i1}, {0, i2}}
end
defp split({i, 0}) do
{i1, i2} = split(i)
{{i1, 0}, {i2, 0}}
end
defp split({i1, i2}), do: {{i1, 0}, {0, i2}}
defp join_ev({n1, _, _} = e1, {n2, _, _} = e2) when n1 > n2, do: join_ev(e2, e1)
defp join_ev({n1, l1, r1}, {n2, l2, r2}) when n1 <= n2 do
d = n2 - n1
norm_ev({n1, join_ev(l1, lift(d, l2)), join_ev(r1, lift(d, r2))})
end
defp join_ev(n1, {n2, l2, r2}), do: join_ev({n1, 0, 0}, {n2, l2, r2})
defp join_ev({n1, l1, r1}, n2), do: join_ev({n1, l1, r1}, {n2, 0, 0})
defp join_ev(n1, n2), do: max(n1, n2)
defp fill(0, e), do: e
defp fill(1, {_, _, _} = e), do: height(e)
defp fill(_, n) when is_integer(n), do: n
defp fill({1, r}, {n, el, er}) do
er1 = fill(r, er)
d = max(height(el), base(er1))
norm_ev({n, d, er1})
end
defp fill({l, 1}, {n, el, er}) do
el1 = fill(l, el)
d = max(height(er), base(el1))
norm_ev({n, el1, d})
end
defp fill({l, r}, {n, el, er}) do
norm_ev({n, fill(l, el), fill(r, er)})
end
defp grow(1, n) when is_integer(n), do: {0, n + 1}
defp grow({0, i}, {n, l, r}) do
{h, e1} = grow(i, r)
{h + 1, {n, l, e1}}
end
defp grow({i, 0}, {n, l, r}) do
{h, e1} = grow(i, l)
{h + 1, {n, e1, r}}
end
defp grow({il, ir}, {n, l, r}) do
{hl, el} = grow(il, l)
{hr, er} = grow(ir, r)
if hl < hr, do: {hl + 1, {n, el, r}}, else: {hr + 1, {n, l, er}}
end
defp grow(i, n) when is_integer(n) do
{h, e} = grow(i, {n, 0, 0})
{h + 100_000, e}
end
defp height({n, l, r}), do: n + max(height(l), height(r))
defp height(n), do: n
defp base({n, _, _}), do: n
defp base(n), do: n
defp lift(m, {n, l, r}), do: {n + m, l, r}
defp lift(m, n), do: n + m
defp drop(m, {n, l, r}) when m <= n, do: {n - m, l, r}
defp drop(m, n) when m <= n, do: n - m
defp max(x, y) when x <= y, do: y
defp max(x, _), do: x
defp min(x, y) when x <= y, do: x
defp min(_, y), do: y
def str({i, e}),
do: List.to_string(List.flatten([List.flatten(stri(i)), List.flatten(stre(e))]))
defp stri(0), do: '0'
defp stri(1), do: ''
defp stri({0, i}), do: 'R' ++ stri(i)
defp stri({i, 0}), do: 'L' ++ stri(i)
defp stri({l, r}), do: ['(L' ++ stri(l), '+', 'R' ++ stri(r), ')']
defp stre({n, l, 0}), do: [stre(n), 'L', stre(l)]
defp stre({n, 0, r}), do: [stre(n), 'R', stre(r)]
defp stre({n, l, r}), do: [stre(n), '(L', stre(l), '+R', stre(r), ')']
defp stre(n) when n > 0, do: :erlang.integer_to_list(n)
defp stre(_), do: ''
end
| 26.935223
| 94
| 0.556441
|
93ae8dba97311e9fb281d9436691f4f3df76bdec
| 3,025
|
exs
|
Elixir
|
.credo.exs
|
mbta/api
|
e22e0b29dfa4f600d1b630db1a391c37ad619245
|
[
"MIT"
] | 62
|
2019-01-17T12:34:39.000Z
|
2022-03-20T21:49:47.000Z
|
.credo.exs
|
mbta/api
|
e22e0b29dfa4f600d1b630db1a391c37ad619245
|
[
"MIT"
] | 375
|
2019-02-13T15:30:50.000Z
|
2022-03-30T18:50:41.000Z
|
.credo.exs
|
mbta/api
|
e22e0b29dfa4f600d1b630db1a391c37ad619245
|
[
"MIT"
] | 14
|
2019-01-16T19:35:57.000Z
|
2022-02-26T18:55:54.000Z
|
%{
configs: [
%{
name: "default",
files: %{
included: ["apps/"],
excluded: []
},
checks: [
{Credo.Check.Design.AliasUsage, false},
{Credo.Check.Readability.MaxLineLength, false},
{Credo.Check.Consistency.ExceptionNames},
{Credo.Check.Consistency.LineEndings},
{Credo.Check.Consistency.ParameterPatternMatching},
{Credo.Check.Consistency.SpaceAroundOperators},
{Credo.Check.Consistency.SpaceInParentheses},
{Credo.Check.Consistency.TabsOrSpaces},
{Credo.Check.Design.DuplicatedCode, excluded_macros: []},
{Credo.Check.Design.TagTODO, exit_status: 2},
{Credo.Check.Design.TagFIXME},
{Credo.Check.Readability.FunctionNames},
{Credo.Check.Readability.LargeNumbers},
{Credo.Check.Readability.ModuleAttributeNames},
{Credo.Check.Readability.ModuleDoc},
{Credo.Check.Readability.ModuleNames},
{Credo.Check.Readability.ParenthesesOnZeroArityDefs},
{Credo.Check.Readability.ParenthesesInCondition},
{Credo.Check.Readability.PredicateFunctionNames},
{Credo.Check.Readability.PreferImplicitTry},
{Credo.Check.Readability.RedundantBlankLines},
{Credo.Check.Readability.StringSigils},
{Credo.Check.Readability.TrailingBlankLine},
{Credo.Check.Readability.TrailingWhiteSpace},
{Credo.Check.Readability.VariableNames},
{Credo.Check.Readability.Semicolons},
{Credo.Check.Readability.SpaceAfterCommas},
{Credo.Check.Refactor.DoubleBooleanNegation},
{Credo.Check.Refactor.CondStatements},
{Credo.Check.Refactor.CyclomaticComplexity},
{Credo.Check.Refactor.FunctionArity},
{Credo.Check.Refactor.MatchInCondition},
{Credo.Check.Refactor.NegatedConditionsInUnless},
{Credo.Check.Refactor.NegatedConditionsWithElse},
{Credo.Check.Refactor.Nesting},
{Credo.Check.Refactor.PipeChainStart},
{Credo.Check.Refactor.UnlessWithElse},
{Credo.Check.Warning.BoolOperationOnSameValues},
{Credo.Check.Warning.IExPry},
{Credo.Check.Warning.IoInspect},
{Credo.Check.Warning.OperationOnSameValues},
{Credo.Check.Warning.OperationWithConstantResult},
{Credo.Check.Warning.UnusedEnumOperation},
{Credo.Check.Warning.UnusedFileOperation},
{Credo.Check.Warning.UnusedKeywordOperation},
{Credo.Check.Warning.UnusedListOperation},
{Credo.Check.Warning.UnusedPathOperation},
{Credo.Check.Warning.UnusedRegexOperation},
{Credo.Check.Warning.UnusedStringOperation},
{Credo.Check.Warning.UnusedTupleOperation},
# Controversial and experimental checks (opt-in, just remove `, false`)
{Credo.Check.Refactor.ABCSize, false},
{Credo.Check.Refactor.AppendSingleItem, false},
{Credo.Check.Refactor.VariableRebinding, false},
{Credo.Check.Warning.MapGetUnsafePass, false}
]
}
]
}
| 43.214286
| 79
| 0.680661
|
93aeca01fb8da1161855c74054e5882f2b1f5f40
| 1,633
|
ex
|
Elixir
|
clients/sql_admin/lib/google_api/sql_admin/v1/model/sql_active_directory_config.ex
|
renovate-bot/elixir-google-api
|
1da34cd39b670c99f067011e05ab90af93fef1f6
|
[
"Apache-2.0"
] | 1
|
2021-12-20T03:40:53.000Z
|
2021-12-20T03:40:53.000Z
|
clients/sql_admin/lib/google_api/sql_admin/v1/model/sql_active_directory_config.ex
|
swansoffiee/elixir-google-api
|
9ea6d39f273fb430634788c258b3189d3613dde0
|
[
"Apache-2.0"
] | 1
|
2020-08-18T00:11:23.000Z
|
2020-08-18T00:44:16.000Z
|
clients/sql_admin/lib/google_api/sql_admin/v1/model/sql_active_directory_config.ex
|
dazuma/elixir-google-api
|
6a9897168008efe07a6081d2326735fe332e522c
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.SQLAdmin.V1.Model.SqlActiveDirectoryConfig do
@moduledoc """
Active Directory configuration, relevant only for Cloud SQL for SQL Server.
## Attributes
* `domain` (*type:* `String.t`, *default:* `nil`) - The name of the domain (e.g., mydomain.com).
* `kind` (*type:* `String.t`, *default:* `nil`) - This is always sql#activeDirectoryConfig.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:domain => String.t() | nil,
:kind => String.t() | nil
}
field(:domain)
field(:kind)
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1.Model.SqlActiveDirectoryConfig do
def decode(value, options) do
GoogleApi.SQLAdmin.V1.Model.SqlActiveDirectoryConfig.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1.Model.SqlActiveDirectoryConfig do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 32.66
| 100
| 0.723821
|
93aee157c85a9d0d5c8e3988ddc0c7cc503529a2
| 7,656
|
ex
|
Elixir
|
lib/logi/channel.ex
|
sile/logi_ex
|
6af6a28cd73faa02e12059645405d85597d4d6a7
|
[
"MIT"
] | 1
|
2016-11-29T08:43:21.000Z
|
2016-11-29T08:43:21.000Z
|
lib/logi/channel.ex
|
sile/logi_ex
|
6af6a28cd73faa02e12059645405d85597d4d6a7
|
[
"MIT"
] | null | null | null |
lib/logi/channel.ex
|
sile/logi_ex
|
6af6a28cd73faa02e12059645405d85597d4d6a7
|
[
"MIT"
] | null | null | null |
defmodule Logi.Channel do
@moduledoc """
Log Message Channels.
A channel (logically) receives log messages from loggers and delivers the messages to installed sinks.
## Examples
```elixir
# CREATE CHANNEL
iex> :ok = Logi.Channel.create :sample_log
iex> Logi.Channel.which_channels
[:sample_log, :logi_default_log] # 'logi_default_log' is created automatically when 'logi' application was started
# INSTALL SINK
iex> write_fun = fn (_, format, data) -> :io.format("[my_sink] " <> format <> "\\n", data) end
iex> sink = Logi.BuiltIn.Sink.Fun.new :sample_sink, write_fun
iex> {:ok, _} = Logi.Channel.install_sink :sample_log, sink, :info # Installs `sink` with `:info` level
iex> Logi.Channel.which_sinks :sample_log
[:sample_sink]
# OUTPUT LOG MESSAGE
iex> require Logi
iex> Logi.debug "hello world", [], [logger: :sample_log]
# The message is not emitted (the severity is too low).
iex> Logi.info "hello world", [], [logger: :sample_log]
#OUTPUT# [my_sink] hello world
iex> Logi.alert "hello world", [], [logger: :sample_log]
#OUTPUT# [my_sink] hello world
iex> Logi.info "hello world" # If `logger` option is omitted, the default channel will be used
# The message is not emitted (no sinks are installed to the default channel).
```
"""
@typedoc "The identifier of a channel"
@type id :: atom
@typedoc """
Options for `install_sink_opt/3`.
## if_exists
- The confliction handling policy.
- If a sink with the same identifier already exists,
- `:error`: the function returns an error `{:error, {:already_installed, existing_sink}}`.
- `:ignore`: the new sink is ignored. Then the function returns `{:ok, existing_sink}`.
- `:supersede`: the new sink supersedes it. Then the function returns `{:ok, old_sink}`.
- Default: `:supersede`
"""
@type install_sink_options :: [
{:if_exists, :error | :ignore | :supersede}
]
@typedoc "The information of an installed sink."
@type installed_sink :: %{
:sink => Logi.Sink.sink,
:condition => Logi.Confliction.condition,
:sink_sup => Logi.SinkProc.sink_sup,
:writer => Logi.SinkWriter.writer | :undefined
}
@doc """
The default channel.
This channel is created automatically when `logi_ex` application was started.
NOTE: The default channel ID is the same as the default logger ID (`Logi.default_logger/0`).
"""
@spec default_channel :: id
def default_channel do
:logi_channel.default_channel
end
@doc """
Creates a new channel.
If the channel already exists, nothing happens.
If there exists a process or a ETS table with the same name as `channel`, the function crashes.
"""
@spec create(id) :: :ok
def create(channel) do
:logi_channel.create channel
end
@doc """
Deletes a channel.
If the channel does not exists, it is silently ignored.
"""
@spec delete(id) :: :ok
def delete(channel) do
:logi_channel.delete channel
end
@doc "Returns a list of all existing channels."
@spec which_channels :: [id]
def which_channels do
:logi_channel.which_channels
end
@doc "Equivalent to `Logi.Channel.install_sink Logi.Channel.default_channel, sink, condition`."
@spec install_sink(Logi.Sink.sink, Logi.Condition.condition) :: {:ok, old} | {:error, reason} when
old: :undefined | installed_sink,
reason: {:cannot_start, any}
def install_sink(sink, condition) do
:logi_channel.install_sink sink, condition
end
@doc "Equivalent to `Logi.Channel.install_sink_opt channel, sink, condition, []`."
@spec install_sink(id, Logi.Sink.sink, Logi.Condition.condition) :: {:ok, old} | {:error, reason} when
old: :undefined | installed_sink,
reason: {:cannot_start, any}
def install_sink(channel, sink, condition) do
:logi_channel.install_sink channel, sink, condition
end
@doc "Equivalent to `Logi.Channel.install_sink_opt Logi.Channel.default_channel, sink, condition, options`."
@spec install_sink_opt(Logi.Sink.sink, Logi.Condition.condition, install_sink_options) :: {:ok, old} | {:error, reason} when
old: :undefined | installed_sink,
reason: {:cannot_start, any} | {:already_installed, installed_sink}
def install_sink_opt(sink, condition, options) do
:logi_channel.install_sink_opt sink, condition, options
end
@doc """
Installs `sink`.
If failed to start a sink process specified by `logi_sink:get_spec(sink)`,
the function returns `{:cannot_start, failure_reason}`.
If there does not exist a sink which has the same identifier with a new one,
the function returns `{:ok, :undefined}`.
Otherwise the result value depends on the value of the `:if_exists` option
(see the description of `t:install_sink_options/0` for details).
"""
@spec install_sink_opt(id, Logi.Sink.sink, Logi.Condition.condition, install_sink_options) :: {:ok, old} | {:error, reason} when
old: :undefined | installed_sink,
reason: {:cannot_start, any} | {:already_installed, installed_sink}
def install_sink_opt(channel, sink, condition, options) do
:logi_channel.install_sink_opt channel, sink, condition, options
end
@doc "Equivalent to `Logi.Channel.uninstall_sink Logi.Channel.default_channel, sink_id`."
@spec uninstall_sink(Logi.Sink.id) :: {:ok, installed_sink} | :error
def uninstall_sink(sink_id) do
:logi_channel.uninstall_sink sink_id
end
@doc """
Uninstalls the sink which has the identifier `sink_id` from `channel`.
The function returns `{:ok, sink}` if the specified sink exists in the channel, `:error` otherwise.
"""
@spec uninstall_sink(id, Logi.Sink.id) :: {:ok, installed_sink} | :error
def uninstall_sink(channel, sink_id) do
:logi_channel.uninstall_sink channel, sink_id
end
@doc "Equivalent to `Logi.Channel.set_sink_condition Logi.Channel.default_channel, sink_id, condition`."
@spec set_sink_condition(Logi.Sink.id, Logi.Condition.condition) :: {:ok, old} | :error when
old: Logi.Condition.condition
def set_sink_condition(sink_id, condition) do
:logi_channel.set_sink_condition sink_id, condition
end
@doc """
Sets the applicable condition of the `sink_id`.
The function returns `{:ok, old}` if the specified sink exists in the channel, `:error` otherwise.
"""
@spec set_sink_condition(id, Logi.Sink.id, Logi.Condition.condition) :: {:ok, old} | :error when
old: Logi.Condition.condition
def set_sink_condition(channel, sink_id, condition) do
:logi_channel.set_sink_condition channel, sink_id, condition
end
@doc "Equivalent to `Logi.Channel.find_sink Logi.Channel.id, sink_id`."
@spec find_sink(Logi.Sink.id) :: {:ok, installed_sink} | :error
def find_sink(sink_id) do
:logi_channel.find_sink sink_id
end
@doc """
Searches for `sink_id` in `channel`.
The function returns `{:ok, sink}`, or `:error` if `sink_id` is not present.
"""
@spec find_sink(id, Logi.Sink.id) :: {:ok, installed_sink} | :error
def find_sink(channel_id, sink_id) do
:logi_channel.find_sink channel_id, sink_id
end
@doc "Returns a list of installed sinks."
@spec which_sinks(id) :: [Logi.Sink.id]
def which_sinks(channel \\ Logi.Channel.default_channel) do
:logi_channel.which_sinks channel
end
@doc "Equivalent to `Logi.Channel.whereis_sink_proc Logi.Channel.default_channel, path`."
@spec whereis_sink_proc([Logi.Sink.id]) :: pid | :undefined
def whereis_sink_proc(path) do
:logi_channel.whereis_sink_proc path
end
@doc "Returns the pid associated with `path`."
@spec whereis_sink_proc(id, [Logi.Sink.id]) :: pid | :undefined
def whereis_sink_proc(channel, path) do
:logi_channel.whereis_sink_proc channel, path
end
end
| 35.444444
| 130
| 0.713166
|
93af02576db2c877b53f984cb32c030ac1a95dbe
| 1,212
|
ex
|
Elixir
|
lib/open_pantry/web/views/shared_view.ex
|
neilfulwiler/open_pantry
|
4b705f2282c7b2365a784503c9f1bdd34c741798
|
[
"MIT"
] | 41
|
2017-10-04T00:33:46.000Z
|
2021-04-09T01:33:34.000Z
|
lib/open_pantry/web/views/shared_view.ex
|
openpantry/open_pantry
|
27d898a65dd6f44b325f48d41bc448bb486d9c6f
|
[
"MIT"
] | 74
|
2017-09-20T03:36:17.000Z
|
2018-11-20T20:46:16.000Z
|
lib/open_pantry/web/views/shared_view.ex
|
neilfulwiler/open_pantry
|
4b705f2282c7b2365a784503c9f1bdd34c741798
|
[
"MIT"
] | 12
|
2017-10-04T10:02:49.000Z
|
2021-12-28T22:57:20.000Z
|
defmodule OpenPantry.Web.SharedView do
@default_max 999
use OpenPantry.Web, :view
import OpenPantry.Stock
import OpenPantry.Web.DisplayLogic
alias OpenPantry.StockDistribution
alias OpenPantry.UserOrder
alias OpenPantry.Image
@doc """
Renders a distribution line item for food selection index, or to send update to same page via channel
"""
def render_distribution(%StockDistribution{id: id}, conn) do
try do
render_to_string(__MODULE__, "distribution.html", distribution: StockDistribution.find(id, [:stock]), conn: conn)
rescue
Ecto.NoResultsError -> ""
end
end
@doc """
Renders a line for user order management index, or to send update to same page via channel
"""
def render_order_link(user_order = %UserOrder{id: _id}, conn) do
render_to_string(__MODULE__, "user_order_details.html", order: user_order, conn: conn)
end
def image_url(stock) do
Image.url({:stock_image, stock}, :thumb)
end
def max_allowed(stock, family_members) do
cond do
stock.max_per_package -> stock.max_per_package
stock.max_per_person -> stock.max_per_person * family_members
true -> @default_max
end
end
end
| 29.560976
| 119
| 0.712871
|
93af0fe993596dd5bf1ec94e4bd75ec0f2948eb1
| 445
|
ex
|
Elixir
|
lib/wise_homex/models/foreign_device.ex
|
wise-home/wise_homex
|
851f13191ed67acb1003888c12f4e6b71800d31b
|
[
"MIT"
] | 2
|
2019-03-14T09:09:14.000Z
|
2020-11-25T06:44:46.000Z
|
lib/wise_homex/models/foreign_device.ex
|
wise-home/wise_homex
|
851f13191ed67acb1003888c12f4e6b71800d31b
|
[
"MIT"
] | 139
|
2019-03-14T06:58:55.000Z
|
2022-03-29T12:28:09.000Z
|
lib/wise_homex/models/foreign_device.ex
|
wise-home/wise_homex
|
851f13191ed67acb1003888c12f4e6b71800d31b
|
[
"MIT"
] | 7
|
2021-04-09T13:55:45.000Z
|
2021-04-16T15:49:36.000Z
|
defmodule WiseHomex.ForeignDevice do
@moduledoc false
use WiseHomex.BaseModel
embedded_schema do
belongs_to :household, WiseHomex.Household
field :start_date, :date
field :end_date, :date
field :start_value, WiseHomex.QuantityType
field :end_value, WiseHomex.QuantityType
field :meter_type, :string
field :reading_type, :string
field :number, :string
field :hot_water_heat_meter, :boolean
end
end
| 22.25
| 46
| 0.739326
|
93af1085298c38499d38e56eee3c6c7d9736b933
| 8,633
|
exs
|
Elixir
|
apps/data/test/grapevine_data/authorizations_test.exs
|
sb8244/grapevine
|
effaaa01294d30114090c20f9cc40b8665d834f2
|
[
"MIT"
] | 107
|
2018-10-05T18:20:32.000Z
|
2022-02-28T04:02:50.000Z
|
apps/data/test/grapevine_data/authorizations_test.exs
|
sb8244/grapevine
|
effaaa01294d30114090c20f9cc40b8665d834f2
|
[
"MIT"
] | 33
|
2018-10-05T14:11:18.000Z
|
2022-02-10T22:19:18.000Z
|
apps/data/test/grapevine_data/authorizations_test.exs
|
sb8244/grapevine
|
effaaa01294d30114090c20f9cc40b8665d834f2
|
[
"MIT"
] | 18
|
2019-02-03T03:08:20.000Z
|
2021-12-28T04:29:36.000Z
|
defmodule GrapevineData.AuthorizationsTest do
use Grapevine.DataCase
alias GrapevineData.Authorizations
alias GrapevineData.Authorizations.AccessToken
alias GrapevineData.Authorizations.Authorization
alias GrapevineData.Games
describe "starting to authenticate" do
setup [:with_user, :with_game]
test "successful", %{user: user, game: game} do
{:ok, authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile"
})
assert authorization.state == "my+state"
assert authorization.redirect_uri == "https://example.com/oauth/callback"
assert authorization.scopes == ["profile"]
end
test "reuses authorizations if one is already active", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, new_authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile"
})
assert new_authorization.id == authorization.id
end
test "regenerates the authorization's code on reuse", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, _authorization} = Authorizations.mark_as_used(authorization)
{:ok, new_authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile"
})
assert new_authorization.code
end
test "deactivates all previous tokens on reuse", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, access_token} = Authorizations.create_token(game.client_id, authorization.redirect_uri, authorization.code)
{:ok, _new_authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile"
})
access_token = Repo.get(AccessToken, access_token.id)
refute access_token.active
end
test "does not reuse if scopes are different", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, new_authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile email"
})
assert new_authorization.id != authorization.id
end
test "invalid if redirect uri does not match a known uri", %{user: user, game: game} do
{:error, changeset} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callbacks",
"scope" => "profile"
})
assert changeset.errors[:redirect_uri]
end
test "missing params", %{user: user, game: game} do
{:error, changeset} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
})
assert changeset.errors[:redirect_uri]
end
end
describe "get a user's authorization" do
setup [:with_user, :with_game]
test "scoped to the user", %{user: user, game: game} do
authorization = create_authorization(user, game)
assert {:ok, _authorization} = Authorizations.get(user, authorization.id)
user = create_user(%{username: "other", email: "other@example.com"})
assert {:error, :not_found} = Authorizations.get(user, authorization.id)
end
end
describe "mark an authorization as allowed" do
setup [:with_user, :with_game]
test "sets authorization to active", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, authorization} = Authorizations.authorize(authorization)
assert authorization.active
end
end
describe "mark an authorization as denied" do
setup [:with_user, :with_game]
test "deletes the authorization", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, authorization} = Authorizations.deny(authorization)
assert {:error, :not_found} = Authorizations.get(user, authorization.id)
end
end
describe "redirect uris" do
test "authorized uri" do
authorization = %Authorization{
code: "code",
redirect_uri: "https://example.com/oauth/callback",
state: "my+state"
}
{:ok, uri} = Authorizations.authorized_redirect_uri(authorization)
assert uri == "https://example.com/oauth/callback?code=code&state=my%2Bstate"
end
test "denied uri" do
authorization = %Authorization{
code: "code",
redirect_uri: "https://example.com/oauth/callback",
state: "my+state"
}
{:ok, uri} = Authorizations.denied_redirect_uri(authorization)
assert uri == "https://example.com/oauth/callback?error=access_denied&state=my%2Bstate"
end
end
describe "create an access token for an authorization" do
setup [:with_user, :with_game]
test "create a token", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, access_token} = Authorizations.create_token(game.client_id, authorization.redirect_uri, authorization.code)
assert access_token.access_token
end
test "authorization code is good once", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:ok, _access_token} = Authorizations.create_token(game.client_id, authorization.redirect_uri, authorization.code)
{:error, :invalid_grant} = Authorizations.create_token(game.client_id, authorization.redirect_uri, authorization.code)
end
test "authorization is not active", %{user: user, game: game} do
{:ok, authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile",
})
{:error, :invalid_grant} = Authorizations.create_token(game.client_id, authorization.redirect_uri, authorization.code)
end
test "invalid client id", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:error, :invalid_grant} = Authorizations.create_token("invalid", authorization.redirect_uri, authorization.code)
end
test "invalid redirect uri", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:error, :invalid_grant} = Authorizations.create_token(game.client_id, "redirect", authorization.code)
end
test "invalid code", %{user: user, game: game} do
authorization = create_authorization(user, game)
{:error, :invalid_grant} = Authorizations.create_token(game.client_id, authorization.redirect_uri, "code")
end
end
describe "access token is valid" do
setup [:with_user, :with_game, :with_token]
test "is valid", %{access_token: access_token} do
assert Authorizations.valid_token?(access_token)
end
test "token is not active", %{access_token: access_token} do
access_token = %{access_token | active: false}
refute Authorizations.valid_token?(access_token)
end
test "after expiration", %{access_token: access_token} do
yesterday = Timex.now() |> Timex.shift(minutes: -70)
access_token = %{access_token | inserted_at: yesterday}
refute Authorizations.valid_token?(access_token)
end
test "authorization is not valid", %{authorization: authorization, access_token: access_token} do
authorization
|> Ecto.Changeset.change(%{active: false})
|> Repo.update!()
refute Authorizations.valid_token?(access_token)
end
end
def with_user(_) do
%{user: create_user()}
end
def with_game(_) do
game = create_game(create_user(%{username: "owner", email: "owner@example.com"}))
Games.create_redirect_uri(game, "https://example.com/oauth/callback")
game = Repo.preload(game, [:redirect_uris])
%{game: game}
end
def with_token(%{user: user, game: game}) do
{:ok, authorization} = Authorizations.start_auth(user, game, %{
"state" => "my+state",
"redirect_uri" => "https://example.com/oauth/callback",
"scope" => "profile",
})
{:ok, authorization} = Authorizations.authorize(authorization)
{:ok, access_token} = Authorizations.create_token(authorization)
%{authorization: authorization, access_token: access_token}
end
end
| 33.59144
| 124
| 0.670103
|
93af4b5e00fe4b3daa12e30ccc235537d1ecea7a
| 1,805
|
ex
|
Elixir
|
web/controllers/token_controller.ex
|
lyncms/lyn
|
ef825e7ff8df049a41f9a10685324079ebe116f9
|
[
"MIT"
] | 96
|
2016-02-26T20:20:33.000Z
|
2020-10-02T16:21:00.000Z
|
web/controllers/token_controller.ex
|
lyncms/lyn
|
ef825e7ff8df049a41f9a10685324079ebe116f9
|
[
"MIT"
] | 12
|
2016-02-27T16:23:55.000Z
|
2017-07-04T13:46:00.000Z
|
web/controllers/token_controller.ex
|
lyncms/lyn
|
ef825e7ff8df049a41f9a10685324079ebe116f9
|
[
"MIT"
] | 24
|
2016-03-10T23:55:33.000Z
|
2019-06-07T18:32:34.000Z
|
defmodule Lyn.TokenController do
use Lyn.Web, :controller
alias Lyn.GuardianToken
alias Guardian.Plug.EnsureAuthenticated
alias Guardian.Plug.EnsurePermissions
plug EnsureAuthenticated, handler: __MODULE__, typ: "token"
plug EnsurePermissions, [handler: __MODULE__, default: ~w(read_token)] when action in [:index]
plug EnsurePermissions, [handler: __MODULE__, default: ~w(revoke_token)] when action in [:delete]
def index(conn, _params, current_user, {:ok, %{"jti" => jti}}) do
render conn,
"index.html",
current_user: current_user,
tokens: GuardianToken.for_user(current_user),
current_jti: jti
end
def delete(conn, %{"id" => jti}, current_user, _claims) do
case Repo.get(GuardianToken, jti) do
nil -> could_not_delete(conn)
token ->
case Repo.delete(token) do
{:ok, _} ->
{:ok, sub} = Lyn.GuardianSerializer.for_token(current_user)
if sub == token.sub do
conn
|> put_flash(:info, "Done")
|> redirect(to: token_path(conn, :index))
else
could_not_delete(conn)
end
{:error, _} -> could_not_delete(conn)
end
end
end
defp could_not_delete(conn) do
conn
|> put_flash(:error, "Could not delete")
|> redirect(external: redirect_back(conn))
end
# The unauthenticated function is called because this controller has been
# specified as the handler.
def unauthenticated(conn, _params) do
conn
|> put_flash(:error, "Authentication required")
|> redirect(to: auth_path(conn, :login, :identity))
end
def unauthorized(conn, _params) do
conn
|> put_flash(:error, "Unauthorized")
|> redirect(external: redirect_back(conn))
end
end
| 30.59322
| 99
| 0.639335
|
93af847df074efc3edd9cb68235bc7353de2ced8
| 2,197
|
exs
|
Elixir
|
mix.exs
|
nyaray/custom_rpi3
|
59257f63c49930f76b69ba9722171eab373997cb
|
[
"Apache-2.0"
] | 1
|
2018-11-27T16:22:47.000Z
|
2018-11-27T16:22:47.000Z
|
mix.exs
|
nyaray/custom_rpi3
|
59257f63c49930f76b69ba9722171eab373997cb
|
[
"Apache-2.0"
] | null | null | null |
mix.exs
|
nyaray/custom_rpi3
|
59257f63c49930f76b69ba9722171eab373997cb
|
[
"Apache-2.0"
] | null | null | null |
defmodule CustomRpi3.MixProject do
use Mix.Project
@app :custom_rpi3
@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
System.put_env("MIX_TARGET", "custom_rpi3")
Application.start(:nerves_bootstrap)
Mix.Task.run("loadconfig", args)
end
defp nerves_package do
[
type: :system,
#artifact_sites: [
# {:github_releases, "nerves-project/#{@app}"}
#],
platform: Nerves.System.BR,
platform_config: [
defconfig: "nerves_defconfig"
],
checksum: package_files()
]
end
defp deps do
[
{:nerves, "~> 1.3", runtime: false},
{:nerves_system_br, "1.5.3", runtime: false},
{:nerves_toolchain_arm_unknown_linux_gnueabihf, "1.1.0", runtime: false},
{:nerves_system_linter, "~> 0.3.0", runtime: false},
{:ex_doc, "~> 0.18", only: [:dev, :test], runtime: false}
]
end
defp description do
"""
Nerves System - Raspberry Pi 3 B / B+
"""
end
defp package do
[
maintainers: ["Emilio Nyaray"],
files: package_files(),
licenses: ["Apache 2.0"],
links: %{"GitHub" => "https://github.com/nyaray/#{@app}"}
]
end
defp package_files do
[
"fwup_include",
"rootfs_overlay",
"CHANGELOG.md",
"cmdline.txt",
"config.txt",
"fwup-revert.conf",
"fwup.conf",
"LICENSE",
"linux-4.14.defconfig",
"mix.exs",
"nerves_defconfig",
"post-build.sh",
"post-createfs.sh",
"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
end
| 22.418367
| 79
| 0.568958
|
93af9b58e9ec36712396f0723daeb7fb5aea00e3
| 534
|
ex
|
Elixir
|
apps/authorizer/lib/policies/behaviour.ex
|
dcdourado/watcher_ex
|
ce80df81610a6e9b77612911aac2a6d6cf4de8d5
|
[
"Apache-2.0"
] | 9
|
2020-10-13T14:11:37.000Z
|
2021-08-12T18:40:08.000Z
|
apps/authorizer/lib/policies/behaviour.ex
|
dcdourado/watcher_ex
|
ce80df81610a6e9b77612911aac2a6d6cf4de8d5
|
[
"Apache-2.0"
] | 28
|
2020-10-04T14:43:48.000Z
|
2021-12-07T16:54:22.000Z
|
apps/authorizer/lib/policies/behaviour.ex
|
dcdourado/watcher_ex
|
ce80df81610a6e9b77612911aac2a6d6cf4de8d5
|
[
"Apache-2.0"
] | 3
|
2020-11-25T20:59:47.000Z
|
2021-08-30T10:36:58.000Z
|
defmodule Authorizer.Policies.Behaviour do
@moduledoc """
A policy is a set of verifications to make sure that a subject can do such action.
"""
@doc "Return the policy description"
@callback info() :: String.t()
@doc "Runs the input validations"
@callback validate(conn :: Plug.Conn.t()) :: {:ok, context :: map()} | {:error, atom()}
@doc "Runs the authorization policy"
@callback execute(context :: map(), opts :: Keyword.t()) ::
{:ok, shared_context :: Keyword.t()} | {:error, :unauthorized}
end
| 33.375
| 89
| 0.64794
|
93afab96c318283885c9531d023f6f99393b89db
| 3,678
|
ex
|
Elixir
|
lib/policr_mini/businesses/statistic_business.ex
|
skyplaying/policr-mini
|
ac265daa251fd76b770d0ce08c67075a6a57f796
|
[
"MIT"
] | null | null | null |
lib/policr_mini/businesses/statistic_business.ex
|
skyplaying/policr-mini
|
ac265daa251fd76b770d0ce08c67075a6a57f796
|
[
"MIT"
] | 2
|
2022-02-25T06:15:30.000Z
|
2022-02-25T06:15:33.000Z
|
lib/policr_mini/businesses/statistic_business.ex
|
skyplaying/policr-mini
|
ac265daa251fd76b770d0ce08c67075a6a57f796
|
[
"MIT"
] | null | null | null |
defmodule PolicrMini.StatisticBusiness do
@moduledoc """
用户业务功能的实现。
"""
use PolicrMini, business: PolicrMini.Schema.Statistic
import Ecto.Query, only: [from: 2]
@type status :: :passed | :timeout | :wronged | :other
@spec create(map) :: written_returns
def create(params) do
%Statistic{} |> Statistic.changeset(params) |> Repo.insert()
end
@spec update(Statistic.t(), map) :: written_returns
def update(statistic, params) do
statistic |> Statistic.changeset(params) |> Repo.update()
end
@day_seconds 3600 * 24
@zero_oclock ~T[00:00:00]
@spec find_today(integer, status) :: Statistic.t() | nil
def find_today(chat_id, status), do: find(chat_id, status, range: :today)
@spec find_yesterday(integer, status) :: Statistic.t() | nil
def find_yesterday(chat_id, status), do: find(chat_id, status, range: :yesterday)
@type dt_conts ::
[{:range, :today | :yesterday}] | [{:begin_at, DateTime.t()}, {:end_at, DateTime.t()}]
@spec find(integer, status, dt_conts) :: Statistic.t() | nil
defp find(chat_id, status, dt_conts) do
{begin_at, end_at} =
case Keyword.get(dt_conts, :range) do
:today -> today_datetimes()
:yesterday -> yesterday_datetimes()
nil -> {Keyword.get(dt_conts, :begin_at), Keyword.get(dt_conts, :end_at)}
end
from(
s in Statistic,
where:
s.chat_id == ^chat_id and
s.verification_status == ^status and
s.begin_at == ^begin_at and
s.end_at == ^end_at
)
|> Repo.one()
end
def fetch_today(chat_id, status, params) do
Repo.transaction(fn ->
case find_today(chat_id, status) || create(params) do
{:ok, statistic} ->
# 创建了一个新的
statistic
{:error, e} ->
# 创建时发生错误
Repo.rollback(e)
statistic ->
# 已存在
statistic
end
end)
end
@doc """
自增一个当天的统计。
"""
@spec increment_one(integer, String.t(), status) :: {:ok, Statistic.t()} | {:error, any}
def increment_one(chat_id, language_code, status) do
language_code = language_code || "unknown"
{begin_at, end_at} = today_datetimes()
params = %{
chat_id: chat_id,
verifications_count: 0,
languages_top: %{language_code => 0},
begin_at: begin_at,
end_at: end_at,
verification_status: status
}
fetch_one = fn -> fetch_today(chat_id, status, params) end
trans_fun = fn ->
trans_r = increment_trans(fetch_one, language_code)
case trans_r do
{:ok, r} -> r
e -> e
end
end
# TODO: 此处的事务需保证具有回滚的能力并能够返回错误结果。
Repo.transaction(trans_fun)
end
defp increment_trans(fetch_stat, language_code) do
case fetch_stat.() do
{:ok, stat} ->
verifications_count = stat.verifications_count + 1
languages_top =
if count = stat.languages_top[language_code] do
Map.put(stat.languages_top, language_code, count + 1)
else
Map.put(stat.languages_top, language_code, 1)
end
update(stat, %{verifications_count: verifications_count, languages_top: languages_top})
e ->
e
end
end
defp today_datetimes do
begin_at = DateTime.new!(Date.utc_today(), @zero_oclock, "Etc/UTC")
end_at = DateTime.add(begin_at, @day_seconds - 1, :second)
{begin_at, end_at}
end
defp yesterday_datetimes do
today_date = Date.utc_today()
yesterday_date = Date.add(today_date, -1)
begin_at = DateTime.new!(yesterday_date, @zero_oclock, "Etc/UTC")
end_at = DateTime.add(begin_at, @day_seconds - 1, :second)
{begin_at, end_at}
end
end
| 26.271429
| 96
| 0.62398
|
93afb112375ed009187d9eb5c3441d3609d1f776
| 1,803
|
exs
|
Elixir
|
clients/home_graph/mix.exs
|
kolorahl/elixir-google-api
|
46bec1e092eb84c6a79d06c72016cb1a13777fa6
|
[
"Apache-2.0"
] | null | null | null |
clients/home_graph/mix.exs
|
kolorahl/elixir-google-api
|
46bec1e092eb84c6a79d06c72016cb1a13777fa6
|
[
"Apache-2.0"
] | null | null | null |
clients/home_graph/mix.exs
|
kolorahl/elixir-google-api
|
46bec1e092eb84c6a79d06c72016cb1a13777fa6
|
[
"Apache-2.0"
] | null | null | null |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.HomeGraph.Mixfile do
use Mix.Project
@version "0.5.0"
def project() do
[
app: :google_api_home_graph,
version: @version,
elixir: "~> 1.6",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
description: description(),
package: package(),
deps: deps(),
source_url: "https://github.com/googleapis/elixir-google-api/tree/master/clients/home_graph"
]
end
def application() do
[extra_applications: [:logger]]
end
defp deps() do
[
{:google_gax, "~> 0.2"},
{:ex_doc, "~> 0.16", only: :dev}
]
end
defp description() do
"""
HomeGraph API client library.
"""
end
defp package() do
[
files: ["lib", "mix.exs", "README*", "LICENSE"],
maintainers: ["Jeff Ching", "Daniel Azuma"],
licenses: ["Apache 2.0"],
links: %{
"GitHub" => "https://github.com/googleapis/elixir-google-api/tree/master/clients/home_graph",
"Homepage" => "https://developers.google.com/actions/smarthome/create-app#request-sync"
}
]
end
end
| 26.910448
| 101
| 0.652801
|
93afb2f4c039900b629b414a0100bf01a04ada30
| 3,147
|
ex
|
Elixir
|
clients/reseller/lib/google_api/reseller/v1/model/subscription_plan.ex
|
linjunpop/elixir-google-api
|
444cb2b2fb02726894535461a474beddd8b86db4
|
[
"Apache-2.0"
] | null | null | null |
clients/reseller/lib/google_api/reseller/v1/model/subscription_plan.ex
|
linjunpop/elixir-google-api
|
444cb2b2fb02726894535461a474beddd8b86db4
|
[
"Apache-2.0"
] | null | null | null |
clients/reseller/lib/google_api/reseller/v1/model/subscription_plan.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.Reseller.V1.Model.SubscriptionPlan do
@moduledoc """
The plan property is required. In this version of the API, the G Suite plans are the flexible plan, annual commitment plan, and the 30-day free trial plan. For more information about the API\"s payment plans, see the API concepts.
## Attributes
- commitmentInterval (SubscriptionPlanCommitmentInterval): Defaults to: `null`.
- isCommitmentPlan (boolean()): The isCommitmentPlan property's boolean value identifies the plan as an annual commitment plan: - true — The subscription's plan is an annual commitment plan. - false — The plan is not an annual commitment plan. Defaults to: `null`.
- planName (String.t): The planName property is required. This is the name of the subscription's plan. For more information about the Google payment plans, see the API concepts. Possible values are: - ANNUAL_MONTHLY_PAY — The annual commitment plan with monthly payments. Caution: ANNUAL_MONTHLY_PAY is returned as ANNUAL in all API responses. - ANNUAL_YEARLY_PAY — The annual commitment plan with yearly payments - FLEXIBLE — The flexible plan - TRIAL — The 30-day free trial plan. A subscription in trial will be suspended after the 30th free day if no payment plan is assigned. Calling changePlan will assign a payment plan to a trial but will not activate the plan. A trial will automatically begin its assigned payment plan after its 30th free day or immediately after calling startPaidService. - FREE — The free plan is exclusive to the Cloud Identity SKU and does not incur any billing. Defaults to: `null`.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:commitmentInterval =>
GoogleApi.Reseller.V1.Model.SubscriptionPlanCommitmentInterval.t(),
:isCommitmentPlan => any(),
:planName => any()
}
field(:commitmentInterval, as: GoogleApi.Reseller.V1.Model.SubscriptionPlanCommitmentInterval)
field(:isCommitmentPlan)
field(:planName)
end
defimpl Poison.Decoder, for: GoogleApi.Reseller.V1.Model.SubscriptionPlan do
def decode(value, options) do
GoogleApi.Reseller.V1.Model.SubscriptionPlan.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Reseller.V1.Model.SubscriptionPlan do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 57.218182
| 932
| 0.760724
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.