hexsha
stringlengths 40
40
| size
int64 2
991k
| ext
stringclasses 2
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
208
| max_stars_repo_name
stringlengths 6
106
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
sequence | max_stars_count
int64 1
33.5k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
208
| max_issues_repo_name
stringlengths 6
106
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
sequence | max_issues_count
int64 1
16.3k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
208
| max_forks_repo_name
stringlengths 6
106
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
sequence | max_forks_count
int64 1
6.91k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 2
991k
| avg_line_length
float64 1
36k
| max_line_length
int64 1
977k
| alphanum_fraction
float64 0
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f74ce3a06dfac4b41dbb6b4b7f41049a16c5da7a | 722 | exs | Elixir | apps/load_tester/mix.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/load_tester/mix.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | apps/load_tester/mix.exs | jimpeebles/ewallet | ad4a9750ec8dc5adc4c0dfe6c22f0ef760825405 | [
"Apache-2.0"
] | null | null | null | defmodule LoadTester.MixProject do
use Mix.Project
def project do
[
app: :load_tester,
version: "1.2.0-dev",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.8",
start_permanent: Mix.env() == :prod,
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [:appsignal, :logger],
mod: {LoadTester.Application, []}
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:chaperon, "~> 0.2.3"},
{:deferred_config, "~> 0.1.0"},
]
end
end
| 21.235294 | 59 | 0.554017 |
f74cee83ef9d94b82353f64db791d56a1d62cedc | 5,632 | ex | Elixir | lib/mix/lib/mix/tasks/app.start.ex | lytedev/elixir | dc25bb8e1484e2328eef819402d268dec7bb908a | [
"Apache-2.0"
] | 1 | 2018-08-08T12:15:48.000Z | 2018-08-08T12:15:48.000Z | lib/mix/lib/mix/tasks/app.start.ex | lytedev/elixir | dc25bb8e1484e2328eef819402d268dec7bb908a | [
"Apache-2.0"
] | 1 | 2018-09-10T23:36:45.000Z | 2018-09-10T23:36:45.000Z | lib/mix/lib/mix/tasks/app.start.ex | lytedev/elixir | dc25bb8e1484e2328eef819402d268dec7bb908a | [
"Apache-2.0"
] | 1 | 2018-09-10T23:32:56.000Z | 2018-09-10T23:32:56.000Z | defmodule Mix.Tasks.App.Start do
use Mix.Task
# Do not mark this task as recursive as it is
# responsible for loading consolidated protocols.
@shortdoc "Starts all registered apps"
@moduledoc """
Starts all registered apps.
The application is started by default as temporary. In case
`:start_permanent` is set to `true` in your project configuration
or the `--permanent` flag is given, it is started as permanent,
which guarantees the node will shutdown if the application
crashes permanently.
## Configuration
* `:start_permanent` - the application and all of its children
applications are started in permanent mode. Defaults to `false`.
* `:consolidate_protocols` - when `true`, loads consolidated
protocols before start. The default value is `true`.
* `:elixir` - matches the current Elixir version against the
given requirement
## Command line options
* `--force` - forces compilation regardless of compilation times
* `--temporary` - starts the application as temporary
* `--permanent` - starts the application as permanent
* `--preload-modules` - preloads all modules defined in applications
* `--no-compile` - does not compile even if files require compilation
* `--no-protocols` - does not load consolidated protocols
* `--no-archives-check` - does not check archives
* `--no-deps-check` - does not check dependencies
* `--no-elixir-version-check` - does not check Elixir version
* `--no-start` - does not start applications after compilation
"""
@switches [
permanent: :boolean,
temporary: :boolean,
preload_modules: :boolean
]
def run(args) do
Mix.Project.get!()
config = Mix.Project.config()
{opts, _, _} = OptionParser.parse(args, switches: @switches)
Mix.Task.run("loadpaths", args)
unless "--no-compile" in args do
Mix.Project.compile(args, config)
end
unless "--no-protocols" in args do
path = Mix.Project.consolidation_path(config)
if config[:consolidate_protocols] && File.dir?(path) do
Code.prepend_path(path)
Enum.each(File.ls!(path), &load_protocol/1)
end
end
# Stop Logger when starting the application as it is
# up to the application to decide if it should be restarted
# or not.
#
# Mix should not depend directly on Logger so check that it's loaded.
logger = Process.whereis(Logger)
if logger do
Logger.App.stop()
end
if "--no-start" in args do
# Start Logger again if the application won't be starting it
if logger do
:ok = Logger.App.start()
end
else
start(Mix.Project.config(), opts)
# If there is a build path, we will let the application
# that owns the build path do the actual check
unless config[:build_path] do
loaded = loaded_applications(opts)
check_configured(loaded)
end
end
:ok
end
@doc false
def start(config, opts) do
apps =
cond do
Mix.Project.umbrella?(config) ->
for %Mix.Dep{app: app} <- Mix.Dep.Umbrella.cached(), do: app
app = config[:app] ->
[app]
true ->
[]
end
type = type(config, opts)
Enum.each(apps, &ensure_all_started(&1, type))
:ok
end
defp ensure_all_started(app, type) do
case Application.start(app, type) do
:ok ->
:ok
{:error, {:already_started, ^app}} ->
:ok
{:error, {:not_started, dep}} ->
:ok = ensure_all_started(dep, type)
ensure_all_started(app, type)
{:error, reason} when type == :permanent ->
# We need to stop immediately because application_controller is
# shutting down all applications. Since any work we do here is prone
# to race conditions as whatever process we call may no longer exist,
# we print a quick message and then block by calling `System.stop/1`.
Mix.shell().error(["** (Mix) ", could_not_start(app, reason)])
System.stop(1)
{:error, reason} ->
Mix.raise(could_not_start(app, reason))
end
end
defp could_not_start(app, reason) do
"Could not start application #{app}: " <> Application.format_error(reason)
end
@doc false
def type(config, opts) do
cond do
opts[:temporary] -> :temporary
opts[:permanent] -> :permanent
config[:start_permanent] -> :permanent
true -> :temporary
end
end
defp loaded_applications(opts) do
preload_modules? = opts[:preload_modules]
for {app, _, _} <- Application.loaded_applications() do
if modules = preload_modules? && Application.spec(app, :modules) do
:code.ensure_modules_loaded(modules)
end
app
end
end
defp check_configured(loaded) do
configured = Mix.ProjectStack.config_apps()
for app <- configured -- loaded, :code.lib_dir(app) == {:error, :bad_name} do
Mix.shell().error("""
You have configured application #{inspect(app)} in your configuration file,
but the application is not available.
This usually means one of:
1. You have not added the application as a dependency in a mix.exs file.
2. You are configuring an application that does not really exist.
Please ensure #{inspect(app)} exists or remove the configuration.
""")
end
:ok
end
defp load_protocol(file) do
case file do
"Elixir." <> _ ->
module = file |> Path.rootname() |> String.to_atom()
:code.purge(module)
:code.delete(module)
_ ->
:ok
end
end
end
| 27.881188 | 81 | 0.642045 |
f74d04dfb71c587480e07e8d8611cd13510e153b | 349 | ex | Elixir | lib/wait_for_it/application.ex | jvoegele/wait_for_it | a3e722dec8d7c291f545533d70d3dab774e7cb4f | [
"Apache-2.0"
] | 10 | 2018-02-19T12:18:44.000Z | 2020-12-03T22:55:48.000Z | lib/wait_for_it/application.ex | jvoegele/wait_for_it | a3e722dec8d7c291f545533d70d3dab774e7cb4f | [
"Apache-2.0"
] | 11 | 2017-08-30T23:43:06.000Z | 2019-04-05T20:15:42.000Z | lib/wait_for_it/application.ex | jvoegele/wait_for_it | a3e722dec8d7c291f545533d70d3dab774e7cb4f | [
"Apache-2.0"
] | 2 | 2017-08-30T13:11:29.000Z | 2017-12-28T20:26:42.000Z | defmodule WaitForIt.Application do
@moduledoc false
use Application
def start(_type, _args) do
children = [
{Registry, keys: :unique, name: WaitForIt.ConditionVariable.registry()},
WaitForIt.ConditionVariable.Supervisor
]
Supervisor.start_link(children, strategy: :one_for_one, name: WaitForIt.Supervisor)
end
end
| 23.266667 | 87 | 0.730659 |
f74d0faaa0cc6202dc06ad15bf109838c145acdf | 997 | exs | Elixir | mix.exs | szTheory/ecto_psql_extras | 05a2315b68f6c65e9c1e1cd36a06dc20c1556022 | [
"MIT"
] | null | null | null | mix.exs | szTheory/ecto_psql_extras | 05a2315b68f6c65e9c1e1cd36a06dc20c1556022 | [
"MIT"
] | null | null | null | mix.exs | szTheory/ecto_psql_extras | 05a2315b68f6c65e9c1e1cd36a06dc20c1556022 | [
"MIT"
] | null | null | null | defmodule EctoPSQLExtras.Mixfile do
use Mix.Project
@github_url "https://github.com/pawurb/ecto_psql_extras"
@version "0.4.1"
def project do
[
app: :ecto_psql_extras,
version: @version,
elixir: "~> 1.5",
escript: [main_module: EctoPSQLExtras],
description: description(),
deps: deps(),
package: package(),
docs: docs()
]
end
def deps do
[
{:table_rex, "~> 3.0.0"},
{:ecto_sql, "~> 3.4"},
{:postgrex, ">= 0.15.7"},
{:ex_doc, ">= 0.0.0", only: :dev, runtime: false}
]
end
defp description do
"""
Ecto PostgreSQL database performance insights. Locks, index usage, buffer cache hit ratios, vacuum stats and more.
"""
end
defp package do
[
maintainers: ["Pawel Urbanek"],
licenses: ["MIT"],
links: %{"GitHub" => @github_url}
]
end
defp docs do
[
main: "readme",
source_url: @github_url,
extras: ["README.md"]
]
end
end
| 19.94 | 118 | 0.561685 |
f74d32f331765292907e98c69bdbd68b42aa0240 | 18,806 | exs | Elixir | test/liberator/resource_defaults_test.exs | Cantido/liberator | fa958699ffc699a350a06dbcac6402b81208f282 | [
"MIT"
] | 36 | 2020-10-03T16:58:57.000Z | 2021-11-27T09:33:51.000Z | test/liberator/resource_defaults_test.exs | Cantido/liberator | fa958699ffc699a350a06dbcac6402b81208f282 | [
"MIT"
] | 23 | 2020-10-13T00:23:03.000Z | 2022-03-10T11:05:22.000Z | test/liberator/resource_defaults_test.exs | Cantido/liberator | fa958699ffc699a350a06dbcac6402b81208f282 | [
"MIT"
] | 1 | 2020-10-12T20:33:30.000Z | 2020-10-12T20:33:30.000Z | # SPDX-FileCopyrightText: 2021 Rosa Richter
#
# SPDX-License-Identifier: MIT
defmodule Liberator.ResourceDefaultsTest do
use ExUnit.Case, async: true
use Plug.Test
alias Liberator.HTTPDateTime
defmodule MyDefaultResource do
use Liberator.Resource
end
describe "method_allowed?/1" do
test "allows GET" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows HEAD" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows PUT" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows POST" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows DELETE" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows OPTIONS" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows TRACE" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "allows PATCH" do
assert MyDefaultResource.method_allowed?(conn(:get, "/"))
end
test "disallows asdf" do
refute MyDefaultResource.method_allowed?(conn(:asdf, "/"))
end
end
describe "is_options?" do
test "returns true for options type" do
assert MyDefaultResource.is_options?(conn(:options, "/"))
end
test "returns false for non-options type" do
refute MyDefaultResource.is_options?(conn(:get, "/"))
end
end
describe "method_put?" do
test "returns true for put type" do
assert MyDefaultResource.method_put?(conn(:put, "/"))
end
test "returns false for non-put type" do
refute MyDefaultResource.method_put?(conn(:get, "/"))
end
end
describe "method_post?" do
test "returns true for post type" do
assert MyDefaultResource.method_post?(conn(:post, "/"))
end
test "returns false for non-post type" do
refute MyDefaultResource.method_post?(conn(:get, "/"))
end
end
describe "method_delete?" do
test "returns true for delete type" do
assert MyDefaultResource.method_delete?(conn(:delete, "/"))
end
test "returns false for non-delete type" do
refute MyDefaultResource.method_delete?(conn(:get, "/"))
end
end
describe "method_patch?" do
test "returns true for patch type" do
assert MyDefaultResource.method_patch?(conn(:patch, "/"))
end
test "returns false for non-patch type" do
refute MyDefaultResource.method_patch?(conn(:get, "/"))
end
end
describe "body_exists?/1" do
test "returns true if the body is present" do
conn = conn(:get, "/", "test body") |> put_req_header("content-type", "text/plain")
assert MyDefaultResource.body_exists?(conn)
end
test "returns false if the body is not present" do
refute MyDefaultResource.body_exists?(conn(:get, "/"))
end
end
describe "accept_exists?/1" do
test "returns true if the accept header is present" do
conn =
conn(:get, "/")
|> put_req_header("accept", "application/json")
assert MyDefaultResource.accept_exists?(conn)
end
test "returns true if the accept header is */*" do
conn =
conn(:get, "/")
|> put_req_header("accept", "*/*")
assert MyDefaultResource.accept_exists?(conn)
end
test "returns false if the accept header is not present" do
refute MyDefaultResource.accept_exists?(conn(:get, "/"))
end
end
describe "accept_language_exists?/1" do
test "returns true if the accept-language header is present" do
conn =
conn(:get, "/")
|> put_req_header("accept-language", "en")
assert MyDefaultResource.accept_language_exists?(conn)
end
test "returns false if the accept-language header is not present" do
refute MyDefaultResource.accept_language_exists?(conn(:get, "/"))
end
end
defmodule LanguageAgnosticResource do
use Liberator.Resource
def available_languages(_conn), do: ["*"]
end
defmodule EnglishOnlyResource do
use Liberator.Resource
def available_languages(_conn), do: ["en"]
end
defmodule GermanOnlyResource do
use Liberator.Resource
def available_languages(_conn), do: ["de"]
end
describe "language_available?/1" do
test "returns the user's requested language if acceptable languges is *" do
conn =
conn(:get, "/")
|> put_req_header("accept-language", "de")
assert LanguageAgnosticResource.language_available?(conn) == %{language: "de"}
end
test "returns * if the user accepts * and only * is available" do
conn =
conn(:get, "/")
|> put_req_header("accept-language", "*")
assert LanguageAgnosticResource.language_available?(conn) == %{language: "*"}
end
test "returns false if acceptable languges is different from requested language" do
conn =
conn(:get, "/")
|> put_req_header("accept-language", "de")
refute EnglishOnlyResource.language_available?(conn)
end
test "returns a map containing the matching language" do
conn =
conn(:get, "/")
|> put_req_header("accept-language", "en")
assert EnglishOnlyResource.language_available?(conn) == %{language: "en"}
end
test "sets the Gettext locale to the given locale when it is available" do
# Using the GermanOnlyResource here just in case my default language is set to "en".
conn =
conn(:get, "/")
|> put_req_header("accept-language", "de")
GermanOnlyResource.language_available?(conn)
assert Gettext.get_locale() == "de"
end
test "does not set the Gettext locale if language is *" do
# The best I can do is assert that Gettext.get_locale() is "en",
# because it always returns the default locale if one isn't set
conn =
conn(:get, "/")
|> put_req_header("accept-language", "*")
LanguageAgnosticResource.language_available?(conn)
assert Gettext.get_locale() == "en"
end
end
describe "accept_charset_exists?/1" do
test "returns true if the accept-charset header is present" do
conn =
conn(:get, "/")
|> put_req_header("accept-charset", "en")
assert MyDefaultResource.accept_charset_exists?(conn)
end
test "returns false if the accept-charset header is not present" do
refute MyDefaultResource.accept_charset_exists?(conn(:get, "/"))
end
end
describe "accept_encoding_exists?/1" do
test "returns true if the accept-encoding header is present" do
conn =
conn(:get, "/")
|> put_req_header("accept-encoding", "en")
assert MyDefaultResource.accept_encoding_exists?(conn)
end
test "returns false if the accept-encoding header is not present" do
refute MyDefaultResource.accept_encoding_exists?(conn(:get, "/"))
end
end
defmodule Utf8EncodingAvailableResource do
use Liberator.Resource
def available_encodings(_), do: ["UTF-8"]
end
describe "encoding_available?/1" do
test "disallows UTF-16" do
refute Utf8EncodingAvailableResource.encoding_available?(
conn(:get, "/")
|> put_req_header("accept-encoding", "UTF-16")
)
end
test "returns a map containing the matching encoding" do
conn =
conn(:get, "/")
|> put_req_header("accept-encoding", "UTF-8")
assert Utf8EncodingAvailableResource.encoding_available?(conn) == %{encoding: "UTF-8"}
end
end
defmodule JsonMediaTypeAvailableResource do
use Liberator.Resource
def available_media_types(_), do: ["application/json", "text/html"]
end
describe "media_type_available?/1" do
test "disallows text/nonexistent-media-type" do
refute MyDefaultResource.media_type_available?(
conn(:get, "/")
|> put_req_header("accept", "text/nonexistent-media-type")
)
end
test "returns a map containing the matching media type" do
conn =
conn(:get, "/")
|> put_req_header("accept", "application/json")
assert JsonMediaTypeAvailableResource.media_type_available?(conn) == %{
media_type: "application/json"
}
end
test "returns a map containing the matching media type with the highest q" do
conn =
conn(:get, "/")
|> put_req_header("accept", "application/json;q=1.0, text/html;q=0.8")
assert JsonMediaTypeAvailableResource.media_type_available?(conn) == %{
media_type: "application/json"
}
end
test "returns a map containing the matching media type with the highest q even if they're out of order" do
conn =
conn(:get, "/")
|> put_req_header("accept", "text/html;q=0.8, application/json;q=1.0")
assert JsonMediaTypeAvailableResource.media_type_available?(conn) == %{
media_type: "application/json"
}
end
test "values with plus modifiers aren't the same" do
conn =
conn(:get, "/")
|> put_req_header("accept", "text/html;q=0.8, application/json+myspecialschema;q=1.0")
assert JsonMediaTypeAvailableResource.media_type_available?(conn) == %{
media_type: "text/html"
}
end
test "values with no q are the highest ranked" do
conn =
conn(:get, "/")
|> put_req_header("accept", "text/html;q=0.8, application/json")
assert JsonMediaTypeAvailableResource.media_type_available?(conn) == %{
media_type: "application/json"
}
end
end
defmodule CharsetUtf8AvailableResource do
use Liberator.Resource
def available_charsets(_), do: ["UTF-8"]
end
defmodule CharsetUtf16UnavailableResource do
use Liberator.Resource
def available_charsets(_), do: ["UTF-8"]
end
defmodule SetsCharsetResource do
use Liberator.Resource
def available_charsets(_), do: ["UTF-8"]
end
describe "charset_available?/1" do
test "returns true if charset is present in `available_charsets/1`" do
conn =
conn(:get, "/")
|> put_req_header("accept-charset", "UTF-8")
assert CharsetUtf8AvailableResource.charset_available?(conn)
end
test "returns trfalseue if charset is not present in `available_charsets/1`" do
conn =
conn(:get, "/")
|> put_req_header("accept-charset", "UTF-16")
refute CharsetUtf16UnavailableResource.charset_available?(conn)
end
test "returns a map containing the matching charset" do
conn =
conn(:get, "/")
|> put_req_header("accept-charset", "UTF-8")
assert SetsCharsetResource.charset_available?(conn) == %{charset: "UTF-8"}
end
end
describe "if_modified_since_exists?" do
test "returns true if the if-modified-since header is present" do
conn =
conn(:get, "/")
|> put_req_header("if-modified-since", "*")
assert MyDefaultResource.if_modified_since_exists?(conn)
end
test "returns false if the if-modified-since header is not present" do
refute MyDefaultResource.if_modified_since_exists?(conn(:get, "/"))
end
end
describe "modified_since?" do
test "returns true if last modification date is after modification_since" do
time_str =
Timex.Timezone.get("GMT")
|> Timex.now()
|> Timex.shift(days: -1)
|> HTTPDateTime.format!()
conn =
conn(:get, "/")
|> put_req_header("if-modified-since", time_str)
assert MyDefaultResource.modified_since?(conn)
end
test "returns false if last modification date is before modification_since" do
time_str =
Timex.Timezone.get("GMT")
|> Timex.now()
|> Timex.shift(days: 1)
|> HTTPDateTime.format!()
conn =
conn(:get, "/")
|> put_req_header("if-modified-since", time_str)
refute MyDefaultResource.modified_since?(conn)
end
end
describe "if_modified_since_valid_date?" do
test "returns true if if_modified_since header contains a valid date" do
time_str =
Timex.now()
|> HTTPDateTime.format!()
conn =
conn(:get, "/")
|> put_req_header("if-modified-since", time_str)
assert MyDefaultResource.if_modified_since_valid_date?(conn)
end
test "returns false if if_modified_since header contains an invalid date" do
conn =
conn(:get, "/")
|> put_req_header("if-modified-since", "asdf")
refute MyDefaultResource.if_modified_since_valid_date?(conn)
end
end
describe "if_unmodified_since_exists?" do
test "returns true if the if-unmodified-since header is present" do
conn =
conn(:get, "/")
|> put_req_header("if-unmodified-since", "*")
assert MyDefaultResource.if_unmodified_since_exists?(conn)
end
test "returns false if the if-unmodified-since header is not present" do
refute MyDefaultResource.if_unmodified_since_exists?(conn(:get, "/"))
end
end
describe "if_unmodified_since_valid_date?" do
test "returns true if if_unmodified_since header contains a valid date" do
time_str =
Timex.now()
|> HTTPDateTime.format!()
conn =
conn(:get, "/")
|> put_req_header("if-unmodified-since", time_str)
assert MyDefaultResource.if_unmodified_since_valid_date?(conn)
end
test "returns false if if_unmodified_since header contains an invalid date" do
conn =
conn(:get, "/")
|> put_req_header("if-unmodified-since", "asdf")
refute MyDefaultResource.if_unmodified_since_valid_date?(conn)
end
end
describe "unmodified_since?" do
test "returns false if last modification date is after modification_since" do
time_str =
Timex.Timezone.get("GMT")
|> Timex.now()
|> Timex.shift(days: -1)
|> HTTPDateTime.format!()
conn =
conn(:get, "/")
|> put_req_header("if-unmodified-since", time_str)
refute MyDefaultResource.unmodified_since?(conn)
end
test "returns true if last modification date is before modification_since" do
time_str =
Timex.Timezone.get("GMT")
|> Timex.now()
|> Timex.shift(days: 1)
|> HTTPDateTime.format!()
conn =
conn(:get, "/")
|> put_req_header("if-unmodified-since", time_str)
assert MyDefaultResource.unmodified_since?(conn)
end
end
describe "if_match_exists?" do
test "returns true if the if-match header is present" do
conn =
conn(:get, "/")
|> put_req_header("if-match", "*")
assert MyDefaultResource.if_match_exists?(conn)
end
test "returns false if the if-match header is not present" do
refute MyDefaultResource.if_match_exists?(conn(:get, "/"))
end
end
describe "if_match_star?" do
test "returns true if the if-match * header is present" do
conn =
conn(:get, "/")
|> put_req_header("if-match", "*")
assert MyDefaultResource.if_match_star?(conn)
end
test "returns false if the if-match * header is not present" do
conn =
conn(:get, "/")
|> put_req_header("if-match", "abcdefg")
refute MyDefaultResource.if_match_star?(conn)
end
end
describe "if_match_star_exists_for_missing?" do
test "returns true if the if-match * header is present" do
conn =
conn(:get, "/")
|> put_req_header("if-match", "*")
assert MyDefaultResource.if_match_star_exists_for_missing?(conn)
end
test "returns false if the if-match * header is not present" do
conn =
conn(:get, "/")
|> put_req_header("if-match", "abcdefg")
refute MyDefaultResource.if_match_star_exists_for_missing?(conn)
end
end
describe "if_none_match_exists?" do
test "returns true if the if-none-match header is present" do
conn =
conn(:get, "/")
|> put_req_header("if-none-match", "asdf")
assert MyDefaultResource.if_none_match_exists?(conn)
end
test "returns false if the if-none-match header is not present" do
refute MyDefaultResource.if_none_match_exists?(conn(:get, "/"))
end
end
describe "if_none_match_star?" do
test "returns true if the if-none-match header is *" do
conn =
conn(:get, "/")
|> put_req_header("if-none-match", "*")
assert MyDefaultResource.if_none_match_star?(conn)
end
test "returns false if the if-none-match header is not *" do
conn =
conn(:get, "/")
|> put_req_header("if-none-match", "asdf")
refute MyDefaultResource.if_none_match_star?(conn)
end
end
defmodule IfMatchModule do
use Liberator.Resource
def etag(_), do: "1"
end
describe "etag_matches_for_if_match?" do
test "returns false by default" do
refute MyDefaultResource.etag_matches_for_if_match?(conn(:get, "/"))
end
test "returns the etag if etag matches" do
conn =
conn(:get, "/")
|> put_req_header("if-match", "1")
assert IfMatchModule.etag_matches_for_if_match?(conn) == %{etag: "1"}
end
end
defmodule IfNoneMatchModule do
use Liberator.Resource
def etag(_), do: "1"
end
describe "etag_matches_for_if_none?" do
test "returns false by default" do
refute MyDefaultResource.etag_matches_for_if_none?(conn(:get, "/"))
end
test "returns the etag if etag matches" do
conn =
conn(:get, "/")
|> put_req_header("if-none-match", "1")
assert IfNoneMatchModule.etag_matches_for_if_none?(conn) == %{etag: "1"}
end
end
describe "post_to_missing?" do
test "returns true for POST" do
assert MyDefaultResource.post_to_missing?(conn(:post, "/"))
end
test "returns true for GET" do
refute MyDefaultResource.post_to_missing?(conn(:get, "/"))
end
end
describe "post_to_existing?" do
test "returns true for POST" do
assert MyDefaultResource.post_to_existing?(conn(:post, "/"))
end
test "returns true for GET" do
refute MyDefaultResource.post_to_existing?(conn(:get, "/"))
end
end
describe "post_to_gone?" do
test "returns true for POST" do
assert MyDefaultResource.post_to_gone?(conn(:post, "/"))
end
test "returns true for GET" do
refute MyDefaultResource.post_to_gone?(conn(:get, "/"))
end
end
describe "put_to_existing?" do
test "returns true for PUT" do
assert MyDefaultResource.put_to_existing?(conn(:put, "/"))
end
test "returns true for GET" do
refute MyDefaultResource.put_to_existing?(conn(:get, "/"))
end
end
end
| 27.860741 | 110 | 0.644528 |
f74d3419de0030de5b932ffbd9aad19b85479817 | 3,586 | ex | Elixir | lib/cache/cache.ex | madnificent/mu-elixir-cache | c86717907b113d593966b3b2e1e86a8e530fe0bb | [
"MIT"
] | null | null | null | lib/cache/cache.ex | madnificent/mu-elixir-cache | c86717907b113d593966b3b2e1e86a8e530fe0bb | [
"MIT"
] | null | null | null | lib/cache/cache.ex | madnificent/mu-elixir-cache | c86717907b113d593966b3b2e1e86a8e530fe0bb | [
"MIT"
] | null | null | null | defmodule UsePlugProxy.Cache do
use GenServer
def find_cache( { _method, _full_path, _get_params, _allowed_groups } = key ) do
case GenServer.call( __MODULE__, { :find_cache, key } ) do
{ :ok, response } -> response
{ :not_found } -> nil
end
end
def store( { _method, _full_path, _get_params, _allowed_groups } = key, response ) do
# IO.puts "Going to store new content"
# IO.inspect( key, label: "Key to store under" )
# IO.inspect( response, label: "Response to save" )
GenServer.call( __MODULE__, {:store, key, response } )
end
def clear_keys( keys ) do
GenServer.call( __MODULE__, {:clear_keys, keys} )
end
###
# GenServer API
###
def start_link(_) do
GenServer.start_link( __MODULE__, [%{cache: %{}, caches_by_key: %{}}], name: __MODULE__ )
end
def init(_) do
{:ok, %{cache: %{}, caches_by_key: %{}}}
end
def handle_call({:find_cache, key}, _from, state) do
if has_key? state, key do
{ :reply, { :ok, Map.get( state.cache, key ) }, state }
else
{ :reply, { :not_found }, state }
end
end
def handle_call({:store, request_key, response}, _from, state) do
# IO.inspect( request_key, label: "Request key" )
# IO.inspect( response, label: "Response" )
%{ cache_keys: cache_keys, clear_keys: clear_keys } = response
# IO.inspect { :cache_keys, cache_keys }
# IO.inspect { :clear_keys, clear_keys }
state =
state
# update state for clear_keys
|> clear_keys!( clear_keys )
# IO.puts "Executed clear keys"
if cache_keys == [] do
{:reply, :ok, state }
else
# IO.puts "Caching request"
# update state for new cache
state =
state
|> add_cache_key_dependency!( cache_keys, request_key )
|> add_cached_value!( request_key, response )
{:reply, :ok, state }
end
end
def handle_call({:clear_keys, keys}, _from, state) do
{:reply, :ok, clear_keys!( state, keys )}
end
defp has_key?( state, key ) do
Map.has_key?( state.cache, key )
end
defp clear_keys!( state, [] ) do
state
end
defp clear_keys!( state, clear_keys ) do
# We have multiple clear_keys and need to update the state for it.
%{ cache: cache, caches_by_key: caches_by_key } = state
cache =
Enum.reduce( clear_keys, cache, fn (clear_key, cache) ->
keys_to_remove = Map.get( caches_by_key, clear_key, [] )
cache = Map.drop( cache, keys_to_remove )
cache
end )
caches_by_key =
Map.drop( caches_by_key, clear_keys )
%{ state |
cache: cache,
caches_by_key: caches_by_key }
end
defp add_cache_key_dependency!( state, [], _request_key ) do
state
end
defp add_cache_key_dependency!( state, cache_keys, request_key ) do
# For each cache_key, we need to see if the request_key is already
# in the cache_keys and add it if it is not there.
%{ caches_by_key: caches_by_key } = state
caches_by_key =
Enum.reduce( cache_keys, caches_by_key, fn (cache_key, caches_by_key) ->
relevant_keys = Map.get( caches_by_key, cache_key, [] )
if Enum.member?( relevant_keys, request_key ) do
caches_by_key
else
Map.put( caches_by_key, cache_key, [ request_key | relevant_keys ] )
end
end )
%{ state | caches_by_key: caches_by_key }
end
defp add_cached_value!( state, request_key, response ) do
%{ cache: cache } = state
cache = Map.put( cache, request_key, response )
%{ state | cache: cache }
end
end
| 27.166667 | 93 | 0.62744 |
f74d4de622c476690eab00cf5ef47589aee429a2 | 458 | ex | Elixir | lib/codes/codes_z21.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_z21.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | lib/codes/codes_z21.ex | badubizzle/icd_code | 4c625733f92b7b1d616e272abc3009bb8b916c0c | [
"Apache-2.0"
] | null | null | null | defmodule IcdCode.ICDCode.Codes_Z21 do
alias IcdCode.ICDCode
def _Z21 do
%ICDCode{full_code: "Z21",
category_code: "Z21",
short_code: "",
full_name: "Asymptomatic human immunodeficiency virus [HIV] infection status",
short_name: "Asymptomatic human immunodeficiency virus [HIV] infection status",
category_name: "Asymptomatic human immunodeficiency virus [HIV] infection status"
}
end
end
| 28.625 | 91 | 0.683406 |
f74d5dbee5e290e5b76054e2b2b800f846ebf874 | 493 | ex | Elixir | lib/tap_racer_web/views/error_view.ex | dtcristo/tap-racer | f66a3f4c728d547c85335aea7770e9b9ad857016 | [
"MIT"
] | 7 | 2016-06-04T09:24:24.000Z | 2017-09-03T16:26:21.000Z | lib/tap_racer_web/views/error_view.ex | dtcristo/tap-racer | f66a3f4c728d547c85335aea7770e9b9ad857016 | [
"MIT"
] | 10 | 2020-07-25T02:04:03.000Z | 2021-07-28T12:01:20.000Z | lib/tap_racer_web/views/error_view.ex | dtcristo/tap-racer | f66a3f4c728d547c85335aea7770e9b9ad857016 | [
"MIT"
] | 1 | 2019-05-17T03:37:43.000Z | 2019-05-17T03:37:43.000Z | defmodule TapRacerWeb.ErrorView do
use TapRacerWeb, :view
# If you want to customize a particular status code
# for a certain format, you may uncomment below.
# def render("500.html", _assigns) do
# "Internal Server Error"
# end
# By default, Phoenix returns the status message from
# the template name. For example, "404.html" becomes
# "Not Found".
def template_not_found(template, _assigns) do
Phoenix.Controller.status_message_from_template(template)
end
end
| 29 | 61 | 0.736308 |
f74d692ed168b48787d5a08403d406ba5f389e31 | 313 | ex | Elixir | apps/buzzcms_web/lib/buzzcms_web/resolvers/email_template.ex | buzzcms/buzzcms | 8ca8e6dea381350f94cc4a666448b5dba6676520 | [
"Apache-2.0"
] | null | null | null | apps/buzzcms_web/lib/buzzcms_web/resolvers/email_template.ex | buzzcms/buzzcms | 8ca8e6dea381350f94cc4a666448b5dba6676520 | [
"Apache-2.0"
] | 41 | 2020-02-12T07:53:14.000Z | 2020-03-30T02:18:14.000Z | apps/buzzcms_web/lib/buzzcms_web/resolvers/email_template.ex | buzzcms/buzzcms | 8ca8e6dea381350f94cc4a666448b5dba6676520 | [
"Apache-2.0"
] | null | null | null | defmodule BuzzcmsWeb.EmailTemplateResolver do
@schema Buzzcms.Schema.EmailTemplate
@filter_definition [
fields: [
{:code, FilterParser.StringFilterInput},
{:is_system, FilterParser.BooleanFilterInput},
{:subject, FilterParser.StringFilterInput}
]
]
use BuzzcmsWeb.Resolver
end
| 22.357143 | 52 | 0.731629 |
f74d85c6368fd88bdd768956747eedc92cbfeaff | 879 | exs | Elixir | test/test_helper.exs | carusso/codec | 45895a6aab4908e0c6528260849aeebf0cea8cae | [
"MIT"
] | 4 | 2018-02-13T13:39:07.000Z | 2021-01-24T22:11:42.000Z | test/test_helper.exs | carusso/codec | 45895a6aab4908e0c6528260849aeebf0cea8cae | [
"MIT"
] | null | null | null | test/test_helper.exs | carusso/codec | 45895a6aab4908e0c6528260849aeebf0cea8cae | [
"MIT"
] | null | null | null | ExUnit.start()
defmodule TestHelper do
use Bitwise
def crc16Lsb(input, crc \\ 0xFFFF)
def crc16Lsb(input, crc) when bit_size(input) == 0, do: (~~~crc) &&& 0xFFFF
def crc16Lsb(<< head :: size(8), tail :: binary >>, crc) do
crc = shifter(crc ^^^ head, 0)
crc16Lsb(tail, crc)
end
def crc32Lsb(input, crc \\ 0xFFFFFFFF)
def crc32Lsb(input, crc) when bit_size(input) == 0, do: (~~~crc) &&& 0xFFFFFFFF
def crc32Lsb(<< head :: size(8), tail :: binary >>, crc) do
crc = shifter(crc ^^^ head, 0)
crc32Lsb(tail, crc)
end
defp shifter(crc, count) do
crc = case crc &&& 0x0001 do
0 -> crc >>> 1
1 -> (crc >>> 1) ^^^ 0x8408;
end
case count do
7 ->
crc
_ ->
shifter(crc, count+1)
end
end
def sum(input) do
(for << byte :: 8 <- input >>, do: byte)
|> Enum.reduce(&(&1 + &2))
end
end
| 23.131579 | 81 | 0.550626 |
f74dbe0b86ad5809c368fb26133a7c1872f15bad | 4,704 | ex | Elixir | spec/data/apt/chef-integration-test2-1.0/debian/manpage.sgml.ex | ktpan/chef-play | 119798db7d1d25bb166bbce2f50e1399c0be1ae3 | [
"Apache-2.0"
] | null | null | null | spec/data/apt/chef-integration-test2-1.0/debian/manpage.sgml.ex | ktpan/chef-play | 119798db7d1d25bb166bbce2f50e1399c0be1ae3 | [
"Apache-2.0"
] | 1 | 2019-03-28T15:48:50.000Z | 2019-03-28T15:48:50.000Z | spec/data/apt/chef-integration-test2-1.0/debian/manpage.sgml.ex | ktpan/chef-play | 119798db7d1d25bb166bbce2f50e1399c0be1ae3 | [
"Apache-2.0"
] | null | null | null | <!doctype refentry PUBLIC "-//OASIS//DTD DocBook V4.1//EN" [
<!-- Process this file with docbook-to-man to generate an nroff manual
page: `docbook-to-man manpage.sgml > manpage.1'. You may view
the manual page with: `docbook-to-man manpage.sgml | nroff -man |
less'. A typical entry in a Makefile or Makefile.am is:
manpage.1: manpage.sgml
docbook-to-man $< > $@
The docbook-to-man binary is found in the docbook-to-man package.
Please remember that if you create the nroff version in one of the
debian/rules file targets (such as build), you will need to include
docbook-to-man in your Build-Depends control field.
-->
<!-- Fill in your name for FIRSTNAME and SURNAME. -->
<!ENTITY dhfirstname "<firstname>FIRSTNAME</firstname>">
<!ENTITY dhsurname "<surname>SURNAME</surname>">
<!-- Please adjust the date whenever revising the manpage. -->
<!ENTITY dhdate "<date>November 23, 2015</date>">
<!-- SECTION should be 1-8, maybe w/ subsection other parameters are
allowed: see man(7), man(1). -->
<!ENTITY dhsection "<manvolnum>SECTION</manvolnum>">
<!ENTITY dhemail "<email>[email protected]</email>">
<!ENTITY dhusername "Lamont Granquist">
<!ENTITY dhucpackage "<refentrytitle>CHEF-INTEGRATION-TEST2</refentrytitle>">
<!ENTITY dhpackage "chef-integration-test2">
<!ENTITY debian "<productname>Debian</productname>">
<!ENTITY gnu "<acronym>GNU</acronym>">
<!ENTITY gpl "&gnu; <acronym>GPL</acronym>">
]>
<refentry>
<refentryinfo>
<address>
&dhemail;
</address>
<author>
&dhfirstname;
&dhsurname;
</author>
<copyright>
<year>2003</year>
<holder>&dhusername;</holder>
</copyright>
&dhdate;
</refentryinfo>
<refmeta>
&dhucpackage;
&dhsection;
</refmeta>
<refnamediv>
<refname>&dhpackage;</refname>
<refpurpose>program to do something</refpurpose>
</refnamediv>
<refsynopsisdiv>
<cmdsynopsis>
<command>&dhpackage;</command>
<arg><option>-e <replaceable>this</replaceable></option></arg>
<arg><option>--example <replaceable>that</replaceable></option></arg>
</cmdsynopsis>
</refsynopsisdiv>
<refsect1>
<title>DESCRIPTION</title>
<para>This manual page documents briefly the
<command>&dhpackage;</command> and <command>bar</command>
commands.</para>
<para>This manual page was written for the &debian; distribution
because the original program does not have a manual page.
Instead, it has documentation in the &gnu;
<application>Info</application> format; see below.</para>
<para><command>&dhpackage;</command> is a program that...</para>
</refsect1>
<refsect1>
<title>OPTIONS</title>
<para>These programs follow the usual &gnu; command line syntax,
with long options starting with two dashes (`-'). A summary of
options is included below. For a complete description, see the
<application>Info</application> files.</para>
<variablelist>
<varlistentry>
<term><option>-h</option>
<option>--help</option>
</term>
<listitem>
<para>Show summary of options.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><option>-v</option>
<option>--version</option>
</term>
<listitem>
<para>Show version of program.</para>
</listitem>
</varlistentry>
</variablelist>
</refsect1>
<refsect1>
<title>SEE ALSO</title>
<para>bar (1), baz (1).</para>
<para>The programs are documented fully by <citetitle>The Rise and
Fall of a Fooish Bar</citetitle> available via the
<application>Info</application> system.</para>
</refsect1>
<refsect1>
<title>AUTHOR</title>
<para>This manual page was written by &dhusername; &dhemail; for
the &debian; system (and may be used by others). Permission is
granted to copy, distribute and/or modify this document under
the terms of the &gnu; General Public License, Version 2 any
later version published by the Free Software Foundation.
</para>
<para>
On Debian systems, the complete text of the GNU General Public
License can be found in /usr/share/common-licenses/GPL.
</para>
</refsect1>
</refentry>
<!-- Keep this comment at the end of the file
Local variables:
mode: sgml
sgml-omittag:t
sgml-shorttag:t
sgml-minimize-attributes:nil
sgml-always-quote-attributes:t
sgml-indent-step:2
sgml-indent-data:t
sgml-parent-document:nil
sgml-default-dtd-file:nil
sgml-exposed-tags:nil
sgml-local-catalogs:nil
sgml-local-ecat-files:nil
End:
-->
| 30.348387 | 79 | 0.660502 |
f74dd685684815b785240515afb264a87794d495 | 1,909 | exs | Elixir | clients/artifact_registry/mix.exs | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/artifact_registry/mix.exs | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | clients/artifact_registry/mix.exs | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.ArtifactRegistry.Mixfile do
use Mix.Project
@version "0.8.2"
def project() do
[
app: :google_api_artifact_registry,
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/artifact_registry"
]
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
"""
Artifact Registry API client library. Store and manage build artifacts in a scalable and integrated service built on Google infrastructure.
"""
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/artifact_registry",
"Homepage" => "https://cloud.google.com/artifacts/docs/"
}
]
end
end
| 28.492537 | 143 | 0.66527 |
f74de516f95e51ee952c03da5388deb91d204cc5 | 1,000 | ex | Elixir | lib/slurp/new_heads/timer.ex | AwaitFuture/slurp | f1d0fe5feb21f3135727c1516908e89130ea5801 | [
"MIT"
] | 20 | 2021-01-02T07:45:04.000Z | 2022-03-29T07:34:42.000Z | lib/slurp/new_heads/timer.ex | AwaitFuture/slurp | f1d0fe5feb21f3135727c1516908e89130ea5801 | [
"MIT"
] | 11 | 2021-01-25T13:10:34.000Z | 2021-09-23T05:34:08.000Z | lib/slurp/new_heads/timer.ex | AwaitFuture/slurp | f1d0fe5feb21f3135727c1516908e89130ea5801 | [
"MIT"
] | 1 | 2021-03-12T07:27:05.000Z | 2021-03-12T07:27:05.000Z | defmodule Slurp.NewHeads.Timer do
use GenServer
alias Slurp.{Blockchains, NewHeads}
defmodule State do
@type blockchain :: Blockchains.Blockchain.t()
@type t :: %State{
blockchain: blockchain
}
defstruct ~w[blockchain]a
end
@type blockchain :: Blockchains.Blockchain.t()
@type blockchain_id :: Blockchains.Blockchain.id()
@spec start_link(blockchain: blockchain) :: GenServer.on_start()
def start_link(blockchain: blockchain) do
name = process_name(blockchain.id)
state = %State{blockchain: blockchain}
GenServer.start_link(__MODULE__, state, name: name)
end
@spec process_name(blockchain_id) :: atom
def process_name(id), do: :"#{__MODULE__}_#{id}"
def init(state) do
Process.send(self(), :poll, [])
{:ok, state}
end
def handle_info(:poll, state) do
Process.send_after(self(), :poll, state.blockchain.poll_interval_ms)
NewHeads.NewHeadFetcher.check(state.blockchain.id)
{:noreply, state}
end
end
| 26.315789 | 72 | 0.692 |
f74df5ffc6621ba655895d3b319af177b69c6bb1 | 1,292 | ex | Elixir | lib/ucx_chat/release_tasks.ex | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 60 | 2017-05-09T19:08:26.000Z | 2021-01-20T11:09:42.000Z | lib/ucx_chat/release_tasks.ex | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 6 | 2017-05-10T15:43:16.000Z | 2020-07-15T07:14:41.000Z | lib/ucx_chat/release_tasks.ex | smpallen99/ucx_chat | 0dd98d0eb5e0537521844520ea2ba63a08fd3f19 | [
"MIT"
] | 10 | 2017-05-10T04:13:54.000Z | 2020-12-28T10:30:27.000Z | defmodule UcxChat.ReleaseTasks do
@start_apps [
:mariaex,
:ecto
]
@repos [
UcxChat.Repo
]
@app :ucx_chat
def seed do
IO.puts "Loading myapp.."
# Load the code for myapp, but don't start it
:ok = Application.load(@app)
IO.puts "Starting dependencies.."
# Start apps necessary for executing migrations
Enum.each(@start_apps, &Application.ensure_all_started/1)
# Start the Repo(s) for myapp
IO.puts "Starting repos.."
Enum.each(@repos, &(&1.start_link(pool_size: 1)))
# Run migrations
Enum.each(@repos, &run_migrations_for/1)
# Run the seed script if it exists
seed_script = seed_path(@app)
# Path.join([priv_dir(:ucx_chat), "repo", "seeds_prod.exs"])
if File.exists?(seed_script) do
IO.puts "Running seed script.."
Code.eval_file(seed_script)
end
# Signal shutdown
IO.puts "Success!"
:init.stop()
end
def priv_dir(app), do: "#{:code.priv_dir(app)}"
defp run_migrations_for(app) do
IO.puts "Running migrations for #{app}"
Ecto.Migrator.run(app, migrations_path(@app), :up, all: true)
end
defp migrations_path(app), do: Path.join([priv_dir(app), "repo", "migrations"])
defp seed_path(app), do: Path.join([priv_dir(app), "repo", "seeds_prod.exs"])
end
| 23.925926 | 81 | 0.652477 |
f74e1f411ce835b0b5bc4290c780dbe38816d6db | 1,049 | ex | Elixir | test/support/conn_case.ex | avinoth/spaces | 00bec5adf4568fef73b49e57808033295a837931 | [
"MIT"
] | 1 | 2016-09-13T10:40:53.000Z | 2016-09-13T10:40:53.000Z | test/support/conn_case.ex | avinoth/spaces | 00bec5adf4568fef73b49e57808033295a837931 | [
"MIT"
] | null | null | null | test/support/conn_case.ex | avinoth/spaces | 00bec5adf4568fef73b49e57808033295a837931 | [
"MIT"
] | null | null | null | defmodule Spaces.ConnCase do
@moduledoc """
This module defines the test case to be used by
tests that require setting up a connection.
Such tests rely on `Phoenix.ConnTest` and also
imports other functionality to make it easier
to build and query models.
Finally, if the test case interacts with the database,
it cannot be async. For this reason, every test runs
inside a transaction which is reset at the beginning
of the test unless the test case is marked as async.
"""
use ExUnit.CaseTemplate
using do
quote do
# Import conveniences for testing with connections
use Phoenix.ConnTest
alias Spaces.Repo
import Ecto
import Ecto.Changeset
import Ecto.Query, only: [from: 1, from: 2]
import Spaces.Router.Helpers
# The default endpoint for testing
@endpoint Spaces.Endpoint
end
end
setup tags do
unless tags[:async] do
Ecto.Adapters.SQL.restart_test_transaction(Spaces.Repo, [])
end
{:ok, conn: Phoenix.ConnTest.conn()}
end
end
| 24.395349 | 65 | 0.701621 |
f74e26d8c097100b8eed414a177343f81b9441b8 | 762 | exs | Elixir | priv/repo/migrations/20200716040244_create_users_auth_tables.exs | Fomich686/buy_the_food | ca4638a4efbb5f86347948ad07bcf7827f6523f9 | [
"Apache-2.0"
] | null | null | null | priv/repo/migrations/20200716040244_create_users_auth_tables.exs | Fomich686/buy_the_food | ca4638a4efbb5f86347948ad07bcf7827f6523f9 | [
"Apache-2.0"
] | null | null | null | priv/repo/migrations/20200716040244_create_users_auth_tables.exs | Fomich686/buy_the_food | ca4638a4efbb5f86347948ad07bcf7827f6523f9 | [
"Apache-2.0"
] | null | null | null | defmodule BuyTheFood.Repo.Migrations.CreateUsersAuthTables do
use Ecto.Migration
def change do
execute "CREATE EXTENSION IF NOT EXISTS citext", ""
create table(:users) do
add :email, :citext, null: false
add :hashed_password, :string, null: false
add :confirmed_at, :naive_datetime
timestamps()
end
create unique_index(:users, [:email])
create table(:users_tokens) do
add :user_id, references(:users, on_delete: :delete_all), null: false
add :token, :binary, null: false
add :context, :string, null: false
add :sent_to, :string
timestamps(updated_at: false)
end
create index(:users_tokens, [:user_id])
create unique_index(:users_tokens, [:context, :token])
end
end
| 27.214286 | 75 | 0.674541 |
f74e751d98cf48508b515c5397fc30796f0dc291 | 109 | ex | Elixir | ModulePlaygroun.ex | Dmdv/ElixirPlayground | 02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1 | [
"Apache-2.0"
] | null | null | null | ModulePlaygroun.ex | Dmdv/ElixirPlayground | 02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1 | [
"Apache-2.0"
] | null | null | null | ModulePlaygroun.ex | Dmdv/ElixirPlayground | 02d9e8a7fdd6e8742e200430debc9f0ec7fd28a1 | [
"Apache-2.0"
] | null | null | null | defmodule ModulePlayground do
import IO, only: [puts: 1]
def say do
puts "Hello"
end
end | 15.571429 | 30 | 0.614679 |
f74e91f5360a12c5f9bdffe325d2a5e75830d48b | 764 | ex | Elixir | test/support/test_utils.ex | kianmeng/control-node | 76f96e09772a36a2aed23a5f7a5c909c4fc7f5df | [
"MIT"
] | null | null | null | test/support/test_utils.ex | kianmeng/control-node | 76f96e09772a36a2aed23a5f7a5c909c4fc7f5df | [
"MIT"
] | null | null | null | test/support/test_utils.ex | kianmeng/control-node | 76f96e09772a36a2aed23a5f7a5c909c4fc7f5df | [
"MIT"
] | null | null | null | defmodule ControlNode.TestUtils do
require ExUnit.Assertions
alias ControlNode.Host.SSH
def ssh_fixture do
private_key_dir = with_fixture_path('host-vm/.ssh') |> :erlang.list_to_binary()
# on CI the env var SSH_HOST is set to openssh-server to connect
# to the service container running SSH server
host = System.get_env("SSH_HOST", "localhost")
%SSH{
host: host,
port: 2222,
user: "linuxserver.io",
private_key_dir: private_key_dir
}
end
defp with_fixture_path(path) do
Path.join([File.cwd!(), "test/fixture", path]) |> to_char_list()
end
def assert_until(fun) do
ExUnit.Assertions.assert(
Enum.any?(0..20, fn _i ->
:timer.sleep(100)
fun.()
end)
)
end
end
| 23.875 | 83 | 0.650524 |
f74eee75499285db9c8a0523384e178fa84ca823 | 624 | ex | Elixir | lib/bgg.ex | peralmq/bgg-elixir | 50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8 | [
"MIT"
] | 3 | 2016-01-19T14:40:39.000Z | 2020-07-07T16:37:55.000Z | lib/bgg.ex | peralmq/bgg-elixir | 50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8 | [
"MIT"
] | null | null | null | lib/bgg.ex | peralmq/bgg-elixir | 50ee895c27d7ffc8a38d4670a4fd34ba9bcd7da8 | [
"MIT"
] | null | null | null | defmodule BGG do
@moduledoc """
A BoardGameGeek (http://boardgamegeek.com/xmlapi/) client
"""
use Application
use HTTPoison.Base
def start(_type, _args) do
BGG.Supervisor.start_link
end
def process_url(path) do
url = "http://boardgamegeek.com/xmlapi/#{path}"
URI.encode(url)
end
def process_response_body(body) do
body |> Quinn.parse
end
def game(id) do
BGG.Game.game(id) |> BGG.Game.as_BGGGame
end
def games(ids) do
BGG.Game.games(ids) |> BGG.Game.as_BGGGames
end
def search(query) do
BGG.Search.search_games(query) |> BGG.Game.as_BGGGames
end
end
| 18.352941 | 60 | 0.671474 |
f74f1a6c3cd883229418541321789794b8cd5506 | 1,038 | ex | Elixir | lib/rtl_web/channels/user_socket.ex | topherhunt/reassembling-the-line | c6823b3394ee98d9b0149fa3d09448928ac5c0db | [
"MIT"
] | 1 | 2019-04-27T15:39:20.000Z | 2019-04-27T15:39:20.000Z | lib/rtl_web/channels/user_socket.ex | topherhunt/reassembling-the-line | c6823b3394ee98d9b0149fa3d09448928ac5c0db | [
"MIT"
] | 11 | 2020-07-16T11:40:53.000Z | 2021-08-16T07:03:33.000Z | lib/rtl_web/channels/user_socket.ex | topherhunt/reassembling-the-line | c6823b3394ee98d9b0149fa3d09448928ac5c0db | [
"MIT"
] | null | null | null | defmodule RTLWeb.UserSocket do
use Phoenix.Socket
## Channels
# channel "room:*", RTLWeb.RoomChannel
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "user_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# RTLWeb.Endpoint.broadcast("user_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 30.529412 | 83 | 0.690751 |
f74f2574a05b25678bc8339c0bc14757a51275c3 | 3,232 | exs | Elixir | backend/config/runtime.exs | makoto-engineer/kakeibo | d6882ccfa56d376a39dd307d28417d956ddc8584 | [
"MIT"
] | null | null | null | backend/config/runtime.exs | makoto-engineer/kakeibo | d6882ccfa56d376a39dd307d28417d956ddc8584 | [
"MIT"
] | null | null | null | backend/config/runtime.exs | makoto-engineer/kakeibo | d6882ccfa56d376a39dd307d28417d956ddc8584 | [
"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 :kakeibo, KakeiboWeb.Endpoint, server: true
end
if config_env() == :prod do
database_url =
System.get_env("DATABASE_URL") ||
raise """
environment variable DATABASE_URL is missing.
For example: ecto://USER:PASS@HOST/DATABASE
"""
maybe_ipv6 = if System.get_env("ECTO_IPV6"), do: [:inet6], else: []
config :kakeibo, Kakeibo.Repo,
# ssl: true,
url: database_url,
pool_size: String.to_integer(System.get_env("POOL_SIZE") || "10"),
socket_options: maybe_ipv6
# 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 :kakeibo, KakeiboWeb.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 :kakeibo, KakeiboWeb.Endpoint, server: true
#
# Then you can assemble a release by calling `mix release`.
# See `mix help release` for more information.
# ## Configuring the mailer
#
# In production you need to configure the mailer to use a different adapter.
# Also, you may need to configure the Swoosh API client of your choice if you
# are not using SMTP. Here is an example of the configuration:
#
# config :kakeibo, Kakeibo.Mailer,
# adapter: Swoosh.Adapters.Mailgun,
# api_key: System.get_env("MAILGUN_API_KEY"),
# domain: System.get_env("MAILGUN_DOMAIN")
#
# For this example you need include a HTTP client required by Swoosh API client.
# Swoosh supports Hackney and Finch out of the box:
#
# config :swoosh, :api_client, Swoosh.ApiClient.Hackney
#
# See https://hexdocs.pm/swoosh/Swoosh.html#module-installation for details.
end
| 37.581395 | 82 | 0.698639 |
f74f2787dc0b0a16cd65c731f4ebb273e24bedf8 | 1,579 | ex | Elixir | clients/big_query/lib/google_api/big_query/v2/model/category_count.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | null | null | null | clients/big_query/lib/google_api/big_query/v2/model/category_count.ex | MasashiYokota/elixir-google-api | 975dccbff395c16afcb62e7a8e411fbb58e9ab01 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/big_query/lib/google_api/big_query/v2/model/category_count.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.BigQuery.V2.Model.CategoryCount do
@moduledoc """
Represents the count of a single category within the cluster.
## Attributes
* `category` (*type:* `String.t`, *default:* `nil`) - The name of category.
* `count` (*type:* `String.t`, *default:* `nil`) - The count of training samples matching the category within the cluster.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:category => String.t(),
:count => String.t()
}
field(:category)
field(:count)
end
defimpl Poison.Decoder, for: GoogleApi.BigQuery.V2.Model.CategoryCount do
def decode(value, options) do
GoogleApi.BigQuery.V2.Model.CategoryCount.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.BigQuery.V2.Model.CategoryCount do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 31.58 | 126 | 0.721343 |
f74f5418e6d2183c77d0a8d94419191eee7ed1c9 | 17,653 | ex | Elixir | lib/logger/lib/logger.ex | pap/elixir | c803afe90c766663823c74397fb23ed40ec52c5b | [
"Apache-2.0"
] | null | null | null | lib/logger/lib/logger.ex | pap/elixir | c803afe90c766663823c74397fb23ed40ec52c5b | [
"Apache-2.0"
] | null | null | null | lib/logger/lib/logger.ex | pap/elixir | c803afe90c766663823c74397fb23ed40ec52c5b | [
"Apache-2.0"
] | null | null | null | defmodule Logger do
@moduledoc ~S"""
A logger for Elixir applications.
It includes many features:
* Provides debug, info, warn and error levels.
* Supports multiple backends which are automatically
supervised when plugged into Logger.
* Formats and truncates messages on the client
to avoid clogging Logger backends.
* Alternates between sync and async modes to remain
performant when required but also apply backpressure
when under stress.
* Wraps OTP's `error_logger` to prevent it from
overflowing.
## Levels
The supported levels are:
* `:debug` - for debug-related messages
* `:info` - for information of any kind
* `:warn` - for warnings
* `:error` - for errors
## Configuration
Logger supports a wide range of configurations.
This configuration is split in three categories:
* Application configuration - must be set before the Logger
application is started
* Runtime configuration - can be set before the Logger
application is started, but may be changed during runtime
* Error logger configuration - configuration for the
wrapper around OTP's `error_logger`
### Application configuration
The following configuration must be set via config files
before the Logger application is started.
* `:backends` - the backends to be used. Defaults to `[:console]`.
See the "Backends" section for more information.
* `:compile_time_purge_level` - purge all calls that have log level
lower than the configured value at compilation time. This means the
Logger call will be completely removed at compile time, accruing
no overhead at runtime. Defaults to `:debug` and only
applies to the `Logger.debug/2`, `Logger.info/2`, etc style of calls.
* `:compile_time_application` - sets the `:application` metadata value
to the configured value at compilation time. This configuration is
usually only useful for build tools to automatically add the
application to the metadata for `Logger.debug/2`, `Logger.info/2`, etc
style of calls.
For example, to configure the `:backends` and `compile_time_purge_level`
in a `config/config.exs` file:
config :logger,
backends: [:console],
compile_time_purge_level: :info
### Runtime Configuration
All configuration below can be set via config files but also
changed dynamically during runtime via `Logger.configure/1`.
* `:level` - the logging level. Attempting to log any message
with severity less than the configured level will simply
cause the message to be ignored. Keep in mind that each backend
may have its specific level, too.
* `:utc_log` - when `true`, uses UTC in logs. By default it uses
local time (i.e. it defaults to `false`).
* `:truncate` - the maximum message size to be logged. Defaults
to 8192 bytes. Note this configuration is approximate. Truncated
messages will have `" (truncated)"` at the end.
* `:sync_threshold` - if the Logger manager has more than
`sync_threshold` messages in its queue, Logger will change
to sync mode, to apply backpressure to the clients.
Logger will return to async mode once the number of messages
in the queue is reduced to `sync_threshold * 0.75` messages.
Defaults to 20 messages.
* `:translator_inspect_opts` - when translating OTP reports and
errors, the last message and state must be inspected in the
error reports. This configuration allow developers to change
how much and how the data should be inspected.
For example, to configure the `:level` and `:truncate` in a
`config/config.exs` file:
config :logger,
level: :warn,
truncate: 4096
### Error Logger configuration
The following configuration applies to the Logger wrapper around
Erlang's `error_logger`. All the configurations below must be set
before the Logger application starts.
* `:handle_otp_reports` - redirects OTP reports to Logger so
they are formatted in Elixir terms. This uninstalls Erlang's
logger that prints terms to terminal. Defaults to `true`.
* `:handle_sasl_reports` - redirects supervisor, crash and
progress reports to Logger so they are formatted in Elixir
terms. This uninstalls `sasl`'s logger that prints these
reports to the terminal. Defaults to `false`.
* `:discard_threshold_for_error_logger` - a value that, when
reached, triggers the error logger to discard messages. This
value must be a positive number that represents the maximum
number of messages accepted per second. Once above this
threshold, the `error_logger` enters discard mode for the
remainder of that second. Defaults to 500 messages.
For example, to configure Logger to redirect all `error_logger` messages
using a `config/config.exs` file:
config :logger,
handle_otp_reports: true,
handle_sasl_reports: true
Furthermore, Logger allows messages sent by Erlang's `error_logger`
to be translated into an Elixir format via translators. Translators
can be dynamically added at any time with the `add_translator/1`
and `remove_translator/1` APIs. Check `Logger.Translator` for more
information.
## Backends
Logger supports different backends where log messages are written to.
The available backends by default are:
* `:console` - logs messages to the console (enabled by default)
Developers may also implement their own backends, an option that
is explored with detail below.
The initial backends are loaded via the `:backends` configuration,
which must be set before the Logger application is started.
### Console backend
The console backend logs message to the console. It supports the
following options:
* `:level` - the level to be logged by this backend.
Note that messages are first filtered by the general
`:level` configuration in `:logger`
* `:format` - the format message used to print logs.
Defaults to: `"$time $metadata[$level] $levelpad$message\n"`
* `:metadata` - the metadata to be printed by `$metadata`.
Defaults to an empty list (no metadata)
* `:colors` - a keyword list of coloring options.
In addition to the keys provided by the user via `Logger.metadata/1`,
the following default keys are available in the `:metadata` list:
* `:application` - the current application
* `:module` - the current module
* `:function` - the current function
* `:file` - the current file
* `:line` - the current line
The supported keys in the `:colors` keyword list are:
* `:enabled` - boolean value that allows for switching the
coloring on and off. Defaults to: `IO.ANSI.enabled?`
* `:debug` - color for debug messages. Defaults to: `:cyan`
* `:info` - color for info messages. Defaults to: `:normal`
* `:warn` - color for warn messages. Defaults to: `:yellow`
* `:error` - color for error messages. Defaults to: `:red`
See the `IO.ANSI` module for a list of colors and attributes.
Here is an example of how to configure the `:console` backend in a
`config/config.exs` file:
config :logger, :console,
format: "\n$time $metadata[$level] $levelpad$message\n"
metadata: [:user_id]
You can read more about formatting in `Logger.Formatter`.
### Custom backends
Any developer can create their own backend for Logger.
Since Logger is an event manager powered by `GenEvent`,
writing a new backend is a matter of creating an event
handler, as described in the `GenEvent` module.
From now on, we will be using the term "event handler" to refer
to your custom backend, as we head into implementation details.
Once Logger starts, it installs all event handlers under
the `:backends` configuration into the Logger event manager.
The event manager and all added event handlers are
automatically supervised by Logger.
Once initialized, the handler should be designed to handle events
in the following format:
{level, group_leader,
{Logger, message, timestamp, metadata}}
The level is one of `:debug`, `:info`, `:warn` or `:error`,
as previously described, the group leader is the group
leader of the process who logged the message, followed by
a tuple starting with the atom `Logger`, the message as
chardata, the timestamp and a keyword list of metadata.
It is recommended that handlers ignore messages where
the group leader is in a different node than the one
the handler is installed.
Furthermore, backends can be configured via the
`configure_backend/2` function which requires event handlers
to handle calls of the following format:
{:configure, options}
where options is a keyword list. The result of the call is
the result returned by `configure_backend/2`. The recommended
return value for successful configuration is `:ok`.
It is recommended that backends support at least the following
configuration values:
* `level` - the logging level for that backend
* `format` - the logging format for that backend
* `metadata` - the metadata to include the backend
Check the implementation for `Logger.Backends.Console`, for
examples on how to handle the recommendations in this section
and how to process the existing options.
"""
@type backend :: GenEvent.handler
@type message :: IO.chardata | String.Chars.t
@type level :: :error | :info | :warn | :debug
@levels [:error, :info, :warn, :debug]
@metadata :logger_metadata
@compile {:inline, __metadata__: 0}
defp __metadata__ do
Process.get(@metadata) || {true, []}
end
@doc """
Adds the given keyword list to the current process metadata.
"""
def metadata(dict) do
{enabled, metadata} = __metadata__()
metadata =
Enum.reduce(dict, metadata, fn
{key, nil}, acc -> Keyword.delete(acc, key)
{key, val}, acc -> Keyword.put(acc, key, val)
end)
Process.put(@metadata, {enabled, metadata})
:ok
end
@doc """
Reads the current process metadata.
"""
def metadata() do
__metadata__() |> elem(1)
end
@doc """
Enables logging for the current process.
Currently the only accepted process is self().
"""
def enable(pid) when pid == self() do
Process.put(@metadata, {true, metadata()})
:ok
end
@doc """
Disables logging for the current process.
Currently the only accepted process is self().
"""
def disable(pid) when pid == self() do
Process.put(@metadata, {false, metadata()})
:ok
end
@doc """
Retrieves the Logger level.
The Logger level can be changed via `configure/1`.
"""
@spec level() :: level
def level() do
%{level: level} = Logger.Config.__data__
level
end
@doc """
Compares log levels.
Receives two log levels and compares the `left`
against `right` and returns `:lt`, `:eq` or `:gt`.
"""
@spec compare_levels(level, level) :: :lt | :eq | :gt
def compare_levels(level, level), do:
:eq
def compare_levels(left, right), do:
if(level_to_number(left) > level_to_number(right), do: :gt, else: :lt)
defp level_to_number(:debug), do: 0
defp level_to_number(:info), do: 1
defp level_to_number(:warn), do: 2
defp level_to_number(:error), do: 3
@doc """
Configures the logger.
See the "Runtime Configuration" section in `Logger` module
documentation for the available options.
"""
@valid_options [:compile_time_purge_level, :compile_time_application, :sync_threshold, :truncate, :level, :utc_log]
def configure(options) do
Logger.Config.configure(Keyword.take(options, @valid_options))
end
@doc """
Flushes the Logger.
This basically guarantees all messages sent to the
Logger prior to this call will be processed. This is useful
for testing and it should not be called in production code.
"""
@spec flush :: :ok
def flush do
_ = GenEvent.which_handlers(:error_logger)
_ = GenEvent.which_handlers(Logger)
:ok
end
@doc """
Adds a new backend.
## Options
* `:flush` - when `true`, guarantees all messages currently sent
to both Logger and Erlang's `error_logger` are processed before
the backend is added
"""
def add_backend(backend, opts \\ []) do
_ = if opts[:flush], do: GenEvent.which_handlers(:error_logger)
case Logger.Watcher.watch(Logger, Logger.Config.translate_backend(backend), backend) do
{:ok, _} = ok ->
Logger.Config.add_backend(backend)
ok
{:error, _} = error ->
error
end
end
@doc """
Removes a backend.
## Options
* `:flush` - when `true`, guarantees all messages currently sent
to both Logger and Erlang's `error_logger` are processed before
the backend is removed
"""
def remove_backend(backend, opts \\ []) do
_ = if opts[:flush], do: GenEvent.which_handlers(:error_logger)
Logger.Config.remove_backend(backend)
Logger.Watcher.unwatch(Logger, Logger.Config.translate_backend(backend))
end
@doc """
Adds a new translator.
"""
def add_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do
Logger.Config.add_translator(translator)
end
@doc """
Removes a translator.
"""
def remove_translator({mod, fun} = translator) when is_atom(mod) and is_atom(fun) do
Logger.Config.remove_translator(translator)
end
@doc """
Configures the given backend.
The backends needs to be started and running in order to
be configured at runtime.
"""
@spec configure_backend(backend, Keyword.t) :: term
def configure_backend(backend, options) when is_list(options) do
GenEvent.call(Logger, Logger.Config.translate_backend(backend), {:configure, options})
end
@doc """
Logs a message dynamically.
Use this function only when there is a need to
explicitly avoid embedding metadata.
"""
@spec bare_log(level, message | (() -> message), Keyword.t) ::
:ok | {:error, :noproc} | {:error, term}
def bare_log(level, chardata_or_fn, metadata \\ [])
when level in @levels and is_list(metadata) do
case __metadata__() do
{true, pdict} ->
%{mode: mode, truncate: truncate,
level: min_level, utc_log: utc_log?} = Logger.Config.__data__
if compare_levels(level, min_level) != :lt do
metadata = [pid: self()] ++ Keyword.merge(pdict, metadata)
tuple = {Logger, truncate(chardata_or_fn, truncate),
Logger.Utils.timestamp(utc_log?), metadata}
try do
notify(mode, {level, Process.group_leader(), tuple})
:ok
rescue
ArgumentError -> {:error, :noproc}
catch
:exit, reason -> {:error, reason}
end
else
:ok
end
{false, _} ->
:ok
end
end
@doc """
Logs a warning.
## Examples
Logger.warn "knob turned too far to the right"
Logger.warn fn -> "expensive to calculate warning" end
"""
defmacro warn(chardata_or_fn, metadata \\ []) do
maybe_log(:warn, chardata_or_fn, metadata, __CALLER__)
end
@doc """
Logs some info.
## Examples
Logger.info "mission accomplished"
Logger.info fn -> "expensive to calculate info" end
"""
defmacro info(chardata_or_fn, metadata \\ []) do
maybe_log(:info, chardata_or_fn, metadata, __CALLER__)
end
@doc """
Logs an error.
## Examples
Logger.error "oops"
Logger.error fn -> "expensive to calculate error" end
"""
defmacro error(chardata_or_fn, metadata \\ []) do
maybe_log(:error, chardata_or_fn, metadata, __CALLER__)
end
@doc """
Logs a debug message.
## Examples
Logger.debug "hello?"
Logger.debug fn -> "expensive to calculate debug" end
"""
defmacro debug(chardata_or_fn, metadata \\ []) do
maybe_log(:debug, chardata_or_fn, metadata, __CALLER__)
end
@doc """
Logs a message.
Developers should rather use the macros `Logger.debug/2`,
`Logger.warn/2`, `Logger.info/2` or `Logger.error/2` instead
of this macro as they can automatically eliminate
the Logger call altogether at compile time if desired.
"""
defmacro log(level, chardata_or_fn, metadata \\ []) do
macro_log(level, chardata_or_fn, metadata, __CALLER__)
end
defp macro_log(level, data, metadata, caller) do
%{module: module, function: fun, file: file, line: line} = caller
caller = [module: module, function: form_fa(fun), file: file, line: line]
if app = Application.get_env(:logger, :compile_time_application) do
caller = [application: app] ++ caller
end
quote do
Logger.bare_log(unquote(level), unquote(data), unquote(caller) ++ unquote(metadata))
end
end
defp maybe_log(level, data, metadata, caller) do
min_level = Application.get_env(:logger, :compile_time_purge_level, :debug)
if compare_levels(level, min_level) != :lt do
macro_log(level, data, metadata, caller)
else
:ok
end
end
defp truncate(data, n) when is_function(data, 0),
do: Logger.Utils.truncate(data.(), n)
defp truncate(data, n) when is_list(data) or is_binary(data),
do: Logger.Utils.truncate(data, n)
defp truncate(data, n),
do: Logger.Utils.truncate(to_string(data), n)
defp form_fa({name, arity}) do
Atom.to_string(name) <> "/" <> Integer.to_string(arity)
end
defp form_fa(nil), do: nil
defp notify(:sync, msg), do: GenEvent.sync_notify(Logger, msg)
defp notify(:async, msg), do: GenEvent.notify(Logger, msg)
end
| 30.970175 | 117 | 0.685436 |
f74f5824f4fe74e125e1824f4057da8fd5523d3f | 3,223 | ex | Elixir | clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/achievement_configuration.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/achievement_configuration.ex | kolorahl/elixir-google-api | 46bec1e092eb84c6a79d06c72016cb1a13777fa6 | [
"Apache-2.0"
] | null | null | null | clients/games_configuration/lib/google_api/games_configuration/v1configuration/model/achievement_configuration.ex | 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.GamesConfiguration.V1configuration.Model.AchievementConfiguration do
@moduledoc """
An achievement configuration resource.
## Attributes
* `achievementType` (*type:* `String.t`, *default:* `nil`) - The type of the achievement.
* `draft` (*type:* `GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationDetail.t`, *default:* `nil`) - The draft data of the achievement.
* `id` (*type:* `String.t`, *default:* `nil`) - The ID of the achievement.
* `initialState` (*type:* `String.t`, *default:* `nil`) - The initial state of the achievement.
* `kind` (*type:* `String.t`, *default:* `nil`) - Uniquely identifies the type of this resource. Value is always the fixed
string `gamesConfiguration#achievementConfiguration`.
* `published` (*type:* `GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationDetail.t`, *default:* `nil`) - The read-only published data of the achievement.
* `stepsToUnlock` (*type:* `integer()`, *default:* `nil`) - Steps to unlock. Only applicable to incremental achievements.
* `token` (*type:* `String.t`, *default:* `nil`) - The token for this resource.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:achievementType => String.t(),
:draft =>
GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationDetail.t(),
:id => String.t(),
:initialState => String.t(),
:kind => String.t(),
:published =>
GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationDetail.t(),
:stepsToUnlock => integer(),
:token => String.t()
}
field(:achievementType)
field(:draft,
as: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationDetail
)
field(:id)
field(:initialState)
field(:kind)
field(:published,
as: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfigurationDetail
)
field(:stepsToUnlock)
field(:token)
end
defimpl Poison.Decoder,
for: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfiguration do
def decode(value, options) do
GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfiguration.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.GamesConfiguration.V1configuration.Model.AchievementConfiguration do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 38.369048 | 182 | 0.714552 |
f74f61b65ab991dd2765f1ad660b840d83ca3289 | 10,951 | ex | Elixir | lib/aws/certificate_manager.ex | tylerpearson/aws-elixir | 09b7d3a3b9da1d775249cca291ab42ec5a081ff2 | [
"Apache-2.0"
] | null | null | null | lib/aws/certificate_manager.ex | tylerpearson/aws-elixir | 09b7d3a3b9da1d775249cca291ab42ec5a081ff2 | [
"Apache-2.0"
] | null | null | null | lib/aws/certificate_manager.ex | tylerpearson/aws-elixir | 09b7d3a3b9da1d775249cca291ab42ec5a081ff2 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/jkakar/aws-codegen for more details.
defmodule AWS.CertificateManager do
@moduledoc """
AWS Certificate Manager
Welcome to the AWS Certificate Manager (ACM) API documentation.
You can use ACM to manage SSL/TLS certificates for your AWS-based websites
and applications. For general information about using ACM, see the [ *AWS
Certificate Manager User Guide*
](http://docs.aws.amazon.com/acm/latest/userguide/).
"""
@doc """
Adds one or more tags to an ACM Certificate. Tags are labels that you can
use to identify and organize your AWS resources. Each tag consists of a
`key` and an optional `value`. You specify the certificate on input by its
Amazon Resource Name (ARN). You specify the tag by using a key-value pair.
You can apply a tag to just one certificate if you want to identify a
specific characteristic of that certificate, or you can apply the same tag
to multiple certificates if you want to filter for a common relationship
among those certificates. Similarly, you can apply the same tag to multiple
resources if you want to specify a relationship among those resources. For
example, you can add the same tag to an ACM Certificate and an Elastic Load
Balancing load balancer to indicate that they are both used by the same
website. For more information, see [Tagging ACM
Certificates](http://docs.aws.amazon.com/acm/latest/userguide/tags.html).
To remove one or more tags, use the `RemoveTagsFromCertificate` action. To
view all of the tags that have been applied to the certificate, use the
`ListTagsForCertificate` action.
"""
def add_tags_to_certificate(client, input, options \\ []) do
request(client, "AddTagsToCertificate", input, options)
end
@doc """
Deletes a certificate and its associated private key. If this action
succeeds, the certificate no longer appears in the list that can be
displayed by calling the `ListCertificates` action or be retrieved by
calling the `GetCertificate` action. The certificate will not be available
for use by AWS services integrated with ACM.
<note> You cannot delete an ACM Certificate that is being used by another
AWS service. To delete a certificate that is in use, the certificate
association must first be removed.
</note>
"""
def delete_certificate(client, input, options \\ []) do
request(client, "DeleteCertificate", input, options)
end
@doc """
Returns detailed metadata about the specified ACM Certificate.
"""
def describe_certificate(client, input, options \\ []) do
request(client, "DescribeCertificate", input, options)
end
@doc """
Retrieves a certificate specified by an ARN and its certificate chain . The
chain is an ordered list of certificates that contains the end entity
certificate, intermediate certificates of subordinate CAs, and the root
certificate in that order. The certificate and certificate chain are base64
encoded. If you want to decode the certificate to see the individual
fields, you can use OpenSSL.
"""
def get_certificate(client, input, options \\ []) do
request(client, "GetCertificate", input, options)
end
@doc """
Imports a certificate into AWS Certificate Manager (ACM) to use with
services that are integrated with ACM. Note that [integrated
services](http://docs.aws.amazon.com/acm/latest/userguide/acm-services.html)
allow only certificate types and keys they support to be associated with
their resources. Further, their support differs depending on whether the
certificate is imported into IAM or into ACM. For more information, see the
documentation for each service. For more information about importing
certificates into ACM, see [Importing
Certificates](http://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html)
in the *AWS Certificate Manager User Guide*.
<note> ACM does not provide [managed
renewal](http://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html)
for certificates that you import.
</note> Note the following guidelines when importing third party
certificates:
<ul> <li> You must enter the private key that matches the certificate you
are importing.
</li> <li> The private key must be unencrypted. You cannot import a private
key that is protected by a password or a passphrase.
</li> <li> If the certificate you are importing is not self-signed, you
must enter its certificate chain.
</li> <li> If a certificate chain is included, the issuer must be the
subject of one of the certificates in the chain.
</li> <li> The certificate, private key, and certificate chain must be
PEM-encoded.
</li> <li> The current time must be between the `Not Before` and `Not
After` certificate fields.
</li> <li> The `Issuer` field must not be empty.
</li> <li> The OCSP authority URL, if present, must not exceed 1000
characters.
</li> <li> To import a new certificate, omit the `CertificateArn` argument.
Include this argument only when you want to replace a previously imported
certificate.
</li> <li> When you import a certificate by using the CLI or one of the
SDKs, you must specify the certificate, the certificate chain, and the
private key by their file names preceded by `file://`. For example, you can
specify a certificate saved in the `C:\temp` folder as
`file://C:\temp\certificate_to_import.pem`. If you are making an HTTP or
HTTPS Query request, include these arguments as BLOBs.
</li> </ul> This operation returns the [Amazon Resource Name
(ARN)](http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html)
of the imported certificate.
"""
def import_certificate(client, input, options \\ []) do
request(client, "ImportCertificate", input, options)
end
@doc """
Retrieves a list of certificate ARNs and domain names. You can request that
only certificates that match a specific status be listed. You can also
filter by specific attributes of the certificate.
"""
def list_certificates(client, input, options \\ []) do
request(client, "ListCertificates", input, options)
end
@doc """
Lists the tags that have been applied to the ACM Certificate. Use the
certificate's Amazon Resource Name (ARN) to specify the certificate. To add
a tag to an ACM Certificate, use the `AddTagsToCertificate` action. To
delete a tag, use the `RemoveTagsFromCertificate` action.
"""
def list_tags_for_certificate(client, input, options \\ []) do
request(client, "ListTagsForCertificate", input, options)
end
@doc """
Remove one or more tags from an ACM Certificate. A tag consists of a
key-value pair. If you do not specify the value portion of the tag when
calling this function, the tag will be removed regardless of value. If you
specify a value, the tag is removed only if it is associated with the
specified value.
To add tags to a certificate, use the `AddTagsToCertificate` action. To
view all of the tags that have been applied to a specific ACM Certificate,
use the `ListTagsForCertificate` action.
"""
def remove_tags_from_certificate(client, input, options \\ []) do
request(client, "RemoveTagsFromCertificate", input, options)
end
@doc """
Requests an ACM Certificate for use with other AWS services. To request an
ACM Certificate, you must specify the fully qualified domain name (FQDN)
for your site in the `DomainName` parameter. You can also specify
additional FQDNs in the `SubjectAlternativeNames` parameter if users can
reach your site by using other names.
For each domain name you specify, email is sent to the domain owner to
request approval to issue the certificate. Email is sent to three
registered contact addresses in the WHOIS database and to five common
system administration addresses formed from the `DomainName` you enter or
the optional `ValidationDomain` parameter. For more information, see
[Validate Domain
Ownership](http://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate.html).
After receiving approval from the domain owner, the ACM Certificate is
issued. For more information, see the [AWS Certificate Manager User
Guide](http://docs.aws.amazon.com/acm/latest/userguide/).
"""
def request_certificate(client, input, options \\ []) do
request(client, "RequestCertificate", input, options)
end
@doc """
Resends the email that requests domain ownership validation. The domain
owner or an authorized representative must approve the ACM Certificate
before it can be issued. The certificate can be approved by clicking a link
in the mail to navigate to the Amazon certificate approval website and then
clicking **I Approve**. However, the validation email can be blocked by
spam filters. Therefore, if you do not receive the original mail, you can
request that the mail be resent within 72 hours of requesting the ACM
Certificate. If more than 72 hours have elapsed since your original request
or since your last attempt to resend validation mail, you must request a
new certificate. For more information about setting up your contact email
addresses, see [Configure Email for your
Domain](http://docs.aws.amazon.com/acm/latest/userguide/setup-email.html).
"""
def resend_validation_email(client, input, options \\ []) do
request(client, "ResendValidationEmail", input, options)
end
@spec request(map(), binary(), map(), list()) ::
{:ok, Poison.Parser.t | nil, Poison.Response.t} |
{:error, Poison.Parser.t} |
{:error, HTTPoison.Error.t}
defp request(client, action, input, options) do
client = %{client | service: "acm"}
host = get_host("acm", client)
url = get_url(host, client)
headers = [{"Host", host},
{"Content-Type", "application/x-amz-json-1.1"},
{"X-Amz-Target", "CertificateManager.#{action}"}]
payload = Poison.Encoder.encode(input, [])
headers = AWS.Request.sign_v4(client, "POST", url, headers, payload)
case HTTPoison.post(url, payload, headers, options) do
{:ok, response=%HTTPoison.Response{status_code: 200, body: ""}} ->
{:ok, nil, response}
{:ok, response=%HTTPoison.Response{status_code: 200, body: body}} ->
{:ok, Poison.Parser.parse!(body), response}
{:ok, _response=%HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body)
exception = error["__type"]
message = error["message"]
{:error, {exception, message}}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp get_host(endpoint_prefix, client) do
if client.region == "local" do
"localhost"
else
"#{endpoint_prefix}.#{client.region}.#{client.endpoint}"
end
end
defp get_url(host, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}/"
end
end
| 43.284585 | 88 | 0.731075 |
f74ff0818b0e13a455beea665c2cab0634556c3e | 1,272 | exs | Elixir | config/config.exs | GhAc-2017/RoiimPpaysafe | 9bf5f899bce0ec5045c5eee0a358ffa2d3c29d81 | [
"MIT"
] | null | null | null | config/config.exs | GhAc-2017/RoiimPpaysafe | 9bf5f899bce0ec5045c5eee0a358ffa2d3c29d81 | [
"MIT"
] | null | null | null | config/config.exs | GhAc-2017/RoiimPpaysafe | 9bf5f899bce0ec5045c5eee0a358ffa2d3c29d81 | [
"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 :roiimPpaysafe,
ecto_repos: [RoiimPpaysafe.Repo]
# Configures the endpoint
config :roiimPpaysafe, RoiimPpaysafeWeb.Endpoint,
url: [host: "localhost"],
secret_key_base: "bjS/eITjGggp/u4Yh5Nv+T5GVdt29Trs4VHJc4CjcL3qSTmU7DULfxluQ2VicQ/C",
render_errors: [view: RoiimPpaysafeWeb.ErrorView, accepts: ~w(html json), layout: false],
pubsub_server: RoiimPpaysafe.PubSub,
live_view: [signing_salt: "J6ir2Wti"]
# Configures Elixir's Logger
config :logger, :console,
format: "$time $metadata[$level] $message\n",
metadata: [:request_id]
# Use Jason for JSON parsing in Phoenix
config :phoenix, :json_library, Jason
config :roiimPpaysafe,
paysafe_api_username: "private-7751",
paysafe_api_password: "B-qa2-0-5f031cdd-0-302d0214496be84732a01f690268d3b8eb72e5b8ccf94e2202150085913117f2e1a8531505ee8ccfc8e98df3cf1748"
# 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"
| 36.342857 | 139 | 0.791667 |
f7501ac10479d670930b76c1758a6eab45d7f27d | 3,007 | ex | Elixir | lib/hl7/header.ex | starbelly/elixir-hl7 | 677566200ac0da8bf84f7b7e62ffdf2386351469 | [
"Apache-2.0"
] | null | null | null | lib/hl7/header.ex | starbelly/elixir-hl7 | 677566200ac0da8bf84f7b7e62ffdf2386351469 | [
"Apache-2.0"
] | null | null | null | lib/hl7/header.ex | starbelly/elixir-hl7 | 677566200ac0da8bf84f7b7e62ffdf2386351469 | [
"Apache-2.0"
] | null | null | null | defmodule HL7.Header do
@moduledoc """
An HL7 header implementation that can be used to build MSH segments and HL7 messages.
It is also exposed as metadata after parsing any HL7 message.
"""
@type t :: %HL7.Header{
message_type: binary(),
trigger_event: binary(),
sending_facility: binary(),
sending_application: binary(),
message_date_time: String.t(),
security: String.t(),
message_control_id: String.t(),
processing_id: String.t(),
separators: HL7.Separators.t(),
hl7_version: binary()
}
defstruct message_type: "",
trigger_event: "",
sending_facility: "",
sending_application: "",
receiving_facility: "",
receiving_application: "",
message_date_time: "",
security: "",
message_control_id: "",
processing_id: "",
separators: %HL7.Separators{},
hl7_version: ""
@spec new(String.t(), String.t(), String.t(), String.t() | list(), String.t()) :: HL7.Header.t()
def new(message_type, trigger_event, message_control_id, processing_id \\ "P", version \\ "2.1") do
%HL7.Header{
hl7_version: version,
message_type: message_type,
trigger_event: trigger_event,
message_control_id: message_control_id,
processing_id: processing_id,
message_date_time: get_message_date_time()
}
end
@spec to_msh(HL7.Header.t()) :: list()
def to_msh(%HL7.Header{} = h) do
[
"MSH",
h.separators.field,
h.separators.encoding_characters,
h.sending_application,
h.sending_facility,
h.receiving_application,
h.receiving_facility,
h.message_date_time,
h.security,
get_message_type_field(h),
h.message_control_id,
h.processing_id,
h.hl7_version
]
end
@spec zero_pad(pos_integer(), pos_integer()) :: String.t()
defp zero_pad(num, digits_needed) when is_integer(num) and is_integer(digits_needed) do
string_num = Integer.to_string(num)
pad_size = digits_needed - String.length(string_num)
zeros = String.duplicate("0", pad_size)
zeros <> string_num
end
@spec get_message_date_time() :: String.t()
def get_message_date_time() do
now = DateTime.utc_now()
zero_pad(now.year, 4) <>
zero_pad(now.month, 2) <>
zero_pad(now.day, 2) <>
zero_pad(now.hour, 2) <> zero_pad(now.minute, 2) <> zero_pad(now.second, 2) <> "+0000"
end
@spec get_message_type_field(HL7.Header.t()) :: [any()]
def get_message_type_field(%HL7.Header{} = h) do
v =
case h.hl7_version do
"2.1" -> [h.message_type, h.trigger_event]
"2.2" -> [h.message_type, h.trigger_event]
"2.3" -> [h.message_type, h.trigger_event]
"2.3.1" -> [h.message_type, h.trigger_event]
_ -> [h.message_type, h.trigger_event, h.message_type <> "_" <> h.trigger_event]
end
[v]
end
end
| 31.322917 | 101 | 0.613236 |
f75035ca110aaab481eb423aa99475d3815a86dd | 594 | exs | Elixir | api/test/views/error_view_test.exs | cnole/phoenix-react-slack-clone | 852cc32ee157a18c93ddd1eb627ddf61bc294cda | [
"MIT"
] | 34 | 2017-01-02T14:00:25.000Z | 2021-11-20T20:51:41.000Z | api/test/views/error_view_test.exs | cnole/phoenix-react-slack-clone | 852cc32ee157a18c93ddd1eb627ddf61bc294cda | [
"MIT"
] | 3 | 2017-08-02T19:38:27.000Z | 2022-03-02T03:34:27.000Z | api/test/views/error_view_test.exs | cnole/phoenix-react-slack-clone | 852cc32ee157a18c93ddd1eb627ddf61bc294cda | [
"MIT"
] | 5 | 2017-02-19T20:34:09.000Z | 2021-10-05T11:35:11.000Z | defmodule Sling.ErrorViewTest do
use Sling.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(Sling.ErrorView, "404.json", []) ==
%{errors: %{detail: "Page not found"}}
end
test "render 500.json" do
assert render(Sling.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal server error"}}
end
test "render any other" do
assert render(Sling.ErrorView, "505.json", []) ==
%{errors: %{detail: "Internal server error"}}
end
end
| 27 | 66 | 0.639731 |
f7503967cbdaaea109513d6aa43d6097be185323 | 753 | exs | Elixir | mix.exs | aseigo/plug_heartbeat | baaa63d15299d29c38037419577e7d1a355e0d27 | [
"MIT"
] | 36 | 2015-02-04T23:44:38.000Z | 2022-02-28T21:20:50.000Z | mix.exs | aseigo/plug_heartbeat | baaa63d15299d29c38037419577e7d1a355e0d27 | [
"MIT"
] | 3 | 2015-09-27T13:42:53.000Z | 2020-04-19T16:18:40.000Z | mix.exs | aseigo/plug_heartbeat | baaa63d15299d29c38037419577e7d1a355e0d27 | [
"MIT"
] | 3 | 2015-08-23T19:32:44.000Z | 2021-03-18T14:43:34.000Z | defmodule PlugHeartbeat.Mixfile do
use Mix.Project
@version "1.0.0"
@github_url "https://github.com/whatyouhide/plug_heartbeat"
@description "A tiny plug for responding to heartbeat requests"
def project do
[
app: :plug_heartbeat,
version: @version,
elixir: "~> 1.8",
deps: deps(),
description: @description,
name: "PlugHeartbeat",
source_url: @github_url,
package: package()
]
end
def application do
[extra_applications: []]
end
defp deps do
[
{:plug, "~> 1.0"},
{:ex_doc, "~> 0.21", only: :dev}
]
end
defp package do
[
maintainers: ["Andrea Leopardi"],
licenses: ["MIT"],
links: %{"GitHub" => @github_url}
]
end
end
| 18.825 | 65 | 0.581673 |
f7504a1e48ef591659ed2aca1cba5f5df740656b | 1,884 | ex | Elixir | clients/container_analysis/lib/google_api/container_analysis/v1/model/hint.ex | renovate-bot/elixir-google-api | 1da34cd39b670c99f067011e05ab90af93fef1f6 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/container_analysis/lib/google_api/container_analysis/v1/model/hint.ex | swansoffiee/elixir-google-api | 9ea6d39f273fb430634788c258b3189d3613dde0 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/container_analysis/lib/google_api/container_analysis/v1/model/hint.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.ContainerAnalysis.V1.Model.Hint do
@moduledoc """
This submessage provides human-readable hints about the purpose of the authority. Because the name of a note acts as its resource reference, it is important to disambiguate the canonical name of the Note (which might be a UUID for security purposes) from "readable" names more suitable for debug output. Note that these hints should not be used to look up authorities in security sensitive contexts, such as when looking up attestations to verify.
## Attributes
* `humanReadableName` (*type:* `String.t`, *default:* `nil`) - Required. The human readable name of this attestation authority, for example "qa".
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:humanReadableName => String.t() | nil
}
field(:humanReadableName)
end
defimpl Poison.Decoder, for: GoogleApi.ContainerAnalysis.V1.Model.Hint do
def decode(value, options) do
GoogleApi.ContainerAnalysis.V1.Model.Hint.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.ContainerAnalysis.V1.Model.Hint do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 40.085106 | 449 | 0.755839 |
f7506afb2f1486b7a8e2e2bae04bad382de322fc | 768 | ex | Elixir | lib/edgedb/protocol/messages/server/command_complete.ex | nsidnev/edgedb-elixir | bade2b9daba2e83bfaa5915b2addb74f41610968 | [
"MIT"
] | 30 | 2021-05-19T08:54:44.000Z | 2022-03-11T22:52:25.000Z | lib/edgedb/protocol/messages/server/command_complete.ex | nsidnev/edgedb-elixir | bade2b9daba2e83bfaa5915b2addb74f41610968 | [
"MIT"
] | 3 | 2021-11-17T21:26:01.000Z | 2022-03-12T09:49:25.000Z | lib/edgedb/protocol/messages/server/command_complete.ex | nsidnev/edgedb-elixir | bade2b9daba2e83bfaa5915b2addb74f41610968 | [
"MIT"
] | 3 | 2021-08-29T14:55:41.000Z | 2022-03-12T01:30:35.000Z | defmodule EdgeDB.Protocol.Messages.Server.CommandComplete do
use EdgeDB.Protocol.Message
alias EdgeDB.Protocol.{
Datatypes,
Enums,
Types
}
defmessage(
name: :command_complete,
server: true,
mtype: 0x43,
fields: [
headers: Keyword.t(),
status: Datatypes.String.t()
],
known_headers: %{
capabilities: [
code: 0x1001,
decoder: &Enums.Capability.exhaustive_decode/1
]
}
)
@impl EdgeDB.Protocol.Message
def decode_message(<<num_headers::uint16, rest::binary>>) do
{headers, rest} = Types.Header.decode(num_headers, rest)
{status, <<>>} = Datatypes.String.decode(rest)
command_complete(
headers: handle_headers(headers),
status: status
)
end
end
| 20.756757 | 62 | 0.638021 |
f75085312d39c19ece7b193062cd4febc9e627ea | 3,746 | ex | Elixir | lib/hello/accounts/accounts.ex | suhaschitade/AppoRemind | 64ed7123e7e5e2c40e398597c61d0a45db0cae50 | [
"MIT"
] | null | null | null | lib/hello/accounts/accounts.ex | suhaschitade/AppoRemind | 64ed7123e7e5e2c40e398597c61d0a45db0cae50 | [
"MIT"
] | null | null | null | lib/hello/accounts/accounts.ex | suhaschitade/AppoRemind | 64ed7123e7e5e2c40e398597c61d0a45db0cae50 | [
"MIT"
] | null | null | null | defmodule Hello.Accounts do
@moduledoc """
The Accounts context.
"""
import Ecto.Query, warn: false
alias Hello.Repo
alias Hello.Accounts.User
alias Hello.Accounts.User_Attribute
@doc """
Returns the list of users.
## Examples
iex> list_users()
[%User{}, ...]
"""
def list_users do
Repo.all(User)
end
@doc """
Gets a single user.
Raises `Ecto.NoResultsError` if the User does not exist.
## Examples
iex> get_user!(123)
%User{}
iex> get_user!(456)
** (Ecto.NoResultsError)
"""
def get_user!(id), do: Repo.get!(User, id)
@doc """
get the userAttribute based on user_id
"""
def get_user_attribute(id) do
# User_Attribute
# |> Ecto.Query.where(user_id: ^id)
# |> Repo.all
Repo.all(from ua in User_Attribute, where: ua.user_id == ^id and ua.active == true, select: {ua.company_id, ua.role_id})
end
@doc """
Creates a user.
## Examples
iex> create_user(%{field: value})
{:ok, %User{}}
iex> create_user(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_user(attrs \\ %{}) do
IO.inspect(attrs)
%User{}
|> User.changeset(attrs)
|> Repo.insert()
end
@doc """
Add User Attributes
"""
def create_user_attributes(attrs \\%{}) do
%User_Attribute{}
|> User_Attribute.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a user.
## Examples
iex> update_user(user, %{field: new_value})
{:ok, %User{}}
iex> update_user(user, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_user(%User{} = user, attrs) do
user
|> User.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a User.
## Examples
iex> delete_user(user)
{:ok, %User{}}
iex> delete_user(user)
{:error, %Ecto.Changeset{}}
"""
def delete_user(%User{} = user) do
Repo.delete(user)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking user changes.
## Examples
iex> change_user(user)
%Ecto.Changeset{source: %User{}}
"""
def change_user(%User{} = user) do
User.changeset(user, %{})
end
alias Hello.Accounts.Role
@doc """
Returns the list of roles.
## Examples
iex> list_roles()
[%Role{}, ...]
"""
def list_roles do
Repo.all(Role)
end
@doc """
Gets a single role.
Raises `Ecto.NoResultsError` if the Role does not exist.
## Examples
iex> get_role!(123)
%Role{}
iex> get_role!(456)
** (Ecto.NoResultsError)
"""
def get_role!(id), do: Repo.get!(Role, id)
@doc """
Creates a role.
## Examples
iex> create_role(%{field: value})
{:ok, %Role{}}
iex> create_role(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_role(attrs \\ %{}) do
%Role{}
|> Role.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a role.
## Examples
iex> update_role(role, %{field: new_value})
{:ok, %Role{}}
iex> update_role(role, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_role(%Role{} = role, attrs) do
role
|> Role.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a Role.
## Examples
iex> delete_role(role)
{:ok, %Role{}}
iex> delete_role(role)
{:error, %Ecto.Changeset{}}
"""
def delete_role(%Role{} = role) do
Repo.delete(role)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking role changes.
## Examples
iex> change_role(role)
%Ecto.Changeset{source: %Role{}}
"""
def change_role(%Role{} = role) do
Role.changeset(role, %{})
end
end
| 16.502203 | 123 | 0.567539 |
f750a13172590e6a20c04ac064b8d6cb5f83c1a9 | 1,090 | ex | Elixir | lib/ai_web.ex | mirai-audio/- | 365c0fba614543bf40ebaae55de47bc541bd473f | [
"MIT"
] | null | null | null | lib/ai_web.ex | mirai-audio/- | 365c0fba614543bf40ebaae55de47bc541bd473f | [
"MIT"
] | null | null | null | lib/ai_web.ex | mirai-audio/- | 365c0fba614543bf40ebaae55de47bc541bd473f | [
"MIT"
] | null | null | null | defmodule AiWeb do
@moduledoc """
AiWeb extension library for Phoenix Framework.
"""
def controller do
quote do
use Phoenix.Controller, namespace: AiWeb
alias Ai.Repo
import Ecto
import Ecto.Query
import AiWeb.Router.Helpers
import AiWeb.Gettext
end
end
def view do
quote do
use Phoenix.View, root: "lib/ai_web/templates", namespace: AiWeb
# Import convenience functions from controllers
import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
use Phoenix.HTML
import AiWeb.Router.Helpers
import AiWeb.ErrorHelpers
import AiWeb.Gettext
end
end
def router do
quote do
use Phoenix.Router
end
end
def channel do
quote do
use Phoenix.Channel
alias Ai.Repo
import Ecto
import Ecto.Query
import AiWeb.Gettext
end
end
@doc """
When used, dispatch to the appropriate controller/view/etc.
"""
defmacro __using__(which) when is_atom(which) do
apply(__MODULE__, which, [])
end
end
| 18.793103 | 88 | 0.655963 |
f750b52dcc0e8c6144aa7cc71180829df8f0f1bb | 153 | exs | Elixir | test/exonum_client_test.exs | sheb-gregor/elixir-exonum | 137e975c4f53f83b8e813e44feafda8936eb96d7 | [
"Apache-2.0"
] | null | null | null | test/exonum_client_test.exs | sheb-gregor/elixir-exonum | 137e975c4f53f83b8e813e44feafda8936eb96d7 | [
"Apache-2.0"
] | null | null | null | test/exonum_client_test.exs | sheb-gregor/elixir-exonum | 137e975c4f53f83b8e813e44feafda8936eb96d7 | [
"Apache-2.0"
] | null | null | null | defmodule ExonumClientTest do
use ExUnit.Case
doctest ExonumClient
test "greets the world" do
assert ExonumClient.hello() == :world
end
end
| 17 | 41 | 0.738562 |
f750e8291d36c6cff92d2c20b43d264899768f76 | 1,160 | exs | Elixir | mix.exs | twajjo/runtime_config | 9777709caae436bc395b8ec7f37e99943ac7553a | [
"MIT"
] | null | null | null | mix.exs | twajjo/runtime_config | 9777709caae436bc395b8ec7f37e99943ac7553a | [
"MIT"
] | null | null | null | mix.exs | twajjo/runtime_config | 9777709caae436bc395b8ec7f37e99943ac7553a | [
"MIT"
] | null | null | null | defmodule RuntimeConfig.MixProject do
use Mix.Project
def project do
[
app: :runtime_config,
version: "0.1.0",
elixir: "~> 1.9.4",
start_permanent: Mix.env() == :prod,
elixirc_paths: elixirc_paths(Mix.env()),
deps: deps()
]
end
# Run "mix help compile.app" to learn about applications.
def application do
[
extra_applications: [
:logger,
:external_config
]
]
end
# Run "mix help deps" to learn about dependencies.
defp deps do
[
{:external_config, "~> 0.1.0"},
{:earmark, "~> 0.1", only: :dev},
{:ex_doc, "~> 0.11", only: :dev},
# ... and for testing:
{:mox, "~> 0.5.1", only: :test},
{:excoveralls, "~> 0.7", only: :test},
# Code smell detectors
{:credo, "~> 0.8", only: [:dev, :test], runtime: false},
# Utilities
{:atomic_map, "~> 0.8"},
{:jason, "~> 1.1"},
# {:debug_test_lib, git: "git:github.com/mkreyman/debug_test_lib"}
]
end
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
end
| 24.680851 | 72 | 0.52069 |
f7513cbe4bd4dfbd6077990e748b781c91ae5214 | 1,842 | ex | Elixir | clients/content/lib/google_api/content/v2/model/loyalty_points.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/content/lib/google_api/content/v2/model/loyalty_points.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/content/lib/google_api/content/v2/model/loyalty_points.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Content.V2.Model.LoyaltyPoints do
@moduledoc """
## Attributes
* `name` (*type:* `String.t`, *default:* `nil`) - Name of loyalty points program. It is recommended to limit the name to 12 full-width characters or 24 Roman characters.
* `pointsValue` (*type:* `String.t`, *default:* `nil`) - The retailer's loyalty points in absolute value.
* `ratio` (*type:* `float()`, *default:* `nil`) - The ratio of a point when converted to currency. Google assumes currency based on Merchant Center settings. If ratio is left out, it defaults to 1.0.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:name => String.t(),
:pointsValue => String.t(),
:ratio => float()
}
field(:name)
field(:pointsValue)
field(:ratio)
end
defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.LoyaltyPoints do
def decode(value, options) do
GoogleApi.Content.V2.Model.LoyaltyPoints.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.LoyaltyPoints do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 34.754717 | 203 | 0.712812 |
f7515043405e4c84cc404a8dae715e2ee5d6cb5e | 22,519 | ex | Elixir | lib/aws/media_live.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | lib/aws/media_live.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | lib/aws/media_live.ex | ahsandar/aws-elixir | 25de8b6c3a1401bde737cfc26b0679b14b058f23 | [
"Apache-2.0"
] | null | null | null | # WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
# See https://github.com/aws-beam/aws-codegen for more details.
defmodule AWS.MediaLive do
@moduledoc """
API for AWS Elemental MediaLive
"""
@doc """
Update a channel schedule
"""
def batch_update_schedule(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}/schedule"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Creates a new channel
"""
def create_channel(client, input, options \\ []) do
path_ = "/prod/channels"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Create an input
"""
def create_input(client, input, options \\ []) do
path_ = "/prod/inputs"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Creates a Input Security Group
"""
def create_input_security_group(client, input, options \\ []) do
path_ = "/prod/inputSecurityGroups"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 200)
end
@doc """
Create a new multiplex.
"""
def create_multiplex(client, input, options \\ []) do
path_ = "/prod/multiplexes"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Create a new program in the multiplex.
"""
def create_multiplex_program(client, multiplex_id, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/programs"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Create tags for a resource
"""
def create_tags(client, resource_arn, input, options \\ []) do
path_ = "/prod/tags/#{URI.encode(resource_arn)}"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 204)
end
@doc """
Starts deletion of channel. The associated outputs are also deleted.
"""
def delete_channel(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 200)
end
@doc """
Deletes the input end point
"""
def delete_input(client, input_id, input, options \\ []) do
path_ = "/prod/inputs/#{URI.encode(input_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 200)
end
@doc """
Deletes an Input Security Group
"""
def delete_input_security_group(client, input_security_group_id, input, options \\ []) do
path_ = "/prod/inputSecurityGroups/#{URI.encode(input_security_group_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 200)
end
@doc """
Delete a multiplex. The multiplex must be idle.
"""
def delete_multiplex(client, multiplex_id, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 202)
end
@doc """
Delete a program from a multiplex.
"""
def delete_multiplex_program(client, multiplex_id, program_name, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/programs/#{URI.encode(program_name)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 200)
end
@doc """
Delete an expired reservation.
"""
def delete_reservation(client, reservation_id, input, options \\ []) do
path_ = "/prod/reservations/#{URI.encode(reservation_id)}"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 200)
end
@doc """
Delete all schedule actions on a channel.
"""
def delete_schedule(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}/schedule"
headers = []
query_ = []
request(client, :delete, path_, query_, headers, input, options, 200)
end
@doc """
Removes tags for a resource
"""
def delete_tags(client, resource_arn, input, options \\ []) do
path_ = "/prod/tags/#{URI.encode(resource_arn)}"
headers = []
{query_, input} =
[
{"TagKeys", "tagKeys"},
]
|> AWS.Request.build_params(input)
request(client, :delete, path_, query_, headers, input, options, 204)
end
@doc """
Gets details about a channel
"""
def describe_channel(client, channel_id, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Produces details about an input
"""
def describe_input(client, input_id, options \\ []) do
path_ = "/prod/inputs/#{URI.encode(input_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Gets the details for the input device
"""
def describe_input_device(client, input_device_id, options \\ []) do
path_ = "/prod/inputDevices/#{URI.encode(input_device_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Get the latest thumbnail data for the input device.
"""
def describe_input_device_thumbnail(client, input_device_id, accept, options \\ []) do
path_ = "/prod/inputDevices/#{URI.encode(input_device_id)}/thumbnailData"
headers = []
headers = if !is_nil(accept) do
[{"accept", accept} | headers]
else
headers
end
query_ = []
case request(client, :get, path_, query_, headers, nil, options, 200) do
{:ok, body, response} ->
body =
[
{"Content-Length", "ContentLength"},
{"Content-Type", "ContentType"},
{"ETag", "ETag"},
{"Last-Modified", "LastModified"},
]
|> Enum.reduce(body, fn {header_name, key}, acc ->
case List.keyfind(response.headers, header_name, 0) do
nil -> acc
{_header_name, value} -> Map.put(acc, key, value)
end
end)
{:ok, body, response}
result ->
result
end
end
@doc """
Produces a summary of an Input Security Group
"""
def describe_input_security_group(client, input_security_group_id, options \\ []) do
path_ = "/prod/inputSecurityGroups/#{URI.encode(input_security_group_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Gets details about a multiplex.
"""
def describe_multiplex(client, multiplex_id, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Get the details for a program in a multiplex.
"""
def describe_multiplex_program(client, multiplex_id, program_name, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/programs/#{URI.encode(program_name)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Get details for an offering.
"""
def describe_offering(client, offering_id, options \\ []) do
path_ = "/prod/offerings/#{URI.encode(offering_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Get details for a reservation.
"""
def describe_reservation(client, reservation_id, options \\ []) do
path_ = "/prod/reservations/#{URI.encode(reservation_id)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Get a channel schedule
"""
def describe_schedule(client, channel_id, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}/schedule"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Produces list of channels that have been created
"""
def list_channels(client, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/channels"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
List input devices
"""
def list_input_devices(client, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/inputDevices"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Produces a list of Input Security Groups for an account
"""
def list_input_security_groups(client, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/inputSecurityGroups"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Produces list of inputs that have been created
"""
def list_inputs(client, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/inputs"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
List the programs that currently exist for a specific multiplex.
"""
def list_multiplex_programs(client, multiplex_id, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/programs"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Retrieve a list of the existing multiplexes.
"""
def list_multiplexes(client, max_results \\ nil, next_token \\ nil, options \\ []) do
path_ = "/prod/multiplexes"
headers = []
query_ = []
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
List offerings available for purchase.
"""
def list_offerings(client, channel_class \\ nil, channel_configuration \\ nil, codec \\ nil, duration \\ nil, max_results \\ nil, maximum_bitrate \\ nil, maximum_framerate \\ nil, next_token \\ nil, resolution \\ nil, resource_type \\ nil, special_feature \\ nil, video_quality \\ nil, options \\ []) do
path_ = "/prod/offerings"
headers = []
query_ = []
query_ = if !is_nil(video_quality) do
[{"videoQuality", video_quality} | query_]
else
query_
end
query_ = if !is_nil(special_feature) do
[{"specialFeature", special_feature} | query_]
else
query_
end
query_ = if !is_nil(resource_type) do
[{"resourceType", resource_type} | query_]
else
query_
end
query_ = if !is_nil(resolution) do
[{"resolution", resolution} | query_]
else
query_
end
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(maximum_framerate) do
[{"maximumFramerate", maximum_framerate} | query_]
else
query_
end
query_ = if !is_nil(maximum_bitrate) do
[{"maximumBitrate", maximum_bitrate} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
query_ = if !is_nil(duration) do
[{"duration", duration} | query_]
else
query_
end
query_ = if !is_nil(codec) do
[{"codec", codec} | query_]
else
query_
end
query_ = if !is_nil(channel_configuration) do
[{"channelConfiguration", channel_configuration} | query_]
else
query_
end
query_ = if !is_nil(channel_class) do
[{"channelClass", channel_class} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
List purchased reservations.
"""
def list_reservations(client, channel_class \\ nil, codec \\ nil, max_results \\ nil, maximum_bitrate \\ nil, maximum_framerate \\ nil, next_token \\ nil, resolution \\ nil, resource_type \\ nil, special_feature \\ nil, video_quality \\ nil, options \\ []) do
path_ = "/prod/reservations"
headers = []
query_ = []
query_ = if !is_nil(video_quality) do
[{"videoQuality", video_quality} | query_]
else
query_
end
query_ = if !is_nil(special_feature) do
[{"specialFeature", special_feature} | query_]
else
query_
end
query_ = if !is_nil(resource_type) do
[{"resourceType", resource_type} | query_]
else
query_
end
query_ = if !is_nil(resolution) do
[{"resolution", resolution} | query_]
else
query_
end
query_ = if !is_nil(next_token) do
[{"nextToken", next_token} | query_]
else
query_
end
query_ = if !is_nil(maximum_framerate) do
[{"maximumFramerate", maximum_framerate} | query_]
else
query_
end
query_ = if !is_nil(maximum_bitrate) do
[{"maximumBitrate", maximum_bitrate} | query_]
else
query_
end
query_ = if !is_nil(max_results) do
[{"maxResults", max_results} | query_]
else
query_
end
query_ = if !is_nil(codec) do
[{"codec", codec} | query_]
else
query_
end
query_ = if !is_nil(channel_class) do
[{"channelClass", channel_class} | query_]
else
query_
end
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Produces list of tags that have been created for a resource
"""
def list_tags_for_resource(client, resource_arn, options \\ []) do
path_ = "/prod/tags/#{URI.encode(resource_arn)}"
headers = []
query_ = []
request(client, :get, path_, query_, headers, nil, options, 200)
end
@doc """
Purchase an offering and create a reservation.
"""
def purchase_offering(client, offering_id, input, options \\ []) do
path_ = "/prod/offerings/#{URI.encode(offering_id)}/purchase"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 201)
end
@doc """
Starts an existing channel
"""
def start_channel(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}/start"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 200)
end
@doc """
Start (run) the multiplex. Starting the multiplex does not start the
channels. You must explicitly start each channel.
"""
def start_multiplex(client, multiplex_id, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/start"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 202)
end
@doc """
Stops a running channel
"""
def stop_channel(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}/stop"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 200)
end
@doc """
Stops a running multiplex. If the multiplex isn't running, this action has
no effect.
"""
def stop_multiplex(client, multiplex_id, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/stop"
headers = []
query_ = []
request(client, :post, path_, query_, headers, input, options, 202)
end
@doc """
Updates a channel.
"""
def update_channel(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Changes the class of the channel.
"""
def update_channel_class(client, channel_id, input, options \\ []) do
path_ = "/prod/channels/#{URI.encode(channel_id)}/channelClass"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Updates an input.
"""
def update_input(client, input_id, input, options \\ []) do
path_ = "/prod/inputs/#{URI.encode(input_id)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Updates the parameters for the input device.
"""
def update_input_device(client, input_device_id, input, options \\ []) do
path_ = "/prod/inputDevices/#{URI.encode(input_device_id)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Update an Input Security Group's Whilelists.
"""
def update_input_security_group(client, input_security_group_id, input, options \\ []) do
path_ = "/prod/inputSecurityGroups/#{URI.encode(input_security_group_id)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Updates a multiplex.
"""
def update_multiplex(client, multiplex_id, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Update a program in a multiplex.
"""
def update_multiplex_program(client, multiplex_id, program_name, input, options \\ []) do
path_ = "/prod/multiplexes/#{URI.encode(multiplex_id)}/programs/#{URI.encode(program_name)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@doc """
Update reservation.
"""
def update_reservation(client, reservation_id, input, options \\ []) do
path_ = "/prod/reservations/#{URI.encode(reservation_id)}"
headers = []
query_ = []
request(client, :put, path_, query_, headers, input, options, 200)
end
@spec request(AWS.Client.t(), binary(), binary(), list(), list(), map(), list(), pos_integer()) ::
{:ok, Poison.Parser.t(), Poison.Response.t()}
| {:error, Poison.Parser.t()}
| {:error, HTTPoison.Error.t()}
defp request(client, method, path, query, headers, input, options, success_status_code) do
client = %{client | service: "medialive"}
host = build_host("medialive", client)
url = host
|> build_url(path, client)
|> add_query(query)
additional_headers = [{"Host", host}, {"Content-Type", "application/x-amz-json-1.1"}]
headers = AWS.Request.add_headers(additional_headers, headers)
payload = encode_payload(input)
headers = AWS.Request.sign_v4(client, method, url, headers, payload)
perform_request(method, url, payload, headers, options, success_status_code)
end
defp perform_request(method, url, payload, headers, options, nil) do
case HTTPoison.request(method, url, payload, headers, options) do
{:ok, %HTTPoison.Response{status_code: 200, body: ""} = response} ->
{:ok, response}
{:ok, %HTTPoison.Response{status_code: status_code, body: body} = response}
when status_code == 200 or status_code == 202 or status_code == 204 ->
{:ok, Poison.Parser.parse!(body, %{}), response}
{:ok, %HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body, %{})
{:error, error}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp perform_request(method, url, payload, headers, options, success_status_code) do
case HTTPoison.request(method, url, payload, headers, options) do
{:ok, %HTTPoison.Response{status_code: ^success_status_code, body: ""} = response} ->
{:ok, %{}, response}
{:ok, %HTTPoison.Response{status_code: ^success_status_code, body: body} = response} ->
{:ok, Poison.Parser.parse!(body, %{}), response}
{:ok, %HTTPoison.Response{body: body}} ->
error = Poison.Parser.parse!(body, %{})
{:error, error}
{:error, %HTTPoison.Error{reason: reason}} ->
{:error, %HTTPoison.Error{reason: reason}}
end
end
defp build_host(_endpoint_prefix, %{region: "local"}) do
"localhost"
end
defp build_host(endpoint_prefix, %{region: region, endpoint: endpoint}) do
"#{endpoint_prefix}.#{region}.#{endpoint}"
end
defp build_url(host, path, %{:proto => proto, :port => port}) do
"#{proto}://#{host}:#{port}#{path}"
end
defp add_query(url, []) do
url
end
defp add_query(url, query) do
querystring = AWS.Util.encode_query(query)
"#{url}?#{querystring}"
end
defp encode_payload(input) do
if input != nil, do: Poison.Encoder.encode(input, %{}), else: ""
end
end
| 29.359844 | 305 | 0.628047 |
f751724062d81cf4cc06e20508a092cafd6751fd | 1,718 | ex | Elixir | apps/ewallet/lib/ewallet/auth/user_authenticator.ex | Macavirus/ewallet | ce62177b8bd3f7e72156930d384a1c4c047a3b5b | [
"Apache-2.0"
] | null | null | null | apps/ewallet/lib/ewallet/auth/user_authenticator.ex | Macavirus/ewallet | ce62177b8bd3f7e72156930d384a1c4c047a3b5b | [
"Apache-2.0"
] | null | null | null | apps/ewallet/lib/ewallet/auth/user_authenticator.ex | Macavirus/ewallet | ce62177b8bd3f7e72156930d384a1c4c047a3b5b | [
"Apache-2.0"
] | null | null | null | # Copyright 2018-2019 OmiseGO Pte Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
defmodule EWallet.UserAuthenticator do
@moduledoc """
Handle user authentication with appropriate token between AuthToken and PreAuthToken.
"""
alias EWalletDB.{User, AuthToken, PreAuthToken}
def authenticate(nil, _, _), do: false
def authenticate(_, nil, _), do: false
def authenticate(%User{} = user, auth_token, owner_app) do
cond do
not User.enabled_2fa?(user) ->
AuthToken.authenticate(user.id, auth_token, owner_app)
PreAuthToken.get_by_token(auth_token, owner_app) == nil ->
AuthToken.authenticate(user.id, auth_token, owner_app)
true ->
PreAuthToken.authenticate(user.id, auth_token, owner_app)
end
end
def authenticate(user_id, auth_token, owner_app) do
user_id
|> User.get()
|> authenticate(auth_token, owner_app)
end
def generate(nil, _, _), do: {:error, :invalid_parameter}
def generate(%User{} = user, owner_app, originator) do
user
|> User.enabled_2fa?()
|> case do
true -> PreAuthToken.generate(user, owner_app, originator)
false -> AuthToken.generate(user, owner_app, originator)
end
end
end
| 30.678571 | 87 | 0.712456 |
f751a62f9ce97ab9e6f5a44728adb7b7e03bbd23 | 59 | exs | Elixir | test/test_helper.exs | anthonyoconnor/some_weather | edd3c07115b4f76c0531dd9f4586bd8a13fb369f | [
"MIT"
] | 1 | 2016-05-25T04:03:34.000Z | 2016-05-25T04:03:34.000Z | test/test_helper.exs | anthonyoconnor/some_weather | edd3c07115b4f76c0531dd9f4586bd8a13fb369f | [
"MIT"
] | null | null | null | test/test_helper.exs | anthonyoconnor/some_weather | edd3c07115b4f76c0531dd9f4586bd8a13fb369f | [
"MIT"
] | null | null | null | ExUnit.configure exclude: [external: true]
ExUnit.start()
| 14.75 | 42 | 0.762712 |
f751cd547374df51e96e6a0807c760d59cb507db | 1,123 | exs | Elixir | mix.exs | digitalnativescreative/exponent-server-sdk-elixir | b10c569f98ff9e8b3c0114755edc69ffe781fb0f | [
"MIT"
] | null | null | null | mix.exs | digitalnativescreative/exponent-server-sdk-elixir | b10c569f98ff9e8b3c0114755edc69ffe781fb0f | [
"MIT"
] | null | null | null | mix.exs | digitalnativescreative/exponent-server-sdk-elixir | b10c569f98ff9e8b3c0114755edc69ffe781fb0f | [
"MIT"
] | 1 | 2021-12-16T22:18:41.000Z | 2021-12-16T22:18:41.000Z | defmodule ExponentServerSdk.Mixfile do
use Mix.Project
def project do
[
app: :exponent_server_sdk,
version: "0.2.0",
elixir: "~> 1.11.4",
name: "ExponentServerSdk",
description: "Exponent Push Notification API library for Elixir",
source_url: "https://github.com/rdrop/exponent-server-sdk-elixir",
package: package(),
docs: docs(),
deps: deps()
]
end
def application do
[applications: [:logger, :httpoison, :poison]]
end
defp deps do
[
{:httpoison, ">= 1.8.0"},
{:poison, "~> 3.1.0"},
{:dialyze, "~> 0.2.1", only: [:dev, :test]},
{:credo, "~> 0.10.0", only: [:dev, :test]},
{:mock, "~> 0.3.2", only: :test},
{:ex_doc, ">= 0.0.0", only: [:dev, :test]},
{:inch_ex, ">= 0.0.0", only: [:dev, :test]}
]
end
def docs do
[
readme: "README.md",
main: ExponentServerSdk
]
end
defp package do
[
maintainers: ["rdrop"],
licenses: ["MIT"],
links: %{
"Github" => "https://github.com/rdrop/exponent-server-sdk-elixir.git"
}
]
end
end
| 22.019608 | 77 | 0.52894 |
f751e0986e1649f00a2bf91b9cda8f20e1e2527d | 5,306 | exs | Elixir | apps/gitgud_web/test/gitgud_web/controllers/email_controller_test.exs | EdmondFrank/gitgud | 1952c16130564357aa6f23e35f48f19e3a50d4dd | [
"MIT"
] | 449 | 2018-03-06T01:05:55.000Z | 2022-03-23T21:03:56.000Z | apps/gitgud_web/test/gitgud_web/controllers/email_controller_test.exs | EdmondFrank/gitgud | 1952c16130564357aa6f23e35f48f19e3a50d4dd | [
"MIT"
] | 69 | 2018-03-06T09:26:41.000Z | 2022-03-21T22:43:09.000Z | apps/gitgud_web/test/gitgud_web/controllers/email_controller_test.exs | EdmondFrank/gitgud | 1952c16130564357aa6f23e35f48f19e3a50d4dd | [
"MIT"
] | 41 | 2018-03-06T01:06:07.000Z | 2021-11-21T17:55:04.000Z | defmodule GitGud.Web.EmailControllerTest do
use GitGud.Web.ConnCase, async: true
use GitGud.Web.DataFactory
use Bamboo.Test
alias GitGud.DB
alias GitGud.Email
alias GitGud.User
alias GitGud.Web.LayoutView
setup :create_user
test "renders email settings if authenticated", %{conn: conn, user: user} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = get(conn, Routes.email_path(conn, :index))
assert {:ok, html} = Floki.parse_document(html_response(conn, 200))
assert Floki.text(Floki.find(html, "title")) == LayoutView.title(conn)
end
test "fails to render email settings if not authenticated", %{conn: conn} do
conn = get(conn, Routes.email_path(conn, :index))
assert {:ok, html} = Floki.parse_document(html_response(conn, 401))
assert Floki.text(Floki.find(html, "title")) == Plug.Conn.Status.reason_phrase(401)
end
test "creates emails with valid params", %{conn: conn, user: user} do
email_params = factory(:email)
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = post(conn, Routes.email_path(conn, :create), email: email_params)
assert get_flash(conn, :info) == "Email '#{email_params.address}' added."
assert redirected_to(conn) == Routes.email_path(conn, :index)
assert_email_delivered_with(subject: "Verify your email address")
end
test "fails to create email with invalid email address", %{conn: conn, user: user} do
email_params = factory(:email)
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = post(conn, Routes.email_path(conn, :create), email: Map.update!(email_params, :address, &(&1 <> ".$")))
assert get_flash(conn, :error) == "Something went wrong! Please check error(s) below."
assert {:ok, html} = Floki.parse_document(html_response(conn, 400))
assert Floki.text(Floki.find(html, "title")) == LayoutView.title(conn)
end
test "verifies email with valid verification token", %{conn: conn, user: user} do
email_params = factory(:email)
email_address = email_params.address
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = post(conn, Routes.email_path(conn, :create), email: email_params)
assert get_flash(conn, :info) == "Email '#{email_address}' added."
assert redirected_to(conn) == Routes.email_path(conn, :index)
receive do
{:delivered_email, %Bamboo.Email{text_body: text, to: [{_name, ^email_address}]}} ->
[reset_url] = Regex.run(Regex.compile!("#{Regex.escape(GitGud.Web.Endpoint.url)}[^\\s]+"), text)
conn = get(conn, reset_url)
assert get_flash(conn, :info) == "Email '#{email_address}' verified."
assert redirected_to(conn) == Routes.email_path(conn, :index)
after
1_000 -> raise "email not delivered"
end
end
test "fails to verify email with invalid verification token", %{conn: conn, user: user} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = get(conn, Routes.email_path(conn, :verify, "abcdefg"))
assert get_flash(conn, :error) == "Invalid verification token."
assert {:ok, html} = Floki.parse_document(html_response(conn, 400))
assert Floki.text(Floki.find(html, "title")) == LayoutView.title(conn)
end
describe "when emails exist" do
setup :create_emails
test "renders emails", %{conn: conn, user: user, emails: emails} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = get(conn, Routes.email_path(conn, :index))
assert {:ok, html} = Floki.parse_document(html_response(conn, 200))
assert Floki.text(Floki.find(html, "title")) == LayoutView.title(conn)
html_emails = Enum.map(Floki.find(html, "table tr td:first-child"), &String.trim(Floki.text(&1)))
for email <- emails do
assert email.address in html_emails
end
end
test "fails to create email with already existing email address", %{conn: conn, user: user, emails: emails} do
email_params = factory(:email)
conn = Plug.Test.init_test_session(conn, user_id: user.id)
conn = post(conn, Routes.email_path(conn, :create), email: Map.put(email_params, :address, hd(emails).address))
assert get_flash(conn, :error) == "Something went wrong! Please check error(s) below."
assert {:ok, html} = Floki.parse_document(html_response(conn, 400))
assert Floki.text(Floki.find(html, "title")) == LayoutView.title(conn)
end
test "deletes emails", %{conn: conn, user: user, emails: emails} do
conn = Plug.Test.init_test_session(conn, user_id: user.id)
for email <- emails do
conn = delete(conn, Routes.email_path(conn, :delete), email: %{id: to_string(email.id)})
assert get_flash(conn, :info) == "Email '#{email.address}' deleted."
assert redirected_to(conn) == Routes.email_path(conn, :index)
end
end
end
#
# Helpers
#
defp create_user(context) do
user = User.create!(factory(:user))
Map.put(context, :user, struct(user, emails: Enum.map(user.emails, &Email.verify!/1)))
end
defp create_emails(context) do
emails = Stream.repeatedly(fn -> Email.create!(context.user, factory(:email)) end)
context
|> Map.put(:emails, Enum.take(emails, 2))
|> Map.update!(:user, &DB.preload(&1, :emails))
end
end
| 43.85124 | 117 | 0.682623 |
f751e6549c1bbd1eca135233f98cdf1fe1f649e2 | 2,798 | ex | Elixir | lib/screens/v2/screen_audio_data.ex | mbta/screens | 4b586970f8844b19543bb2ffd4b032a89f6fa40a | [
"MIT"
] | 3 | 2021-07-27T14:11:00.000Z | 2022-01-03T14:16:43.000Z | lib/screens/v2/screen_audio_data.ex | mbta/screens | 4b586970f8844b19543bb2ffd4b032a89f6fa40a | [
"MIT"
] | 444 | 2021-03-10T20:57:17.000Z | 2022-03-31T16:00:35.000Z | lib/screens/v2/screen_audio_data.ex | mbta/screens | 4b586970f8844b19543bb2ffd4b032a89f6fa40a | [
"MIT"
] | null | null | null | defmodule Screens.V2.ScreenAudioData do
@moduledoc false
alias Screens.Config.Screen
alias Screens.Config.V2.{Audio, BusShelter}
alias Screens.V2.ScreenData
alias Screens.V2.WidgetInstance
@type screen_id :: String.t()
@spec by_screen_id(screen_id()) :: list({module(), map()}) | :error
def by_screen_id(
screen_id,
get_config_fn \\ &ScreenData.get_config/1,
fetch_data_fn \\ &ScreenData.fetch_data/1,
now \\ DateTime.utc_now()
) do
config = get_config_fn.(screen_id)
{:ok, now} = DateTime.shift_zone(now, "America/New_York")
case config do
%Screen{app_params: %app{}} when app not in [BusShelter] ->
:error
%Screen{app_params: %_app{audio: audio}} ->
if date_in_range?(audio, now) do
config
|> fetch_data_fn.()
|> elem(1)
|> Map.values()
|> Enum.filter(&WidgetInstance.audio_valid_candidate?/1)
|> Enum.sort_by(&WidgetInstance.audio_sort_key/1)
|> Enum.map(&{WidgetInstance.audio_view(&1), WidgetInstance.audio_serialize(&1)})
else
[]
end
end
end
@spec volume_by_screen_id(screen_id()) :: {:ok, float()} | :error
def volume_by_screen_id(
screen_id,
get_config_fn \\ &ScreenData.get_config/1,
now \\ DateTime.utc_now()
) do
config = get_config_fn.(screen_id)
{:ok, now} = DateTime.shift_zone(now, "America/New_York")
case config do
%Screen{app_params: %app{}} when app not in [BusShelter] ->
:error
%Screen{app_params: %_app{audio: audio}} ->
{:ok, get_volume(audio, now)}
end
end
defp get_volume(
%Audio{
daytime_start_time: daytime_start_time,
daytime_stop_time: daytime_stop_time,
daytime_volume: daytime_volume,
nighttime_volume: nighttime_volume
},
now
) do
if time_in_range?(now, daytime_start_time, daytime_stop_time),
do: daytime_volume,
else: nighttime_volume
end
defp date_in_range?(
%Audio{
start_time: start_time,
stop_time: stop_time,
days_active: days_active
},
dt
) do
Date.day_of_week(dt) in days_active and
time_in_range?(DateTime.to_time(dt), start_time, stop_time)
end
def time_in_range?(t, start_time, stop_time) do
if Time.compare(start_time, stop_time) in [:lt, :eq] do
# The range exists within a single day starting/ending at midnight
Time.compare(start_time, t) in [:lt, :eq] and Time.compare(stop_time, t) == :gt
else
# The range crosses midnight, e.g. start: 5am, stop: 1am
Time.compare(start_time, t) in [:lt, :eq] or Time.compare(stop_time, t) == :gt
end
end
end
| 29.765957 | 91 | 0.619014 |
f75230e8efe699010d2fe0687c314e44f9a0e874 | 4,394 | ex | Elixir | lib/mix/tasks/ecto.rollback.ex | bahelms/ecto_sql | a5b4efd127cf110f0a01d30b3e32f636cdee7563 | [
"Apache-2.0"
] | 384 | 2018-10-03T17:52:39.000Z | 2022-03-24T17:54:21.000Z | lib/mix/tasks/ecto.rollback.ex | bahelms/ecto_sql | a5b4efd127cf110f0a01d30b3e32f636cdee7563 | [
"Apache-2.0"
] | 357 | 2018-10-06T13:47:33.000Z | 2022-03-29T08:18:02.000Z | deps/ecto_sql/lib/mix/tasks/ecto.rollback.ex | adrianomota/blog | ef3b2d2ed54f038368ead8234d76c18983caa75b | [
"MIT"
] | 251 | 2018-10-04T11:06:41.000Z | 2022-03-29T07:22:53.000Z | defmodule Mix.Tasks.Ecto.Rollback do
use Mix.Task
import Mix.Ecto
import Mix.EctoSQL
@shortdoc "Rolls back the repository migrations"
@aliases [
r: :repo,
n: :step
]
@switches [
all: :boolean,
step: :integer,
to: :integer,
quiet: :boolean,
prefix: :string,
pool_size: :integer,
log_sql: :boolean,
log_migrations_sql: :boolean,
log_migrator_sql: :boolean,
repo: [:keep, :string],
no_compile: :boolean,
no_deps_check: :boolean,
migrations_path: :keep
]
@moduledoc """
Reverts applied migrations in the given repository.
Migrations are expected at "priv/YOUR_REPO/migrations" directory
of the current application, where "YOUR_REPO" is the last segment
in your repository name. For example, the repository `MyApp.Repo`
will use "priv/repo/migrations". The repository `Whatever.MyRepo`
will use "priv/my_repo/migrations".
You can configure a repository to use another directory by specifying
the `:priv` key under the repository configuration. The "migrations"
part will be automatically appended to it. For instance, to use
"priv/custom_repo/migrations":
config :my_app, MyApp.Repo, priv: "priv/custom_repo"
This task rolls back the last applied migration by default. To roll
back to a version number, supply `--to version_number`. To roll
back a specific number of times, use `--step n`. To undo all applied
migrations, provide `--all`.
The repositories to rollback are the ones specified under the
`:ecto_repos` option in the current app configuration. However,
if the `-r` option is given, it replaces the `:ecto_repos` config.
If a repository has not yet been started, one will be started outside
your application supervision tree and shutdown afterwards.
## Examples
$ mix ecto.rollback
$ mix ecto.rollback -r Custom.Repo
$ mix ecto.rollback -n 3
$ mix ecto.rollback --step 3
$ mix ecto.rollback --to 20080906120000
## Command line options
* `--all` - run all pending migrations
* `--log-migrations-sql` - log SQL generated by migration commands
* `--log-migrator-sql` - log SQL generated by the migrator, such as
transactions, table locks, etc
* `--migrations-path` - the path to load the migrations from, defaults to
`"priv/repo/migrations"`. This option may be given multiple times in which
case the migrations are loaded from all the given directories and sorted
as if they were in the same one
* `--no-compile` - does not compile applications before migrating
* `--no-deps-check` - does not check dependencies before migrating
* `--pool-size` - the pool size if the repository is started
only for the task (defaults to 2)
* `--prefix` - the prefix to run migrations on
* `--quiet` - do not log migration commands
* `-r`, `--repo` - the repo to migrate
* `--step`, `-n` - revert n migrations
* `--strict-version-order` - abort when applying a migration with old
timestamp (otherwise it emits a warning)
* `--to` - revert all migrations down to and including version
"""
@impl true
def run(args, migrator \\ &Ecto.Migrator.run/4) do
repos = parse_repo(args)
{opts, _} = OptionParser.parse!(args, strict: @switches, aliases: @aliases)
opts =
if opts[:to] || opts[:step] || opts[:all],
do: opts,
else: Keyword.put(opts, :step, 1)
opts =
if opts[:quiet],
do: Keyword.merge(opts, [log: false, log_migrations_sql: false, log_migrator_sql: false]),
else: opts
# Start ecto_sql explicitly before as we don't need
# to restart those apps if migrated.
{:ok, _} = Application.ensure_all_started(:ecto_sql)
for repo <- repos do
ensure_repo(repo, args)
paths = ensure_migrations_paths(repo, opts)
pool = repo.config[:pool]
fun =
if Code.ensure_loaded?(pool) and function_exported?(pool, :unboxed_run, 2) do
&pool.unboxed_run(&1, fn -> migrator.(&1, paths, :down, opts) end)
else
&migrator.(&1, paths, :down, opts)
end
case Ecto.Migrator.with_repo(repo, fun, [mode: :temporary] ++ opts) do
{:ok, _migrated, _apps} -> :ok
{:error, error} -> Mix.raise "Could not start repo #{inspect repo}, error: #{inspect error}"
end
end
:ok
end
end
| 30.727273 | 100 | 0.664315 |
f7526023258cbe00952d23a4506260992b2420cc | 6,066 | exs | Elixir | test/ex_doubles_test.exs | steven-solomon/exdoubles | 9650dcf75775de492141648fcee39c3317f722ae | [
"Apache-2.0"
] | 1 | 2019-11-08T21:02:59.000Z | 2019-11-08T21:02:59.000Z | test/ex_doubles_test.exs | steven-solomon/elephant | 9650dcf75775de492141648fcee39c3317f722ae | [
"Apache-2.0"
] | 5 | 2019-11-08T21:05:31.000Z | 2019-12-07T03:41:42.000Z | test/ex_doubles_test.exs | steven-solomon/exdoubles | 9650dcf75775de492141648fcee39c3317f722ae | [
"Apache-2.0"
] | 1 | 2019-10-23T18:13:06.000Z | 2019-10-23T18:13:06.000Z | defmodule ExDoublesTest do
use ExUnit.Case
import ExDoubles
test "raises error when zero arg function is NEVER called" do
{:ok, _} = mock(:zero_arg_name, 0)
assert_raise RuntimeError, "expected 1 times but was 0", fn ->
verify(:zero_arg_name, once())
end
assert_process_stopped()
end
describe "arity" do
test "returns truthy when zero arg function is called" do
{:ok, zero_arg_fn} = mock(:zero_arg_name, 0)
zero_arg_fn.()
assert verify(:zero_arg_name, once())
end
test "returns truthy when one arg function is called" do
{:ok, one_arg_fn} = mock(:one_arg_name, 1)
one_arg_fn.("hello")
assert verify(:one_arg_name, once())
end
test "returns truthy when two arg function is called" do
{:ok, two_arg_fn} = mock(:two_arg_name, 2)
two_arg_fn.("hello", "world")
assert verify(:two_arg_name, once())
end
test "returns truthy when three arg function is called" do
{:ok, three_arg_fn} = mock(:three_arg_name, 3)
three_arg_fn.("hello", "world", "people")
assert verify(:three_arg_name, once())
end
test "returns truthy when four arg function is called" do
{:ok, four_arg_fn} = mock(:four_arg_name, 4)
four_arg_fn.("hello", "world", "people", "hello")
assert verify(:four_arg_name, once())
end
test "returns truthy when five arg function is called" do
{:ok, five_arg_fn} = mock(:five_arg_name, 5)
five_arg_fn.("hello", "world", "people", "hello", "world")
assert verify(:five_arg_name, once())
end
test "returns truthy when six arg function is called" do
{:ok, five_arg_fn} = mock(:six_arg_name, 6)
five_arg_fn.("hello", "world", "people", "hello", "world", "people")
assert verify(:six_arg_name, once())
end
test "raises error when > 6 arg function passed to mock" do
assert_raise RuntimeError, "Arity greater than 6 is not supported.", fn ->
mock(:name, 7)
end
assert_process_stopped()
end
end
test "tracks multiple mocks" do
{:ok, one_fn} = mock(:one, 0)
{:ok, another_fn} = mock(:another, 0)
one_fn.()
another_fn.()
verify(:one, once())
verify(:another, once())
end
describe "stubbing behavior" do
test "returns nil from a mock that has NOT been stubbed" do
{:ok, zero_arg_fn} = mock(:zero_arg, 0)
assert is_nil(zero_arg_fn.())
end
test "returns stubbed value from a stubbed mock" do
{:ok, zero_arg_fn} = mock(:zero_arg, 0)
when_called(:zero_arg, :stub_value)
assert :stub_value == zero_arg_fn.()
end
test "returns stubbed values in the order they were passed" do
{:ok, zero_arg_fn} = mock(:zero_arg, 0)
when_called(:zero_arg, :stub_value_1)
when_called(:zero_arg, :stub_value_2)
assert :stub_value_1 == zero_arg_fn.()
assert :stub_value_2 == zero_arg_fn.()
assert is_nil(zero_arg_fn.())
end
end
describe "matchers" do
test "call count matchers" do
{:ok, zero_arg_fn} = mock(:zero_arg, 0)
zero_arg_fn.()
zero_arg_fn.()
verify(:zero_arg, twice())
zero_arg_fn.()
verify(:zero_arg, thrice())
zero_arg_fn.()
verify(:zero_arg, times(4))
end
test "called_with matcher throws error when used with zero arg mock" do
{:ok, _} = mock(:zero_arg, 0)
assert_raise RuntimeError, "called_with cannot have more arguments than the mocked function.", fn ->
verify(:zero_arg, called_with(:foo))
end
end
test "called_with raises an error when function is never invoked" do
{:ok, _} = mock(:one_arg, 1)
assert_raise RuntimeError, ":one_arg was never called with [:foo]", fn ->
verify(:one_arg, called_with([:foo]))
end
end
test "called_with gives more detail when argument does not match" do
{:ok, one_arg_fn} = mock(:one_arg, 1)
one_arg_fn.(:bar)
one_arg_fn.(:baz)
message = """
:one_arg was never called with [:foo]
but was called with:
[:baz]
[:bar]
"""
assert_raise RuntimeError, message, fn ->
verify(:one_arg, called_with([:foo]))
end
end
test "called_with matches one arg function" do
{:ok, one_arg_fn} = mock(:one_arg, 1)
one_arg_fn.(:foo)
verify(:one_arg, called_with([:foo]))
end
test "called_with matches two arg function" do
{:ok, two_arg_fn} = mock(:two_arg, 2)
two_arg_fn.("hello", "world")
verify(:two_arg, called_with(["hello", "world"]))
end
test "called_with matches three arg function" do
{:ok, three_arg_fn} = mock(:three_arg, 3)
three_arg_fn.("hello", "world", "people")
verify(:three_arg, called_with(["hello", "world", "people"]))
end
test "called_with matches four arg function" do
{:ok, four_arg_fn} = mock(:four_arg, 4)
four_arg_fn.("hello", "world", "people", "hello")
verify(:four_arg, called_with(["hello", "world", "people", "hello"]))
end
test "called_with matches five arg function" do
{:ok, five_arg_fn} = mock(:five_arg, 5)
five_arg_fn.("hello", "world", "people", "hello", "world")
verify(:five_arg, called_with(["hello", "world", "people", "hello", "world"]))
end
test "called_with matches six arg function" do
{:ok, six_arg_fn} = mock(:six_arg, 6)
six_arg_fn.("hello", "world", "people", "hello", "world", "people")
verify(:six_arg, called_with(["hello", "world", "people", "hello", "world", "people"]))
end
end
describe "process book keeping" do
test "there is a process registered " do
_ = mock(:name, 0)
assert_process_running()
end
end
defp assert_process_stopped() do
assert is_nil(Enum.find_index(Process.registered(), fn name -> name == ExDoubles.State end))
end
defp assert_process_running() do
assert is_integer(Enum.find_index(Process.registered(), fn name -> name == ExDoubles.State end))
end
end
| 26.034335 | 106 | 0.625783 |
f7526273f0832101fc4e8911c933f1b5e1f58b1d | 2,023 | exs | Elixir | test/adoptoposs_web/live/repo_live_test.exs | floriank/adoptoposs | 02d1a8d87dbb36ee7364ae737241d6b129d0bf2d | [
"MIT"
] | null | null | null | test/adoptoposs_web/live/repo_live_test.exs | floriank/adoptoposs | 02d1a8d87dbb36ee7364ae737241d6b129d0bf2d | [
"MIT"
] | 1 | 2021-05-11T20:15:21.000Z | 2021-05-11T20:15:21.000Z | test/adoptoposs_web/live/repo_live_test.exs | floriank/adoptoposs | 02d1a8d87dbb36ee7364ae737241d6b129d0bf2d | [
"MIT"
] | null | null | null | defmodule AdoptopossWeb.RepoLiveTest do
use AdoptopossWeb.LiveCase
alias Adoptoposs.Tags.Tag
test "disconnected mount of /settings/repos/:orga_id when logged out", %{conn: conn} do
conn = get(conn, Routes.live_path(conn, AdoptopossWeb.RepoLive, "orga"))
assert html_response(conn, 302)
assert conn.halted
end
test "connected mount of /settings/repos/:orga_id when logged out", %{conn: conn} do
assert {:error, %{redirect: %{to: "/"}}} =
live(conn, Routes.live_path(conn, AdoptopossWeb.RepoLive, "orga"))
end
@tag login_as: "user123"
test "disconnected mount of /settings/repos/:orga_id when logged in", %{conn: conn, user: user} do
conn = get(conn, Routes.live_path(conn, AdoptopossWeb.RepoLive, user.username))
assert html_response(conn, 200) =~ "Submit Repo from"
end
@tag login_as: "user123"
test "connected mount of /settings/repos/:orga_id when logged in", %{conn: conn, user: user} do
{:ok, _view, html} = live(conn, Routes.live_path(conn, AdoptopossWeb.RepoLive, user.username))
assert html =~ "Submit Repo from"
end
@tag login_as: "user123"
test "submitting a repo", %{conn: conn, user: user} do
{:ok, {_page_info, [repo | _] = repos}} = Adoptoposs.Network.user_repos("token", "github", 2)
tags = repos |> Enum.uniq_by(& &1.language.name) |> Enum.map(& &1.language)
for tag <- tags do
insert(:tag, type: Tag.Language.type(), name: tag.name)
end
{:ok, view, html} = live(conn, Routes.live_path(conn, AdoptopossWeb.RepoLive, user.username))
for repo <- repos do
assert html =~ repo.name
end
refute html =~ ~r/submitted to.+your projects/i
component = [view, "#repo-" <> AdoptopossWeb.RepoView.hashed(repo.id)]
html = render_click(component, :attempt_submit, %{})
assert html =~ "I’m looking for"
assert html =~ "Submit"
html = render_submit(component, :submit_project, %{project: %{description: "text"}})
assert html =~ ~r/submitted to.+your projects/is
end
end
| 36.781818 | 100 | 0.672269 |
f7528283b0fb6c8f1a99708d024737b247e2890a | 10,577 | ex | Elixir | lib/cizen/saga.ex | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | lib/cizen/saga.ex | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | lib/cizen/saga.ex | Hihaheho-Studios/Cizen | 09ba3c66aa11d0db913ffde804509bc7bef80db9 | [
"MIT"
] | null | null | null | defmodule Cizen.Saga do
@moduledoc """
The saga behaviour
## Example
defmodule SomeSaga do
use Cizen.Saga
defstruct []
@impl true
def on_start(%__MODULE__{}) do
saga
end
@impl true
def handle_event(_event, state) do
state
end
end
"""
alias Cizen.CizenSagaRegistry
alias Cizen.Dispatcher
alias Cizen.Event
alias Cizen.Pattern
alias Cizen.SagaID
require Pattern
@type t :: struct
@type state :: any
# `pid | {atom, node} | atom` is the same as the Process.monitor/1's argument.
@type lifetime :: pid | {atom, node} | atom | nil
@type start_option ::
{:saga_id, SagaID.t()}
| {:lifetime, pid | SagaID.t() | nil}
| {:return, :pid | :saga_id}
| {:resume, term}
@doc """
Invoked when the saga is started.
Saga.Started event will be dispatched after this callback.
Returned value will be used as the next state to pass `c:handle_event/2` callback.
"""
@callback on_start(t()) :: state
@doc """
Invoked when the saga receives an event.
Returned value will be used as the next state to pass `c:handle_event/2` callback.
"""
@callback handle_event(Event.t(), state) :: state
@doc """
Invoked when the saga is resumed.
Returned value will be used as the next state to pass `c:handle_event/2` callback.
This callback is predefined. The default implementation is here:
```
def on_resume(saga, state) do
on_start(saga)
state
end
```
"""
@callback on_resume(t(), state) :: state
@doc """
The handler for `Saga.call/2`.
You should call `Saga.reply/2` with `from`, otherwise the call will be timeout.
You can reply from any process, at any time.
"""
@callback handle_call(message :: term, from :: GenServer.from(), state) :: state
@doc """
The handler for `Saga.cast/2`.
"""
@callback handle_cast(message :: term, state) :: state
@internal_prefix :"$cizen.saga"
@saga_id_key :"$cizen.saga.id"
@lazy_init :"$cizen.saga.lazy_init"
defmacro __using__(_opts) do
alias Cizen.{CizenSagaRegistry, Dispatcher, Saga}
quote do
@behaviour Saga
@impl Saga
def on_resume(saga, state) do
on_start(saga)
state
end
# @impl GenServer
def init({:start, id, saga, lifetime}) do
Saga.init_with(id, saga, lifetime, %Saga.Started{saga_id: id}, :on_start, [
saga
])
end
# @impl GenServer
def init({:resume, id, saga, state, lifetime}) do
Saga.init_with(id, saga, lifetime, %Saga.Resumed{saga_id: id}, :on_resume, [
saga,
state
])
end
# @impl GenServer
def handle_info({:DOWN, _, :process, _, _}, state) do
{:stop, {:shutdown, :finish}, state}
end
# @impl GenServer
def handle_info(event, state) do
id = Saga.self()
case event do
%Saga.Finish{saga_id: ^id} ->
{:stop, {:shutdown, :finish}, state}
event ->
state = handle_event(event, state)
{:noreply, state}
end
rescue
reason -> {:stop, {:shutdown, {reason, __STACKTRACE__}}, state}
end
# @impl GenServer
def terminate(:shutdown, _state) do
:shutdown
end
def terminate({:shutdown, :finish}, _state) do
Dispatcher.dispatch(%Saga.Finished{saga_id: Saga.self()})
:shutdown
end
def terminate({:shutdown, {reason, trace}}, _state) do
id = Saga.self()
saga =
case Saga.get_saga(id) do
{:ok, saga} ->
saga
# nil -> should not happen
end
Dispatcher.dispatch(%Saga.Crashed{
saga_id: id,
saga: saga,
reason: reason,
stacktrace: trace
})
:shutdown
end
# @impl GenServer
@impl Saga
def handle_call({:"$cizen.saga", :get_saga_id}, _from, state) do
[saga_id] = Registry.keys(CizenSagaRegistry, Kernel.self())
{:reply, saga_id, state}
end
def handle_call({:"$cizen.saga", :request, request}, _from, state) do
result = Saga.handle_request(request)
{:reply, result, state}
end
def handle_call({:"$cizen.saga", message}, from, state) do
state = handle_call(message, from, state)
{:noreply, state}
end
# @impl GenServer
@impl Saga
def handle_cast({:"$cizen.saga", :dummy_to_prevent_dialyzer_errors}, state), do: state
def handle_cast({:"$cizen.saga", message}, state) do
state = handle_cast(message, state)
{:noreply, state}
end
defoverridable on_resume: 2
end
end
defmodule Finish do
@moduledoc "A event fired to finish"
defstruct([:saga_id])
end
defmodule Started do
@moduledoc "A event fired on start"
defstruct([:saga_id])
end
defmodule Resumed do
@moduledoc "A event fired on resume"
defstruct([:saga_id])
end
defmodule Finished do
@moduledoc "A event fired on finish"
defstruct([:saga_id])
end
defmodule Crashed do
@moduledoc "A event fired on crash"
defstruct([:saga_id, :saga, :reason, :stacktrace])
end
@doc """
Returns the pid for the given saga ID.
"""
@spec get_pid(SagaID.t()) :: {:ok, pid} | :error
defdelegate get_pid(saga_id), to: CizenSagaRegistry
@doc """
Returns the saga struct for the given saga ID.
"""
@spec get_saga(SagaID.t()) :: {:ok, t()} | :error
defdelegate get_saga(saga_id), to: CizenSagaRegistry
def lazy_init, do: @lazy_init
@doc """
Returns the module for a saga.
"""
@spec module(t) :: module
def module(saga) do
saga.__struct__
end
@doc """
Resumes a saga with the given state.
Options:
- `{:lifetime, lifetime_saga_or_pid}` the lifetime saga ID or pid. (Default: the saga lives forever)
- `{:return, return_type}` when `:saga_id`, `{:ok, saga_id}` is returned. (Default: :pid)
"""
@spec resume(SagaID.t(), t(), state, [start_option]) :: GenServer.on_start()
def resume(id, saga, state, opts \\ []) do
start(saga, Keyword.merge(opts, saga_id: id, resume: state))
end
@doc """
Starts a saga.
Options:
- `{:saga_id, saga_id}` starts with the specified saga ID. (Default: randomly generated)
- `{:lifetime, lifetime_saga_or_pid}` the lifetime saga ID or pid. (Default: the saga lives forever)
- `{:return, return_type}` when `:saga_id`, `{:ok, saga_id}` is returned. (Default: :pid)
- `{:resume, state}` when given, resumes the saga with the specified state.
"""
@spec start(t(), opts :: [start_option]) :: GenServer.on_start()
def start(%module{} = saga, opts \\ []) do
{saga_id, return, init} = handle_opts(saga, opts)
result = GenServer.start(module, init)
handle_opts_return(result, saga_id, return)
end
@doc """
Starts a saga linked to the current process.
See `Saga.start/2` for details.
"""
@spec start_link(t(), opts :: [start_option]) :: GenServer.on_start()
def start_link(%module{} = saga, opts \\ []) do
{saga_id, return, init} = handle_opts(saga, opts)
result = GenServer.start_link(module, init)
handle_opts_return(result, saga_id, return)
end
defp handle_opts(saga, opts) do
{saga_id, opts} = Keyword.pop(opts, :saga_id, SagaID.new())
{lifetime, opts} = Keyword.pop(opts, :lifetime, nil)
{return, opts} = Keyword.pop(opts, :return, :pid)
mode =
case Keyword.fetch(opts, :resume) do
{:ok, state} -> {:resume, state}
_ -> :start
end
opts = Keyword.delete(opts, :resume)
if opts != [],
do: raise(ArgumentError, message: "invalid argument(s): #{inspect(Keyword.keys(opts))}")
lifetime =
case lifetime do
nil ->
nil
pid when is_pid(pid) ->
pid
saga_id ->
get_lifetime_pid_from_saga_id(saga_id)
end
init =
case mode do
:start -> {:start, saga_id, saga, lifetime}
{:resume, state} -> {:resume, saga_id, saga, state, lifetime}
end
{saga_id, return, init}
end
defp get_lifetime_pid_from_saga_id(saga_id) do
case get_pid(saga_id) do
{:ok, pid} -> pid
_ -> spawn(fn -> nil end)
end
end
defp handle_opts_return(result, saga_id, return) do
case result do
{:ok, pid} ->
{:ok, if(return == :pid, do: pid, else: saga_id)}
other ->
other
end
end
@spec stop(SagaID.t()) :: :ok
def stop(id) do
GenServer.stop({:via, Registry, {CizenSagaRegistry, id}}, :shutdown)
catch
:exit, _ -> :ok
end
def send_to(id, message) do
Registry.dispatch(CizenSagaRegistry, id, fn entries ->
for {pid, _} <- entries, do: send(pid, message)
end)
end
def exit(id, reason, trace) do
GenServer.stop({:via, Registry, {CizenSagaRegistry, id}}, {:shutdown, {reason, trace}})
end
def call(id, message) do
GenServer.call({:via, Registry, {CizenSagaRegistry, id}}, {@internal_prefix, message})
end
def cast(id, message) do
GenServer.cast({:via, Registry, {CizenSagaRegistry, id}}, {@internal_prefix, message})
end
def self do
Process.get(@saga_id_key)
end
def reply(from, reply) do
GenServer.reply(from, reply)
end
@doc false
def init_with(id, saga, lifetime, event, function, arguments) do
Registry.register(CizenSagaRegistry, id, saga)
Dispatcher.listen(Pattern.new(fn %Finish{saga_id: ^id} -> true end))
module = module(saga)
unless is_nil(lifetime), do: Process.monitor(lifetime)
Process.put(@saga_id_key, id)
state =
case apply(module, function, arguments) do
{@lazy_init, state} ->
state
state ->
Dispatcher.dispatch(event)
state
end
{:ok, state}
end
@doc false
def handle_request({:register, registry, saga_id, key, value}) do
Registry.register(registry, key, {saga_id, value})
end
def handle_request({:unregister, registry, key}) do
Registry.unregister(registry, key)
end
def handle_request({:unregister_match, registry, key, pattern, guards}) do
Registry.unregister_match(registry, key, pattern, guards)
end
def handle_request({:update_value, registry, key, callback}) do
Registry.update_value(registry, key, fn {saga_id, value} -> {saga_id, callback.(value)} end)
end
@doc false
def saga_id_key, do: @saga_id_key
@doc false
def internal_prefix, do: @internal_prefix
end
| 25.303828 | 104 | 0.612272 |
f75287fd1112ce468f10dd8810f25f86a2184d67 | 69 | exs | Elixir | apps/led_status/test/led_status_test.exs | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | null | null | null | apps/led_status/test/led_status_test.exs | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | 8 | 2020-11-16T09:59:12.000Z | 2020-11-16T10:13:07.000Z | apps/led_status/test/led_status_test.exs | paulanthonywilson/mcam | df9c5aaae00b568749dff22613636f5cb92f905a | [
"MIT"
] | null | null | null | defmodule LedStatusTest do
use ExUnit.Case
doctest LedStatus
end
| 13.8 | 26 | 0.811594 |
f7531e64ed431e7c802ffd73c97deea2d7d05a7a | 2,727 | exs | Elixir | test/plug/logger_test.exs | zph/ex_json_logger | e744f5b79e41ce105976e3d7ad0406526c9c6890 | [
"MIT"
] | null | null | null | test/plug/logger_test.exs | zph/ex_json_logger | e744f5b79e41ce105976e3d7ad0406526c9c6890 | [
"MIT"
] | null | null | null | test/plug/logger_test.exs | zph/ex_json_logger | e744f5b79e41ce105976e3d7ad0406526c9c6890 | [
"MIT"
] | 1 | 2020-02-04T17:48:30.000Z | 2020-02-04T17:48:30.000Z | defmodule ExJsonLogger.Plug.LoggerTest do
use ExUnit.Case, async: true
use Plug.Test
import TestUtils, only: [capture_log: 1]
require Logger
@default_metadata [
:method,
:path,
:status,
:duration
]
@phoenix_metadata [
:format,
:controller,
:action
]
defmodule MyApp do
use Plug.Builder
plug(ExJsonLogger.Plug.Logger)
plug(
Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Poison
)
plug(:passthrough)
defp passthrough(conn, _) do
Plug.Conn.send_resp(conn, 200, "Passthrough")
end
end
defp put_phoenix_privates(conn) do
conn
|> put_private(:phoenix_controller, __MODULE__)
|> put_private(:phoenix_action, :show)
|> put_private(:phoenix_format, "json")
end
describe "when request is made to phoenix controller" do
test "request information is added to metadata" do
Logger.configure_backend(
:console,
format: "$metadata",
device: :user,
metadata: @default_metadata ++ @phoenix_metadata,
colors: [enabled: false]
)
message =
capture_log(fn ->
:get
|> conn("/")
|> put_phoenix_privates
|> MyApp.call([])
end)
assert message =~ "method=GET"
assert message =~ "path=/"
assert message =~ "status=200"
assert message =~ ~r/duration=\d+.\d/u
assert message =~ "format=json"
assert message =~ "controller=#{inspect(__MODULE__)}"
assert message =~ "action=show"
end
end
describe "when request is made to non phoenix controller" do
test "request information is added to metadata" do
Logger.configure_backend(
:console,
format: "$metadata",
device: :user,
metadata: @default_metadata,
colors: [enabled: false]
)
message =
capture_log(fn ->
:get
|> conn("/")
|> MyApp.call([])
end)
assert message =~ "method=GET"
assert message =~ "path=/"
assert message =~ "status=200"
assert message =~ ~r/duration=\d+.\d/u
refute message =~ "format="
refute message =~ "controller="
refute message =~ "action="
end
end
describe "when metadata isn't included in configuration" do
test "metadata is filtered" do
Logger.configure_backend(
:console,
format: "$metadata",
device: :user,
metadata: [],
colors: [enabled: false]
)
message =
capture_log(fn ->
:get
|> conn("/")
|> MyApp.call([])
end)
assert message == ""
end
end
end
| 21.991935 | 62 | 0.570224 |
f7532181e6f92879d81fd16e62539d5f2bee2ff4 | 3,640 | ex | Elixir | lib/glimesh_web/live/user_live/components/channel_title.ex | DeeRock94/glimesh.tv | e4517e4e3b03f98a3cab2d16b82f365e3b23fd9d | [
"MIT"
] | null | null | null | lib/glimesh_web/live/user_live/components/channel_title.ex | DeeRock94/glimesh.tv | e4517e4e3b03f98a3cab2d16b82f365e3b23fd9d | [
"MIT"
] | null | null | null | lib/glimesh_web/live/user_live/components/channel_title.ex | DeeRock94/glimesh.tv | e4517e4e3b03f98a3cab2d16b82f365e3b23fd9d | [
"MIT"
] | null | null | null | defmodule GlimeshWeb.UserLive.Components.ChannelTitle do
use GlimeshWeb, :live_view
import Gettext, only: [with_locale: 2]
alias Glimesh.ChannelCategories
alias Glimesh.ChannelLookups
alias Glimesh.Streams
@impl true
def render(assigns) do
~L"""
<%= if @can_change do %>
<%= if !@editing do %>
<h5 class="mb-0"><%= render_badge(@channel) %> <span class="badge badge-primary"><%= @channel.category.name %></span> <%= @channel.title %> <a class="fas fa-edit" phx-click="toggle-edit" href="#" aria-label="<%= gettext("Edit") %>"></a></h5>
<% else %>
<%= f = form_for @changeset, "#", [phx_submit: :save] %>
<div class="input-group">
<%= select f, :category_id, @categories, [class: "form-control", "phx-hook": "Choices", "phx-update": "ignore"] %>
<%= text_input f, :title, [class: "form-control"] %>
<div class="input-group-append">
<%= with_locale(Glimesh.Accounts.get_user_locale(@user), fn -> %>
<%= submit gettext("Save Info"), class: "btn btn-primary" %>
<% end) %>
</div>
</div>
</form>
<% end %>
<% else %>
<h5 class="mb-0"><%= render_badge(@channel) %> <span class="badge badge-primary"><%= @channel.category.name %></span> <%= @channel.title %> </h5>
<% end %>
<%= for tag <- @channel.tags do %>
<%= live_patch tag.name, to: Routes.streams_list_path(@socket, :index, @channel.category.slug, %{tag: tag.slug}), class: "badge badge-pill badge-primary" %>
<% end %>
"""
end
def render_badge(channel) do
if channel.status == "live" do
raw("""
<span class="badge badge-danger">Live!</span>
""")
else
raw("")
end
end
@impl true
def mount(_params, %{"channel_id" => channel_id, "user" => nil}, socket) do
if connected?(socket), do: Streams.subscribe_to(:channel, channel_id)
channel = ChannelLookups.get_channel!(channel_id)
{:ok,
socket
|> assign(:channel, channel)
|> assign(:user, nil)
|> assign(:channel, channel)
|> assign(:editing, false)
|> assign(:can_change, false)}
end
@impl true
def mount(_params, %{"channel_id" => channel_id, "user" => user}, socket) do
if connected?(socket), do: Streams.subscribe_to(:channel, channel_id)
channel = ChannelLookups.get_channel!(channel_id)
{:ok,
socket
|> assign_categories()
|> assign(:channel, channel)
|> assign(:user, user)
|> assign(:channel, channel)
|> assign(:changeset, Streams.change_channel(channel))
|> assign(:can_change, Bodyguard.permit?(Glimesh.Streams, :update_channel, user, channel))
|> assign(:editing, false)}
end
@impl true
def handle_event("toggle-edit", _value, socket) do
{:noreply, socket |> assign(:editing, socket.assigns.editing |> Kernel.not())}
end
@impl true
def handle_event("save", %{"channel" => channel}, socket) do
case Streams.update_channel(socket.assigns.user, socket.assigns.channel, channel) do
{:ok, changeset} ->
{:noreply,
socket
|> assign(:editing, false)
|> assign(:channel, changeset)
|> assign(:changeset, Streams.change_channel(changeset))}
{:error, %Ecto.Changeset{} = changeset} ->
{:noreply, assign(socket, changeset: changeset)}
end
end
@impl true
def handle_info({:channel, data}, socket) do
{:noreply, assign(socket, channel: data)}
end
defp assign_categories(socket) do
socket
|> assign(
:categories,
ChannelCategories.list_categories_for_select()
)
end
end
| 32.212389 | 249 | 0.604121 |
f7537c4b05f2589234e95f1e28dfbdd48d8e2c66 | 357 | ex | Elixir | test/support/test_setup/state.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 356 | 2016-03-16T12:37:28.000Z | 2021-12-18T03:22:39.000Z | test/support/test_setup/state.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 30 | 2016-03-16T09:19:10.000Z | 2021-01-12T08:10:52.000Z | test/support/test_setup/state.ex | harry-gao/ex-cart | 573e7f977bb3b710d11618dd215d4ddd8f819fb3 | [
"Apache-2.0"
] | 72 | 2016-03-16T13:32:14.000Z | 2021-03-23T11:27:43.000Z | defmodule Nectar.TestSetup.State do
alias Nectar.Repo
@default_state_attrs %{name: "State", abbr: "ST", country_id: -1}
def valid_attrs, do: @default_state_attrs
def create_state(country, state_attrs \\ @default_state_attrs) do
Nectar.State.changeset(%Nectar.State{}, Map.put(state_attrs, :country_id, country.id)) |> Repo.insert!
end
end
| 27.461538 | 106 | 0.736695 |
f7538f77ee76ed28859ee7b2a78c30f7fa36bc38 | 899 | ex | Elixir | lib/level/schemas/open_invitation.ex | mindriot101/level | 0a2cbae151869c2d9b79b3bfb388f5d00739ae12 | [
"Apache-2.0"
] | 928 | 2018-04-03T16:18:11.000Z | 2019-09-09T17:59:55.000Z | lib/level/schemas/open_invitation.ex | mindriot101/level | 0a2cbae151869c2d9b79b3bfb388f5d00739ae12 | [
"Apache-2.0"
] | 74 | 2018-04-03T00:46:50.000Z | 2019-03-10T18:57:27.000Z | lib/level/schemas/open_invitation.ex | mindriot101/level | 0a2cbae151869c2d9b79b3bfb388f5d00739ae12 | [
"Apache-2.0"
] | 89 | 2018-04-03T17:33:20.000Z | 2019-08-19T03:40:20.000Z | defmodule Level.Schemas.OpenInvitation do
@moduledoc """
The OpenInvitation schema.
"""
use Ecto.Schema
import Ecto.Changeset
alias Level.Schemas.Space
@type t :: %__MODULE__{}
@primary_key {:id, :binary_id, autogenerate: true}
@foreign_key_type :binary_id
schema "open_invitations" do
field :state, :string, read_after_writes: true
field :token, :string
belongs_to :space, Space
timestamps()
end
@doc false
def create_changeset(struct, attrs \\ %{}) do
struct
|> cast(attrs, [:space_id, :token])
|> generate_token()
end
defp generate_token(changeset) do
token =
16
|> :crypto.strong_rand_bytes()
|> Base.encode16()
|> String.downcase()
put_change(changeset, :token, token)
end
end
defimpl Phoenix.Param, for: Level.Schemas.OpenInvitation do
def to_param(%{token: token}) do
token
end
end
| 19.12766 | 59 | 0.667408 |
f75391f0dd08cbe87e2530efe3bf3ca4bd5178f6 | 23,388 | exs | Elixir | installer/test/phx_new_umbrella_test.exs | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | 1 | 2019-07-15T21:58:09.000Z | 2019-07-15T21:58:09.000Z | installer/test/phx_new_umbrella_test.exs | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | null | null | null | installer/test/phx_new_umbrella_test.exs | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | null | null | null | Code.require_file "mix_helper.exs", __DIR__
defmodule Mix.Tasks.Phx.New.UmbrellaTest do
use ExUnit.Case, async: false
import MixHelper
@app "phx_umb"
setup config do
# The shell asks to install deps.
# We will politely say not.
decline_prompt()
{:ok, tmp_dir: to_string(config.test)}
end
defp decline_prompt do
send self(), {:mix_shell_input, :yes?, false}
end
defp root_path(app, path \\ "") do
Path.join(["#{app}_umbrella", path])
end
defp app_path(app, path) do
Path.join(["#{app}_umbrella/apps/#{app}", path])
end
defp web_path(app, path) do
Path.join(["#{app}_umbrella/apps/#{app}_web", path])
end
test "new with umbrella and defaults" do
in_tmp "new with umbrella and defaults", fn ->
Mix.Tasks.Phx.New.run([@app, "--umbrella"])
assert_file root_path(@app, "README.md")
assert_file root_path(@app, ".gitignore")
assert_file app_path(@app, "README.md")
assert_file app_path(@app, ".gitignore"), "#{@app}-*.tar"
assert_file web_path(@app, "README.md")
assert_file root_path(@app, "mix.exs"), fn file ->
assert file =~ "apps_path: \"apps\""
end
assert_file app_path(@app, "mix.exs"), fn file ->
assert file =~ "app: :phx_umb"
assert file =~ ~S{build_path: "../../_build"}
assert file =~ ~S{config_path: "../../config/config.exs"}
assert file =~ ~S{deps_path: "../../deps"}
assert file =~ ~S{lockfile: "../../mix.lock"}
end
assert_file root_path(@app, "config/config.exs"), fn file ->
assert file =~ ~S[import_config "../apps/*/config/config.exs"]
assert file =~ ~S[import_config "#{Mix.env()}.exs"]
assert file =~ "config :phoenix, :json_library, Jason"
end
assert_file app_path(@app, "config/config.exs"), fn file ->
assert file =~ "ecto_repos: [PhxUmb.Repo]"
refute file =~ "namespace"
refute file =~ "config :phx_blog_web, :generators"
end
assert_file web_path(@app, "config/config.exs"), fn file ->
assert file =~ "ecto_repos: [PhxUmb.Repo]"
assert file =~ ":phx_umb_web, PhxUmbWeb.Endpoint"
assert file =~ "generators: [context_app: :phx_umb]\n"
end
assert_file web_path(@app, "config/prod.exs"), fn file ->
assert file =~ "port: 80"
assert file =~ ":inet6"
end
assert_file app_path(@app, "lib/#{@app}/application.ex"), ~r/defmodule PhxUmb.Application do/
assert_file app_path(@app, "lib/#{@app}/application.ex"), ~r/PhxUmb.Repo/
assert_file app_path(@app, "lib/#{@app}.ex"), ~r/defmodule PhxUmb do/
assert_file app_path(@app, "mix.exs"), ~r/mod: {PhxUmb.Application, \[\]}/
assert_file app_path(@app, "test/test_helper.exs")
assert_file web_path(@app, "lib/#{@app}_web/application.ex"), ~r/defmodule PhxUmbWeb.Application do/
assert_file web_path(@app, "mix.exs"), fn file ->
assert file =~ "mod: {PhxUmbWeb.Application, []}"
assert file =~ "{:jason, \"~> 1.0\"}"
end
assert_file web_path(@app, "lib/#{@app}_web.ex"), fn file ->
assert file =~ "defmodule PhxUmbWeb do"
assert file =~ "use Phoenix.View, root: \"lib/phx_umb_web/templates\""
end
assert_file web_path(@app, "lib/#{@app}_web/endpoint.ex"), ~r/defmodule PhxUmbWeb.Endpoint do/
assert_file web_path(@app, "test/#{@app}_web/controllers/page_controller_test.exs")
assert_file web_path(@app, "test/#{@app}_web/views/page_view_test.exs")
assert_file web_path(@app, "test/#{@app}_web/views/error_view_test.exs")
assert_file web_path(@app, "test/#{@app}_web/views/layout_view_test.exs")
assert_file web_path(@app, "test/support/conn_case.ex")
assert_file web_path(@app, "test/test_helper.exs")
assert_file web_path(@app, "lib/#{@app}_web/controllers/page_controller.ex"),
~r/defmodule PhxUmbWeb.PageController/
assert_file web_path(@app, "lib/#{@app}_web/views/page_view.ex"),
~r/defmodule PhxUmbWeb.PageView/
assert_file web_path(@app, "lib/#{@app}_web/router.ex"), "defmodule PhxUmbWeb.Router"
assert_file web_path(@app, "lib/#{@app}_web/templates/layout/app.html.eex"),
"<title>PhxUmb · Phoenix Framework</title>"
assert_file web_path(@app, "test/#{@app}_web/views/page_view_test.exs"),
"defmodule PhxUmbWeb.PageViewTest"
# webpack
assert_file web_path(@app, ".gitignore"), "/assets/node_modules/"
assert_file web_path(@app, ".gitignore"), "#{@app}_web-*.tar"
assert_file( web_path(@app, ".gitignore"), ~r/\n$/)
assert_file web_path(@app, "assets/webpack.config.js"), "js/app.js"
assert_file web_path(@app, "assets/.babelrc"), "env"
assert_file web_path(@app, "config/dev.exs"), fn file ->
assert file =~ "watchers: [node:"
assert file =~ "lib/#{@app}_web/views/.*(ex)"
assert file =~ "lib/#{@app}_web/templates/.*(eex)"
end
assert_file web_path(@app, "assets/static/favicon.ico")
assert_file web_path(@app, "assets/static/images/phoenix.png")
assert_file web_path(@app, "assets/css/app.css")
assert_file web_path(@app, "assets/js/app.js"),
~s[import socket from "./socket"]
assert_file web_path(@app, "assets/js/socket.js"),
~s[import {Socket} from "phoenix"]
assert_file web_path(@app, "assets/package.json"), fn file ->
assert file =~ ~s["file:../../../deps/phoenix"]
assert file =~ ~s["file:../../../deps/phoenix_html"]
end
refute File.exists?(web_path(@app, "priv/static/css/app.css"))
refute File.exists?(web_path(@app, "priv/static/js/phoenix.js"))
refute File.exists?(web_path(@app, "priv/static/js/app.js"))
assert File.exists?(web_path(@app, "assets/vendor"))
# web deps
assert_file web_path(@app, "mix.exs"), fn file ->
assert file =~ "{:phx_umb, in_umbrella: true}"
assert file =~ "{:phoenix,"
assert file =~ "{:phoenix_pubsub,"
assert file =~ "{:gettext,"
assert file =~ "{:cowboy,"
end
# app deps
assert_file web_path(@app, "mix.exs"), fn file ->
assert file =~ "{:phoenix_ecto,"
end
# Ecto
config = ~r/config :phx_umb, PhxUmb.Repo,/
assert_file app_path(@app, "mix.exs"), fn file ->
assert file =~ "aliases: aliases()"
assert file =~ "ecto.setup"
assert file =~ "ecto.reset"
end
assert_file app_path(@app, "config/dev.exs"), config
assert_file app_path(@app, "config/test.exs"), config
assert_file app_path(@app, "config/prod.secret.exs"), config
assert_file app_path(@app, "lib/#{@app}/repo.ex"), ~r"defmodule PhxUmb.Repo"
assert_file app_path(@app, "priv/repo/seeds.exs"), ~r"PhxUmb.Repo.insert!"
assert_file app_path(@app, "test/support/data_case.ex"), ~r"defmodule PhxUmb.DataCase"
# 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_umb"
assert msg =~ "$ mix deps.get"
assert_received {:mix_shell, :info, ["Then configure your database in apps/phx_umb/config/dev.exs" <> _]}
assert_received {:mix_shell, :info, ["Start your Phoenix app" <> _]}
# Channels
assert File.exists?(web_path(@app, "/lib/#{@app}_web/channels"))
assert_file web_path(@app, "lib/#{@app}_web/channels/user_socket.ex"), ~r"defmodule PhxUmbWeb.UserSocket"
assert_file web_path(@app, "lib/#{@app}_web/endpoint.ex"), ~r"socket \"/socket\", PhxUmbWeb.UserSocket"
# Gettext
assert_file web_path(@app, "lib/#{@app}_web/gettext.ex"), ~r"defmodule PhxUmbWeb.Gettext"
assert File.exists?(web_path(@app, "priv/gettext/errors.pot"))
assert File.exists?(web_path(@app, "priv/gettext/en/LC_MESSAGES/errors.po"))
end
end
test "new without defaults" do
in_tmp "new without defaults", fn ->
Mix.Tasks.Phx.New.run([@app, "--umbrella", "--no-html", "--no-webpack", "--no-ecto"])
# No webpack
refute File.read!(web_path(@app, ".gitignore")) |> String.contains?("/assets/node_modules/")
assert_file( web_path(@app, ".gitignore"), ~r/\n$/)
assert_file web_path(@app, "config/dev.exs"), ~r/watchers: \[\]/
# No webpack & No HTML
refute_file web_path(@app, "priv/static/css/app.css")
refute_file web_path(@app, "priv/static/favicon.ico")
refute_file web_path(@app, "priv/static/images/phoenix.png")
refute_file web_path(@app, "priv/static/js/phoenix.js")
refute_file web_path(@app, "priv/static/js/app.js")
# No Ecto
config = ~r/config :phx_umb, PhxUmb.Repo,/
refute File.exists?(app_path(@app, "lib/#{@app}_web/repo.ex"))
assert_file app_path(@app, "mix.exs"), &refute(&1 =~ ~r":phoenix_ecto")
assert_file app_path(@app, "config/config.exs"), fn file ->
refute file =~ "config :phx_blog_web, :generators"
refute file =~ "ecto_repos:"
refute file =~ "config :ecto, :json_library, Jason"
end
assert_file web_path(@app, "config/config.exs"), fn file ->
refute file =~ "config :phx_blog_web, :generators"
end
assert_file web_path(@app, "config/dev.exs"), fn file ->
refute file =~ config
end
assert_file web_path(@app, "config/test.exs"), &refute(&1 =~ config)
assert_file web_path(@app, "config/prod.secret.exs"), &refute(&1 =~ config)
assert_file app_path(@app, "lib/#{@app}/application.ex"), ~r/Supervisor.start_link\(\[\]/
# No HTML
assert File.exists?(web_path(@app, "test/#{@app}_web/controllers"))
assert File.exists?(web_path(@app, "lib/#{@app}_web/controllers"))
assert File.exists?(web_path(@app, "lib/#{@app}_web/views"))
refute File.exists?(web_path(@app, "test/controllers/pager_controller_test.exs"))
refute File.exists?(web_path(@app, "test/views/layout_view_test.exs"))
refute File.exists?(web_path(@app, "test/views/page_view_test.exs"))
refute File.exists?(web_path(@app, "lib/#{@app}_web/controllers/page_controller.ex"))
refute File.exists?(web_path(@app, "lib/#{@app}_web/templates/layout/app.html.eex"))
refute File.exists?(web_path(@app, "lib/#{@app}_web/templates/page/index.html.eex"))
refute File.exists?(web_path(@app, "lib/#{@app}_web/views/layout_view.ex"))
refute File.exists?(web_path(@app, "lib/#{@app}_web/views/page_view.ex"))
assert_file web_path(@app, "mix.exs"), &refute(&1 =~ ~r":phoenix_html")
assert_file web_path(@app, "mix.exs"), &refute(&1 =~ ~r":phoenix_live_reload")
assert_file web_path(@app, "lib/#{@app}_web/endpoint.ex"),
&refute(&1 =~ ~r"Phoenix.LiveReloader")
assert_file web_path(@app, "lib/#{@app}_web/endpoint.ex"),
&refute(&1 =~ ~r"Phoenix.LiveReloader.Socket")
assert_file web_path(@app, "lib/#{@app}_web/views/error_view.ex"), ~r".json"
assert_file web_path(@app, "lib/#{@app}_web/router.ex"), &refute(&1 =~ ~r"pipeline :browser")
end
end
test "new with no_webpack" do
in_tmp "new with no_webpack", fn ->
Mix.Tasks.Phx.New.run([@app, "--umbrella", "--no-webpack"])
assert_file web_path(@app, ".gitignore")
assert_file( web_path(@app, ".gitignore"), ~r/\n$/)
assert_file web_path(@app, "priv/static/css/app.css")
assert_file web_path(@app, "priv/static/favicon.ico")
assert_file web_path(@app, "priv/static/images/phoenix.png")
assert_file web_path(@app, "priv/static/js/phoenix.js")
assert_file web_path(@app, "priv/static/js/app.js")
end
end
test "new with binary_id" do
in_tmp "new with binary_id", fn ->
Mix.Tasks.Phx.New.run([@app, "--umbrella", "--binary-id"])
assert_file web_path(@app, "config/config.exs"), ~r/generators: \[context_app: :phx_umb, binary_id: true\]/
end
end
test "new with uppercase" do
in_tmp "new with uppercase", fn ->
Mix.Tasks.Phx.New.run(["phxUmb", "--umbrella"])
assert_file "phxUmb_umbrella/README.md"
assert_file "phxUmb_umbrella/apps/phxUmb/mix.exs", fn file ->
assert file =~ "app: :phxUmb"
end
assert_file "phxUmb_umbrella/apps/phxUmb_web/mix.exs", fn file ->
assert file =~ "app: :phxUmb_web"
end
assert_file "phxUmb_umbrella/apps/phxUmb/config/dev.exs", fn file ->
assert file =~ ~r/config :phxUmb, PhxUmb.Repo,/
assert file =~ "database: \"phxumb_dev\""
end
end
end
test "new with path, app and module" do
in_tmp "new with path, app and module", fn ->
project_path = Path.join(File.cwd!, "custom_path")
Mix.Tasks.Phx.New.run([project_path, "--umbrella", "--app", @app, "--module", "PhoteuxBlog"])
assert_file "custom_path_umbrella/apps/phx_umb/mix.exs", ~r/app: :phx_umb/
assert_file "custom_path_umbrella/apps/phx_umb_web/lib/phx_umb_web/endpoint.ex", ~r/app: :#{@app}_web/
assert_file "custom_path_umbrella/apps/phx_umb_web/config/config.exs", ~r/namespace: PhoteuxBlogWeb/
assert_file "custom_path_umbrella/apps/phx_umb_web/lib/#{@app}_web.ex", ~r/use Phoenix.Controller, namespace: PhoteuxBlogWeb/
assert_file "custom_path_umbrella/apps/phx_umb/lib/phx_umb/application.ex", ~r/defmodule PhoteuxBlog.Application/
assert_file "custom_path_umbrella/apps/phx_umb/mix.exs", ~r/mod: {PhoteuxBlog.Application, \[\]}/
assert_file "custom_path_umbrella/apps/phx_umb_web/lib/phx_umb_web/application.ex", ~r/defmodule PhoteuxBlogWeb.Application/
assert_file "custom_path_umbrella/apps/phx_umb_web/mix.exs", ~r/mod: {PhoteuxBlogWeb.Application, \[\]}/
assert_file "custom_path_umbrella/apps/phx_umb/config/config.exs", ~r/namespace: PhoteuxBlog/
end
end
test "new inside umbrella" do
in_tmp "new inside umbrella", fn ->
File.write! "mix.exs", MixHelper.umbrella_mixfile_contents()
File.mkdir! "apps"
File.cd! "apps", fn ->
assert_raise Mix.Error, "Unable to nest umbrella project within apps", fn ->
Mix.Tasks.Phx.New.run([@app, "--umbrella"])
end
end
end
end
test "new defaults to pg adapter" do
in_tmp "new defaults to pg adapter", fn ->
app = "custom_path"
project_path = Path.join(File.cwd!, app)
Mix.Tasks.Phx.New.run([project_path, "--umbrella"])
assert_file app_path(app, "mix.exs"), ":postgrex"
assert_file app_path(app, "config/dev.exs"), [~r/username: "postgres"/, ~r/password: "postgres"/, ~r/hostname: "localhost"/]
assert_file app_path(app, "config/test.exs"), [~r/username: "postgres"/, ~r/password: "postgres"/, ~r/hostname: "localhost"/]
assert_file app_path(app, "config/prod.secret.exs"), [~r/username: "postgres"/, ~r/password: "postgres"/]
assert_file app_path(app, "lib/custom_path/repo.ex"), "Ecto.Adapters.Postgres"
assert_file web_path(app, "test/support/conn_case.ex"), "Ecto.Adapters.SQL.Sandbox.checkout"
assert_file web_path(app, "test/support/channel_case.ex"), "Ecto.Adapters.SQL.Sandbox.checkout"
end
end
test "new with mysql adapter" do
in_tmp "new with mysql adapter", fn ->
app = "custom_path"
project_path = Path.join(File.cwd!, app)
Mix.Tasks.Phx.New.run([project_path, "--umbrella", "--database", "mysql"])
assert_file app_path(app, "mix.exs"), ":mariaex"
assert_file app_path(app, "config/dev.exs"), [~r/username: "root"/, ~r/password: ""/]
assert_file app_path(app, "config/test.exs"), [~r/username: "root"/, ~r/password: ""/]
assert_file app_path(app, "config/prod.secret.exs"), [~r/username: "root"/, ~r/password: ""/]
assert_file app_path(app, "lib/custom_path/repo.ex"), "Ecto.Adapters.MySQL"
assert_file web_path(app, "test/support/conn_case.ex"), "Ecto.Adapters.SQL.Sandbox.checkout"
assert_file web_path(app, "test/support/channel_case.ex"), "Ecto.Adapters.SQL.Sandbox.checkout"
end
end
test "new with invalid database adapter" do
in_tmp "new with invalid database adapter", fn ->
project_path = Path.join(File.cwd!, "custom_path")
assert_raise Mix.Error, ~s(Unknown database "invalid"), fn ->
Mix.Tasks.Phx.New.run([project_path, "--umbrella", "--database", "invalid"])
end
end
end
test "new with invalid args" do
assert_raise Mix.Error, ~r"Application name must start with a letter and ", fn ->
Mix.Tasks.Phx.New.run ["007invalid", "--umbrella"]
end
assert_raise Mix.Error, ~r"Application name must start with a letter and ", fn ->
Mix.Tasks.Phx.New.run ["valid1", "--app", "007invalid", "--umbrella"]
end
assert_raise Mix.Error, ~r"Module name must be a valid Elixir alias", fn ->
Mix.Tasks.Phx.New.run ["valid2", "--module", "not.valid", "--umbrella"]
end
assert_raise Mix.Error, ~r"Module name \w+ is already taken", fn ->
Mix.Tasks.Phx.New.run ["string", "--umbrella"]
end
assert_raise Mix.Error, ~r"Module name \w+ is already taken", fn ->
Mix.Tasks.Phx.New.run ["valid3", "--app", "mix", "--umbrella"]
end
assert_raise Mix.Error, ~r"Module name \w+ is already taken", fn ->
Mix.Tasks.Phx.New.run ["valid4", "--module", "String", "--umbrella"]
end
end
test "invalid options" do
assert_raise Mix.Error, ~r/Invalid option: -d/, fn ->
Mix.Tasks.Phx.New.run(["valid5", "-database", "mysql", "--umbrella"])
end
end
describe "ecto task" do
test "can only be run within an umbrella app dir", %{tmp_dir: tmp_dir} do
in_tmp tmp_dir, fn ->
cwd = File.cwd!()
umbrella_path = root_path(@app)
Mix.Tasks.Phx.New.run([@app, "--umbrella"])
flush()
for dir <- [cwd, umbrella_path] do
File.cd!(dir, fn ->
assert_raise Mix.Error, ~r"The ecto task can only be run within an umbrella's apps directory", fn ->
Mix.Tasks.Phx.New.Ecto.run(["valid"])
end
end)
end
end
end
end
describe "web task" do
test "can only be run within an umbrella app dir", %{tmp_dir: tmp_dir} do
in_tmp tmp_dir, fn ->
cwd = File.cwd!()
umbrella_path = root_path(@app)
Mix.Tasks.Phx.New.run([@app, "--umbrella"])
flush()
for dir <- [cwd, umbrella_path] do
File.cd!(dir, 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(["valid"])
end
end)
end
end
end
test "generates web-only files", %{tmp_dir: tmp_dir} do
in_tmp tmp_dir, fn ->
umbrella_path = root_path(@app)
Mix.Tasks.Phx.New.run([@app, "--umbrella"])
flush()
File.cd!(Path.join(umbrella_path, "apps"))
decline_prompt()
Mix.Tasks.Phx.New.Web.run(["another"])
assert_file "another/README.md"
assert_file "another/mix.exs", fn file ->
assert file =~ "app: :another"
assert file =~ "deps_path: \"../../deps\""
assert file =~ "lockfile: \"../../mix.lock\""
end
assert_file "another/config/config.exs", fn file ->
assert file =~ "ecto_repos: [Another.Repo]"
end
assert_file "another/config/prod.exs", fn file ->
assert file =~ "port: 80"
assert file =~ ":inet6"
end
assert_file "another/lib/another/application.ex", ~r/defmodule Another.Application do/
assert_file "another/mix.exs", ~r/mod: {Another.Application, \[\]}/
assert_file "another/lib/another.ex", ~r/defmodule Another do/
assert_file "another/lib/another/endpoint.ex", ~r/defmodule Another.Endpoint do/
assert_file "another/test/another/controllers/page_controller_test.exs"
assert_file "another/test/another/views/page_view_test.exs"
assert_file "another/test/another/views/error_view_test.exs"
assert_file "another/test/another/views/layout_view_test.exs"
assert_file "another/test/support/conn_case.ex"
assert_file "another/test/test_helper.exs"
assert_file "another/lib/another/controllers/page_controller.ex",
~r/defmodule Another.PageController/
assert_file "another/lib/another/views/page_view.ex",
~r/defmodule Another.PageView/
assert_file "another/lib/another/router.ex", "defmodule Another.Router"
assert_file "another/lib/another.ex", "defmodule Another"
assert_file "another/lib/another/templates/layout/app.html.eex",
"<title>Another · Phoenix Framework</title>"
# webpack
assert_file "another/.gitignore", "/assets/node_modules"
assert_file "another/.gitignore", ~r/\n$/
assert_file "another/assets/webpack.config.js", "js/app.js"
assert_file "another/assets/.babelrc", "env"
assert_file "another/config/dev.exs", "watchers: [node:"
assert_file "another/assets/static/favicon.ico"
assert_file "another/assets/static/images/phoenix.png"
assert_file "another/assets/css/app.css"
assert_file "another/assets/js/app.js",
~s[import socket from "./socket"]
assert_file "another/assets/js/socket.js",
~s[import {Socket} from "phoenix"]
assert_file "another/assets/package.json", fn file ->
assert file =~ ~s["file:../../../deps/phoenix"]
assert file =~ ~s["file:../../../deps/phoenix_html"]
end
refute File.exists? "another/priv/static/css/app.css"
refute File.exists? "another/priv/static/js/phoenix.js"
refute File.exists? "another/priv/static/js/app.js"
assert File.exists?("another/assets/vendor")
# Ecto
assert_file "another/mix.exs", fn file ->
assert file =~ "{:phoenix_ecto,"
end
assert_file "another/lib/another.ex", ~r"defmodule Another"
refute_file "another/lib/another/repo.ex"
refute_file "another/priv/repo/seeds.exs"
refute_file "another/test/support/data_case.ex"
# 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 another"
assert msg =~ "$ mix deps.get"
refute_received {:mix_shell, :info, ["Then configure your database" <> _]}
assert_received {:mix_shell, :info, ["Start your Phoenix app" <> _]}
# Channels
assert File.exists?("another/lib/another/channels")
assert_file "another/lib/another/channels/user_socket.ex", ~r"defmodule Another.UserSocket"
assert_file "another/lib/another/endpoint.ex", ~r"socket \"/socket\", Another.UserSocket"
# Gettext
assert_file "another/lib/another/gettext.ex", ~r"defmodule Another.Gettext"
assert File.exists?("another/priv/gettext/errors.pot")
assert File.exists?("another/priv/gettext/en/LC_MESSAGES/errors.po")
end
end
end
end
| 42.601093 | 131 | 0.631178 |
f753bee948f8b83476d23d1b98204c989cea18bc | 120 | exs | Elixir | apps/evm/test/evm/mock/mock_block_header_info_test.exs | wolflee/mana | db66dac85addfaad98d40da5bd4082b3a0198bb1 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 152 | 2018-10-27T04:52:03.000Z | 2022-03-26T10:34:00.000Z | apps/evm/test/evm/mock/mock_block_header_info_test.exs | wolflee/mana | db66dac85addfaad98d40da5bd4082b3a0198bb1 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 270 | 2018-04-14T07:34:57.000Z | 2018-10-25T18:10:45.000Z | apps/evm/test/evm/mock/mock_block_header_info_test.exs | 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 EVM.Mock.MockBlockHeaderInfoTest do
use ExUnit.Case, async: true
doctest EVM.Mock.MockBlockHeaderInfo
end
| 24 | 45 | 0.825 |
f753ca71086843191baa53de238f7b989ed4e788 | 10,869 | exs | Elixir | test/livebook/notebook_test.exs | howard0su/livebook | 6b7825871338af0ec3f4196ec3e17d2670e6a92c | [
"Apache-2.0"
] | null | null | null | test/livebook/notebook_test.exs | howard0su/livebook | 6b7825871338af0ec3f4196ec3e17d2670e6a92c | [
"Apache-2.0"
] | null | null | null | test/livebook/notebook_test.exs | howard0su/livebook | 6b7825871338af0ec3f4196ec3e17d2670e6a92c | [
"Apache-2.0"
] | null | null | null | defmodule Livebook.NotebookTest do
use ExUnit.Case, async: true
alias Livebook.Notebook
alias Livebook.Notebook.{Section, Cell}
describe "fetch_cell_sibling/3" do
test "returns error given invalid cell id" do
notebook = Notebook.new()
assert :error == Notebook.fetch_cell_sibling(notebook, "1", 0)
end
test "returns sibling cell if there is one at the given offset" do
cell1 = Cell.new(:markdown)
cell2 = Cell.new(:markdown)
cell3 = Cell.new(:markdown)
cell4 = Cell.new(:markdown)
notebook = %{
Notebook.new()
| sections: [
%{Section.new() | cells: [cell1, cell2, cell3, cell4]}
]
}
assert {:ok, cell1} == Notebook.fetch_cell_sibling(notebook, cell2.id, -1)
assert {:ok, cell3} == Notebook.fetch_cell_sibling(notebook, cell2.id, 1)
assert {:ok, cell4} == Notebook.fetch_cell_sibling(notebook, cell2.id, 2)
end
test "returns error if the offset is out of range" do
cell1 = Cell.new(:markdown)
cell2 = Cell.new(:markdown)
notebook = %{
Notebook.new()
| sections: [
%{Section.new() | cells: [cell1, cell2]}
]
}
assert :error == Notebook.fetch_cell_sibling(notebook, cell2.id, -2)
assert :error == Notebook.fetch_cell_sibling(notebook, cell2.id, 1)
assert :error == Notebook.fetch_cell_sibling(notebook, cell2.id, 2)
end
end
describe "move_cell/3" do
test "preserves empty sections" do
cell1 = Cell.new(:markdown)
notebook = %{
Notebook.new()
| sections: [
%{Section.new() | cells: [cell1]},
%{Section.new() | cells: []}
]
}
new_notebook = Notebook.move_cell(notebook, cell1.id, 1)
assert %{sections: [%{cells: []}, %{cells: [^cell1]}]} = new_notebook
end
end
describe "cell_dependency_graph/1" do
test "computes a linear graph for regular sections" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:markdown) | id: "c1"},
%{Cell.new(:code) | id: "c2"}
]
},
%{
Section.new()
| id: "s2",
cells: [
%{Cell.new(:markdown) | id: "c3"},
%{Cell.new(:code) | id: "c4"}
]
}
]
}
assert Notebook.cell_dependency_graph(notebook) == %{
"c4" => "c3",
"c3" => "c2",
"c2" => "c1",
"c1" => nil
}
end
test "ignores empty sections" do
notebook = %{
Notebook.new()
| sections: [
%{Section.new() | id: "s1", cells: [%{Cell.new(:code) | id: "c1"}]},
%{Section.new() | id: "s2", cells: []},
%{Section.new() | id: "s3", cells: [%{Cell.new(:code) | id: "c2"}]}
]
}
assert Notebook.cell_dependency_graph(notebook) == %{
"c2" => "c1",
"c1" => nil
}
end
test "computes a non-linear graph if there are branching sections" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1"},
%{Cell.new(:code) | id: "c2"}
]
},
%{
Section.new()
| id: "s2",
parent_id: "s1",
cells: [
%{Cell.new(:code) | id: "c3"},
%{Cell.new(:code) | id: "c4"}
]
},
%{
Section.new()
| id: "s3",
cells: [
%{Cell.new(:code) | id: "c5"},
%{Cell.new(:code) | id: "c6"}
]
}
]
}
assert Notebook.cell_dependency_graph(notebook) == %{
"c6" => "c5",
"c5" => "c2",
"c4" => "c3",
"c3" => "c2",
"c2" => "c1",
"c1" => nil
}
end
test "handles branching sections pointing to empty sections" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1"}
]
},
%{
Section.new()
| id: "s2",
cells: []
},
%{
Section.new()
| id: "s3",
parent_id: "s2",
cells: [
%{Cell.new(:code) | id: "c2"}
]
}
]
}
assert Notebook.cell_dependency_graph(notebook) == %{
"c2" => "c1",
"c1" => nil
}
end
test "handles branching sections placed further in the notebook" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1"}
]
},
%{
Section.new()
| id: "s2",
cells: [
%{Cell.new(:code) | id: "c2"}
]
},
%{
Section.new()
| id: "s3",
parent_id: "s1",
cells: [
%{Cell.new(:code) | id: "c3"}
]
},
%{
Section.new()
| id: "s4",
cells: [
%{Cell.new(:code) | id: "c4"}
]
}
]
}
assert Notebook.cell_dependency_graph(notebook) == %{
"c4" => "c2",
"c3" => "c1",
"c2" => "c1",
"c1" => nil
}
end
test "given :cell_filter option, includes only the matching cells" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1"},
%{Cell.new(:markdown) | id: "c2"},
%{Cell.new(:code) | id: "c3"}
]
}
]
}
assert Notebook.cell_dependency_graph(notebook, cell_filter: &Cell.evaluable?/1) ==
%{
"c3" => "c1",
"c1" => nil
}
end
end
describe "find_asset_info/2" do
test "returns asset info matching the given type if found" do
assets_info = %{archive: "/path/to/archive.tar.gz", hash: "abcd", js_path: "main.js"}
js_info = %{js_view: %{assets: assets_info}}
output = {:js, js_info}
notebook = %{
Notebook.new()
| sections: [%{Section.new() | cells: [%{Cell.new(:code) | outputs: [{0, output}]}]}]
}
assert ^assets_info = Notebook.find_asset_info(notebook, "abcd")
end
test "returns nil if no matching info is found" do
notebook = Notebook.new()
assert Notebook.find_asset_info(notebook, "abcd") == nil
end
end
describe "add_cell_output/3" do
test "merges consecutive stdout results" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1", outputs: [{0, {:stdout, "Hola"}}]}
]
}
],
output_counter: 1
}
assert %{
sections: [
%{
cells: [%{outputs: [{0, {:stdout, "Hola amigo!"}}]}]
}
]
} = Notebook.add_cell_output(notebook, "c1", {:stdout, " amigo!"})
end
test "normalizes individual stdout results to respect CR" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1", outputs: []}
]
}
],
output_counter: 0
}
assert %{
sections: [
%{
cells: [%{outputs: [{0, {:stdout, "Hey"}}]}]
}
]
} = Notebook.add_cell_output(notebook, "c1", {:stdout, "Hola\rHey"})
end
test "normalizes consecutive stdout results to respect CR" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{Cell.new(:code) | id: "c1", outputs: [{0, {:stdout, "Hola"}}]}
]
}
],
output_counter: 1
}
assert %{
sections: [
%{
cells: [%{outputs: [{0, {:stdout, "amigo!\r"}}]}]
}
]
} = Notebook.add_cell_output(notebook, "c1", {:stdout, "\ramigo!\r"})
end
test "updates existing frames on frame update ouptut" do
notebook = %{
Notebook.new()
| sections: [
%{
Section.new()
| id: "s1",
cells: [
%{
Cell.new(:code)
| id: "c1",
outputs: [{0, {:frame, [], %{ref: "1", type: :default}}}]
},
%{
Cell.new(:code)
| id: "c2",
outputs: [{1, {:frame, [], %{ref: "1", type: :default}}}]
}
]
}
],
output_counter: 2
}
assert %{
sections: [
%{
cells: [
%{
outputs: [
{0, {:frame, [{2, {:text, "hola"}}], %{ref: "1", type: :default}}}
]
},
%{
outputs: [
{1, {:frame, [{3, {:text, "hola"}}], %{ref: "1", type: :default}}}
]
}
]
}
]
} =
Notebook.add_cell_output(
notebook,
"c2",
{:frame, [{:text, "hola"}], %{ref: "1", type: :replace}}
)
end
end
end
| 27.104738 | 93 | 0.379244 |
f753ecd71d7e94d37416ad19ee3ecab836aac965 | 1,636 | exs | Elixir | test/translator_test.exs | rktjmp/structured_console | 9befb1ce73ad60a5e3dafe104a5075cef7c85281 | [
"MIT"
] | null | null | null | test/translator_test.exs | rktjmp/structured_console | 9befb1ce73ad60a5e3dafe104a5075cef7c85281 | [
"MIT"
] | null | null | null | test/translator_test.exs | rktjmp/structured_console | 9befb1ce73ad60a5e3dafe104a5075cef7c85281 | [
"MIT"
] | null | null | null | defmodule StructuredConsole.TranslatorTest do
use ExUnit.Case
import ExUnit.CaptureLog
alias StructuredConsole.Translator
doctest StructuredConsole.Translator
describe "signature pattern match" do
test "keyword data" do
assert {:ok, _} = Translator.translate(:any, :any, :report, {:logger, [key: :value]})
end
test "map data" do
assert {:ok, _} = Translator.translate(:any, :any, :report, {:logger, %{key: :value}})
end
test "anything else" do
assert :none = Translator.translate(:any, :any, :report, {:logger, [:key, :value]})
assert :none = Translator.translate(:any, :any, :report, {:report, [key: :value]})
assert :none = Translator.translate(:any, :any, :something, {:report, [key: :value]})
assert :none = Translator.translate(:any, :any, :something, "a string")
end
end
test "message prefixing" do
{:ok, message} = Translator.translate(:any, :any, :report, {:logger, %{key: :value}})
# the prefix is shared between Translator and Formatter, but needs to be
# used in pattern matching, so it can't be wrapped in a function,
# so it is hard coded in this test, which will fail if you change it,
# which should remind you to fix it in Formatter too.
assert String.starts_with?(message, "__is_logfmt__")
end
describe "error reporting" do
test "logfmt.encode errors are caught and logged" do
assert capture_log(fn ->
# still returns a loggable line
{:ok, _} = Translator.translate(:any, :any, :report, {:logger, %{a: %{b: 1}}})
end) =~ "failed to encode"
end
end
end
| 38.046512 | 93 | 0.648533 |
f753f28c9acded8b5c4dcf9f1236c72618a507f4 | 1,193 | ex | Elixir | lib/loaded_bike/web/channels/user_socket.ex | GBH/pedal | a2d68c3561f186ee3017a21b4170127b1625e18d | [
"MIT"
] | 48 | 2017-04-25T16:02:08.000Z | 2021-01-23T01:57:29.000Z | lib/loaded_bike/web/channels/user_socket.ex | GBH/pedal | a2d68c3561f186ee3017a21b4170127b1625e18d | [
"MIT"
] | 5 | 2018-03-09T20:17:55.000Z | 2018-07-23T16:29:21.000Z | lib/loaded_bike/web/channels/user_socket.ex | GBH/pedal | a2d68c3561f186ee3017a21b4170127b1625e18d | [
"MIT"
] | 4 | 2017-05-21T14:38:38.000Z | 2017-12-29T11:09:54.000Z | defmodule LoadedBike.UserSocket do
use Phoenix.Socket
use Drab.Socket
## Channels
# channel "room:*", LoadedBike.RoomChannel
## Transports
transport :websocket, Phoenix.Transports.WebSocket
# transport :longpoll, Phoenix.Transports.LongPoll
# Socket params are passed from the client and can
# be used to verify and authenticate a user. After
# verification, you can put default assigns into
# the socket that will be set for all channels, ie
#
# {:ok, assign(socket, :user_id, verified_user_id)}
#
# To deny connection, return `:error`.
#
# See `Phoenix.Token` documentation for examples in
# performing token verification on connect.
def connect(_params, socket) do
{:ok, socket}
end
# Socket id's are topics that allow you to identify all sockets for a given user:
#
# def id(socket), do: "users_socket:#{socket.assigns.user_id}"
#
# Would allow you to broadcast a "disconnect" event and terminate
# all active sockets and channels for a given user:
#
# LoadedBike.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
#
# Returning `nil` makes this socket anonymous.
def id(_socket), do: nil
end
| 30.589744 | 83 | 0.704107 |
f753f32f336c27efa04177303d7cd443af361cb2 | 162 | exs | Elixir | test/fixtures/parser/safety_assured_create_index.exs | maximemenager/strong_migrations | b7e091d2cfed73098d3bf683c7ce5c8ceee3159b | [
"MIT"
] | 23 | 2021-10-29T19:58:35.000Z | 2021-11-13T21:42:45.000Z | test/fixtures/parser/safety_assured_create_index.exs | maximemenager/strong_migrations | b7e091d2cfed73098d3bf683c7ce5c8ceee3159b | [
"MIT"
] | 1 | 2022-02-07T12:15:16.000Z | 2022-02-07T12:15:16.000Z | test/fixtures/parser/safety_assured_create_index.exs | surgeventures/strong_migrations | 3c82e34a6e7a372c6de17ba7a0b07da7664baa26 | [
"MIT"
] | 3 | 2021-10-31T02:14:10.000Z | 2021-11-09T08:07:22.000Z | defmodule SafetyAssuredCreateIndex do
@moduledoc false
use StrongMigrations
def change do
safety_assured(do: create(index(:users, :email)))
end
end
| 16.2 | 53 | 0.753086 |
f753f39347cdc712d15a5719db60132cc1ee2d1e | 1,008 | ex | Elixir | lib/sobelow/meta_log.ex | juancgalvis/sobelow | 9ae3874c26ab7cfa6c8a8517ccd02af98e187585 | [
"Apache-2.0"
] | 1,305 | 2017-05-12T21:09:40.000Z | 2022-03-31T04:31:49.000Z | lib/sobelow/meta_log.ex | juancgalvis/sobelow | 9ae3874c26ab7cfa6c8a8517ccd02af98e187585 | [
"Apache-2.0"
] | 95 | 2017-05-15T09:45:41.000Z | 2022-03-23T03:35:48.000Z | lib/sobelow/meta_log.ex | juancgalvis/sobelow | 9ae3874c26ab7cfa6c8a8517ccd02af98e187585 | [
"Apache-2.0"
] | 86 | 2017-05-15T20:18:59.000Z | 2022-02-11T22:10:34.000Z | defmodule Sobelow.MetaLog do
use GenServer
alias Sobelow.Parse
def start_link() do
GenServer.start_link(__MODULE__, :ok, name: __MODULE__)
end
def add_templates(templates) do
GenServer.cast(__MODULE__, {:add, templates})
end
def get_templates() do
GenServer.call(__MODULE__, :get_templates)
end
def delete_raw(var, template_path) do
GenServer.cast(__MODULE__, {:delete_raw, {var, template_path}})
end
def init(:ok) do
{:ok, %{:templates => %{}}}
end
def handle_cast({:add, templates}, log) do
{:noreply, Map.put(log, :templates, templates)}
end
def handle_cast({:delete_raw, {var, template_path}}, log) do
raw_funs =
get_in(log, [:templates, template_path, :raw])
|> Enum.reject(fn raw ->
Enum.member?(Parse.get_template_vars([raw]), var)
end)
{:noreply, put_in(log, [:templates, template_path, :raw], raw_funs)}
end
def handle_call(:get_templates, _from, log) do
{:reply, log.templates, log}
end
end
| 23.44186 | 72 | 0.667659 |
f75419582c61c948420dd1cb10aa71403a26e904 | 2,729 | ex | Elixir | lib/bi_web/channels/presence.ex | xuyizhe/phoenix-sample | 9f5a79d9da13858a62d0d9316f799e8cf89d0038 | [
"MIT"
] | null | null | null | lib/bi_web/channels/presence.ex | xuyizhe/phoenix-sample | 9f5a79d9da13858a62d0d9316f799e8cf89d0038 | [
"MIT"
] | null | null | null | lib/bi_web/channels/presence.ex | xuyizhe/phoenix-sample | 9f5a79d9da13858a62d0d9316f799e8cf89d0038 | [
"MIT"
] | null | null | null | defmodule BiWeb.Presence do
@moduledoc """
Provides presence tracking to channels and processes.
See the [`Phoenix.Presence`](http://hexdocs.pm/phoenix/Phoenix.Presence.html)
docs for more details.
## Usage
Presences can be tracked in your channel after joining:
defmodule Bi.MyChannel do
use BiWeb, :channel
alias Bi.Presence
def join("some:topic", _params, socket) do
send(self, :after_join)
{:ok, assign(socket, :user_id, ...)}
end
def handle_info(:after_join, socket) do
push socket, "presence_state", Presence.list(socket)
{:ok, _} = Presence.track(socket, socket.assigns.user_id, %{
online_at: inspect(System.system_time(:seconds))
})
{:noreply, socket}
end
end
In the example above, `Presence.track` is used to register this
channel's process as a presence for the socket's user ID, with
a map of metadata. Next, the current presence list for
the socket's topic is pushed to the client as a `"presence_state"` event.
Finally, a diff of presence join and leave events will be sent to the
client as they happen in real-time with the "presence_diff" event.
See `Phoenix.Presence.list/2` for details on the presence datastructure.
## Fetching Presence Information
The `fetch/2` callback is triggered when using `list/1`
and serves as a mechanism to fetch presence information a single time,
before broadcasting the information to all channel subscribers.
This prevents N query problems and gives you a single place to group
isolated data fetching to extend presence metadata.
The function receives a topic and map of presences and must return a
map of data matching the Presence datastructure:
%{"123" => %{metas: [%{status: "away", phx_ref: ...}],
"456" => %{metas: [%{status: "online", phx_ref: ...}]}
The `:metas` key must be kept, but you can extend the map of information
to include any additional information. For example:
def fetch(_topic, entries) do
users = entries |> Map.keys() |> Accounts.get_users_map(entries)
# => %{"123" => %{name: "User 123"}, "456" => %{name: nil}}
for {key, %{metas: metas}} <- entries, into: %{} do
{key, %{metas: metas, user: users[key]}}
end
end
The function above fetches all users from the database who
have registered presences for the given topic. The fetched
information is then extended with a `:user` key of the user's
information, while maintaining the required `:metas` field from the
original presence data.
"""
use Phoenix.Presence, otp_app: :bi,
pubsub_server: Bi.PubSub
end
| 36.878378 | 79 | 0.669476 |
f75428619b67319602c460700e06a44372bf1e2f | 65 | ex | Elixir | lib/pbbuilder_web/views/page_view.ex | StBarCo/pbbuilder | 9d6eb47d6137a6a16cd746a0c1418493f94043d5 | [
"MIT"
] | null | null | null | lib/pbbuilder_web/views/page_view.ex | StBarCo/pbbuilder | 9d6eb47d6137a6a16cd746a0c1418493f94043d5 | [
"MIT"
] | null | null | null | lib/pbbuilder_web/views/page_view.ex | StBarCo/pbbuilder | 9d6eb47d6137a6a16cd746a0c1418493f94043d5 | [
"MIT"
] | null | null | null | defmodule PbbuilderWeb.PageView do
use PbbuilderWeb, :view
end
| 16.25 | 34 | 0.815385 |
f7543c8fb0b60fb3d4264995bcff48e1d5f00fa7 | 2,655 | ex | Elixir | apps/ex_wire/lib/ex_wire/packet.ex | atoulme/ethereum | cebb0756c7292ac266236636d2ab5705cb40a52e | [
"MIT"
] | 14 | 2017-08-21T06:14:49.000Z | 2020-05-15T12:00:52.000Z | apps/ex_wire/lib/ex_wire/packet.ex | atoulme/ethereum | cebb0756c7292ac266236636d2ab5705cb40a52e | [
"MIT"
] | 7 | 2017-08-11T07:50:14.000Z | 2018-08-23T20:42:50.000Z | apps/ex_wire/lib/ex_wire/packet.ex | atoulme/ethereum | cebb0756c7292ac266236636d2ab5705cb40a52e | [
"MIT"
] | 3 | 2017-08-20T17:56:41.000Z | 2018-08-21T00:36:10.000Z | defmodule ExWire.Packet do
@moduledoc """
Packets handle serializing and deserializing framed packet data from
the DevP2P and Eth Wire Protocols. They also handle how to respond
to incoming packets.
"""
alias ExWire.Packet
@type packet :: %{}
@type block_identifier :: binary() | integer()
@type block_hash :: {binary(), integer()}
@callback serialize(packet) :: ExRLP.t
@callback deserialize(ExRLP.t) :: packet
@type handle_response :: :ok | :activate | :peer_disconnect | {:disconnect, atom()} | {:send, struct()}
@callback handle(packet) :: handle_response
@packet_types %{
0x00 => Packet.Hello,
0x01 => Packet.Disconnect,
0x02 => Packet.Ping,
0x03 => Packet.Pong,
### Ethereum Sub-protocol
0x10 => Packet.Status,
0x11 => Packet.NewBlockHashes, # New model syncing (PV62)
0x12 => Packet.Transactions,
0x13 => Packet.GetBlockHeaders, # New model syncing (PV62)
0x14 => Packet.BlockHeaders, # New model syncing (PV62)
0x15 => Packet.GetBlockBodies, # New model syncing (PV62)
0x16 => Packet.BlockBodies, # New model syncing (PV62)
0x17 => Packet.NewBlock,
### Fast synchronization (PV63)
# 0x1d => Packet.GetNodeData,
# 0x1e => Packet.NodeData,
# 0x1f => Packet.GetReceipts,
# 0x20 => Packet.Receipts
}
@packet_types_inverted (for {k, v} <- @packet_types, do: {v, k}) |> Enum.into(%{})
@doc """
Returns the module which contains functions to
`serialize/1`, `deserialize/1` and `handle/1` the given `packet_type`.
## Examples
iex> ExWire.Packet.get_packet_mod(0x00)
{:ok, ExWire.Packet.Hello}
iex> ExWire.Packet.get_packet_mod(0x10)
{:ok, ExWire.Packet.Status}
iex> ExWire.Packet.get_packet_mod(0xFF)
:unknown_packet_type
"""
@spec get_packet_mod(integer()) :: {:ok, module()} | :unknown_packet_type
def get_packet_mod(packet_type) do
case @packet_types[packet_type] do
nil -> :unknown_packet_type
packet_type -> {:ok, packet_type}
end
end
@doc """
Returns the eth id of the given packet based on the struct.
## Examples
iex> ExWire.Packet.get_packet_type(%ExWire.Packet.Hello{})
{:ok, 0x00}
iex> ExWire.Packet.get_packet_type(%ExWire.Packet.Status{})
{:ok, 0x10}
iex> ExWire.Packet.get_packet_type(%ExWire.Struct.Neighbour{})
:unknown_packet
"""
@spec get_packet_type(struct()) :: {:ok, integer()} | :unknown_packet
def get_packet_type(_packet=%{__struct__: packet_struct}) do
case @packet_types_inverted[packet_struct] do
nil -> :unknown_packet
packet_type -> {:ok, packet_type}
end
end
end | 30.170455 | 105 | 0.664783 |
f75482eebb26fccf682d287ee7915905c3fc1251 | 1,272 | ex | Elixir | apps/studio/lib/studio/painter/pycasso.ex | danmarcab/deep_painting | 860c7d02bd6b112fffa199f715e61d895cba6623 | [
"Apache-2.0"
] | null | null | null | apps/studio/lib/studio/painter/pycasso.ex | danmarcab/deep_painting | 860c7d02bd6b112fffa199f715e61d895cba6623 | [
"Apache-2.0"
] | 11 | 2020-01-28T22:19:10.000Z | 2022-03-11T23:18:18.000Z | apps/studio/lib/studio/painter/pycasso.ex | danmarcab/deep_painting | 860c7d02bd6b112fffa199f715e61d895cba6623 | [
"Apache-2.0"
] | null | null | null | defmodule Studio.Painter.Pycasso do
@moduledoc """
Real implementation of a port that comunicates with pycasso to use with Studio.Painter
"""
require Logger
alias Painting.Settings
def start(%Painting{} = painting) do
executable = System.get_env("PYCASSO_PATH") || Application.get_env(:studio, :pycasso_path)
command = "#{executable} #{args(painting)}"
Logger.info "Calling Pycasso with command: #{command}"
Port.open({:spawn, command}, [:binary, {:packet, 4}, :nouse_stdio, :exit_status])
end
defp args(%Painting{} = painting) do
required_args =
[painting.content, painting.style, output_path(painting)]
|> Enum.map(&inspect/1)
(required_args ++ settings_args(painting.settings))
|> Enum.join(" ")
end
defp output_path(painting) do
Application.app_dir(:studio, "priv") <> "/paintings/" <> painting.name
end
defp settings_args(%Settings{} = settings) do
[
"-r port",
"--initial_type #{settings.initial_type}",
"--output_width #{settings.output_width}",
"--iterations #{settings.iterations}",
"--content_weight #{settings.content_weight}",
"--style_weight #{settings.style_weight}",
"--variation_weight #{settings.variation_weight}"
]
end
end
| 28.266667 | 94 | 0.668239 |
f7549d9ed59d31471c4ae69ee5518fe1abb8da21 | 27,852 | exs | Elixir | test/phoenix/router/helpers_test.exs | mcrumm/phoenix | c3613cadec9ba7c45a8a36360ce8dde905f80ff3 | [
"MIT"
] | null | null | null | test/phoenix/router/helpers_test.exs | mcrumm/phoenix | c3613cadec9ba7c45a8a36360ce8dde905f80ff3 | [
"MIT"
] | null | null | null | test/phoenix/router/helpers_test.exs | mcrumm/phoenix | c3613cadec9ba7c45a8a36360ce8dde905f80ff3 | [
"MIT"
] | null | null | null | modules = [
PostController,
ChatController,
UserController,
CommentController,
FileController,
ProductController,
TrailController,
VistaController,
Admin.MessageController,
SubPlug
]
for module <- modules do
defmodule module do
def init(opts), do: opts
def call(conn, _opts), do: conn
end
end
defmodule Phoenix.Router.HelpersTest do
use ExUnit.Case, async: true
use RouterHelper
defmodule Router do
use Phoenix.Router
get "/posts/top", PostController, :top, as: :top
get "/posts/bottom/:order/:count", PostController, :bottom, as: :bottom
get "/posts/:id", PostController, :show
get "/posts/file/*file", PostController, :file
get "/posts/skip", PostController, :skip, as: nil
get "/chat*js_route", ChatController, :show
resources "/users", UserController do
resources "/comments", CommentController do
resources "/files", FileController
end
end
resources "/files", FileController
resources "/account", UserController, as: :account, singleton: true do
resources "/page", PostController, as: :page, only: [:show], singleton: true
end
scope "/admin", alias: Admin do
resources "/messages", MessageController
end
scope "/admin/new", alias: Admin, as: "admin" do
resources "/messages", MessageController
end
scope "/trails", trailing_slash: true do
get "/", TrailController, :index
get "/open", TrailController, :open, trailing_slash: false
resources "/vistas", VistaController
scope "/nested" do
get "/path", TrailController, :nested_path
end
end
get "/trails/top", TrailController, :top, trailing_slash: true
get "/", PostController, :root, as: :page
get "/products/:id", ProductController, :show
get "/products", ProductController, :show
get "/products/:id/:sort", ProductController, :show
get "/products/:id/:sort/:page", ProductController, :show
get "/mfa_path", SubPlug, func: {M, :f, [10]}
end
# Emulate regular endpoint functions
def url do
"https://example.com"
end
def static_url do
"https://static.example.com"
end
def path(path) do
path
end
def static_path(path) do
path
end
def static_integrity(_path), do: nil
alias Router.Helpers
test "defines a __helpers__ function" do
assert Router.__helpers__() == Router.Helpers
end
test "root helper" do
conn = conn(:get, "/") |> put_private(:phoenix_endpoint, __MODULE__)
assert Helpers.page_path(conn, :root) == "/"
assert Helpers.page_path(__MODULE__, :root) == "/"
end
test "url helper with query strings" do
assert Helpers.post_path(__MODULE__, :show, 5, id: 3) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, foo: "bar") == "/posts/5?foo=bar"
assert Helpers.post_path(__MODULE__, :show, 5, foo: :bar) == "/posts/5?foo=bar"
assert Helpers.post_path(__MODULE__, :show, 5, foo: true) == "/posts/5?foo=true"
assert Helpers.post_path(__MODULE__, :show, 5, foo: false) == "/posts/5?foo=false"
assert Helpers.post_path(__MODULE__, :show, 5, foo: nil) == "/posts/5?foo="
assert Helpers.post_path(__MODULE__, :show, 5, foo: ~w(bar baz)) ==
"/posts/5?foo[]=bar&foo[]=baz"
assert Helpers.post_path(__MODULE__, :show, 5, foo: %{id: 5}) ==
"/posts/5?foo[id]=5"
assert Helpers.post_path(__MODULE__, :show, 5, foo: %{__struct__: Foo, id: 5}) ==
"/posts/5?foo=5"
end
test "url helper with param protocol" do
assert Helpers.post_path(__MODULE__, :show, %{__struct__: Foo, id: 5}) == "/posts/5"
assert_raise ArgumentError, fn ->
Helpers.post_path(__MODULE__, :show, nil)
end
end
test "url helper shows an error if an id is accidentally passed" do
error_suggestion = ~r/bottom_path\(conn, :bottom, order, count, page: 5, per_page: 10\)/
assert_raise ArgumentError, error_suggestion, fn ->
Helpers.bottom_path(__MODULE__, :bottom, :asc, 8, {:not, :enumerable})
end
error_suggestion = ~r/top_path\(conn, :top, page: 5, per_page: 10\)/
assert_raise ArgumentError, error_suggestion, fn ->
Helpers.top_path(__MODULE__, :top, "invalid")
end
end
test "top-level named route" do
assert Helpers.post_path(__MODULE__, :show, 5) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, []) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, id: 5) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, 5, %{"id" => 5}) == "/posts/5"
assert Helpers.post_path(__MODULE__, :show, "foo") == "/posts/foo"
assert Helpers.post_path(__MODULE__, :show, "foo bar") == "/posts/foo%20bar"
assert Helpers.post_path(__MODULE__, :file, ["foo", "bar/baz"]) == "/posts/file/foo/bar%2Fbaz"
assert Helpers.post_path(__MODULE__, :file, ["foo", "bar"], []) == "/posts/file/foo/bar"
assert Helpers.post_path(__MODULE__, :file, ["foo", "bar baz"], []) == "/posts/file/foo/bar%20baz"
assert Helpers.chat_path(__MODULE__, :show, ["chat"]) == "/chat"
assert Helpers.chat_path(__MODULE__, :show, ["chat", "foo"]) == "/chat/foo"
assert Helpers.chat_path(__MODULE__, :show, ["chat/foo"]) == "/chat%2Ffoo"
assert Helpers.chat_path(__MODULE__, :show, ["chat/foo", "bar/baz"]) == "/chat%2Ffoo/bar%2Fbaz"
assert Helpers.top_path(__MODULE__, :top) == "/posts/top"
assert Helpers.top_path(__MODULE__, :top, id: 5) == "/posts/top?id=5"
assert Helpers.top_path(__MODULE__, :top, %{"id" => 5}) == "/posts/top?id=5"
assert Helpers.top_path(__MODULE__, :top, %{"id" => "foo"}) == "/posts/top?id=foo"
assert Helpers.top_path(__MODULE__, :top, %{"id" => "foo bar"}) == "/posts/top?id=foo+bar"
error_message = fn helper, arity ->
"""
no action :skip for #{inspect Helpers}.#{helper}/#{arity}. The following actions/clauses are supported:
#{helper}(conn_or_endpoint, :file, file, params \\\\ [])
#{helper}(conn_or_endpoint, :show, id, params \\\\ [])
""" |> String.trim
end
assert_raise ArgumentError, error_message.("post_path", 3), fn ->
Helpers.post_path(__MODULE__, :skip, 5)
end
assert_raise ArgumentError, error_message.("post_url", 3), fn ->
Helpers.post_url(__MODULE__, :skip, 5)
end
assert_raise ArgumentError, error_message.("post_path", 4), fn ->
Helpers.post_path(__MODULE__, :skip, 5, foo: "bar", other: "param")
end
assert_raise ArgumentError, error_message.("post_url", 4), fn ->
Helpers.post_url(__MODULE__, :skip, 5, foo: "bar", other: "param")
end
assert_raise ArgumentError, ~r/when building url for Phoenix.Router.HelpersTest.Router/, fn ->
Helpers.post_url("oops", :skip, 5, foo: "bar", other: "param")
end
assert_raise ArgumentError, ~r/when building path for Phoenix.Router.HelpersTest.Router/, fn ->
Helpers.post_path("oops", :skip, 5, foo: "bar", other: "param")
end
end
test "top-level named routes with complex ids" do
assert Helpers.post_path(__MODULE__, :show, "==d--+") ==
"/posts/%3D%3Dd--%2B"
assert Helpers.post_path(__MODULE__, :show, "==d--+", []) ==
"/posts/%3D%3Dd--%2B"
assert Helpers.top_path(__MODULE__, :top, id: "==d--+") ==
"/posts/top?id=%3D%3Dd--%2B"
assert Helpers.post_path(__MODULE__, :file, ["==d--+", ":O.jpg"]) ==
"/posts/file/%3D%3Dd--%2B/%3AO.jpg"
assert Helpers.post_path(__MODULE__, :file, ["==d--+", ":O.jpg"], []) ==
"/posts/file/%3D%3Dd--%2B/%3AO.jpg"
assert Helpers.post_path(__MODULE__, :file, ["==d--+", ":O.jpg"], xx: "/=+/") ==
"/posts/file/%3D%3Dd--%2B/%3AO.jpg?xx=%2F%3D%2B%2F"
end
test "top-level named routes with trailing slashes" do
assert Helpers.trail_path(__MODULE__, :top) == "/trails/top/"
assert Helpers.trail_path(__MODULE__, :top, id: 5) == "/trails/top/?id=5"
assert Helpers.trail_path(__MODULE__, :top, %{"id" => "foo"}) == "/trails/top/?id=foo"
assert Helpers.trail_path(__MODULE__, :top, %{"id" => "foo bar"}) == "/trails/top/?id=foo+bar"
end
test "resources generates named routes for :index, :edit, :show, :new" do
assert Helpers.user_path(__MODULE__, :index, []) == "/users"
assert Helpers.user_path(__MODULE__, :index) == "/users"
assert Helpers.user_path(__MODULE__, :edit, 123, []) == "/users/123/edit"
assert Helpers.user_path(__MODULE__, :edit, 123) == "/users/123/edit"
assert Helpers.user_path(__MODULE__, :show, 123, []) == "/users/123"
assert Helpers.user_path(__MODULE__, :show, 123) == "/users/123"
assert Helpers.user_path(__MODULE__, :new, []) == "/users/new"
assert Helpers.user_path(__MODULE__, :new) == "/users/new"
end
test "resources generated named routes with complex ids" do
assert Helpers.user_path(__MODULE__, :edit, "1a+/31d", []) == "/users/1a%2B%2F31d/edit"
assert Helpers.user_path(__MODULE__, :edit, "1a+/31d") == "/users/1a%2B%2F31d/edit"
assert Helpers.user_path(__MODULE__, :show, "1a+/31d", []) == "/users/1a%2B%2F31d"
assert Helpers.user_path(__MODULE__, :show, "1a+/31d") == "/users/1a%2B%2F31d"
assert Helpers.message_path(__MODULE__, :update, "8=/=d", []) == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.message_path(__MODULE__, :update, "8=/=d") == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.message_path(__MODULE__, :delete, "8=/=d", []) == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.message_path(__MODULE__, :delete, "8=/=d") == "/admin/messages/8%3D%2F%3Dd"
assert Helpers.user_path(__MODULE__, :show, "1a+/31d", [dog: "8d="]) == "/users/1a%2B%2F31d?dog=8d%3D"
assert Helpers.user_path(__MODULE__, :index, [cat: "=8+/&"]) == "/users?cat=%3D8%2B%2F%26"
end
test "resources generates named routes for :create, :update, :delete" do
assert Helpers.message_path(__MODULE__, :create, []) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :create) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :update, 1, []) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :update, 1) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :delete, 1, []) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :delete, 1) == "/admin/messages/1"
end
test "1-Level nested resources generates nested named routes for :index, :edit, :show, :new" do
assert Helpers.user_comment_path(__MODULE__, :index, 99, []) == "/users/99/comments"
assert Helpers.user_comment_path(__MODULE__, :index, 99) == "/users/99/comments"
assert Helpers.user_comment_path(__MODULE__, :edit, 88, 2, []) == "/users/88/comments/2/edit"
assert Helpers.user_comment_path(__MODULE__, :edit, 88, 2) == "/users/88/comments/2/edit"
assert Helpers.user_comment_path(__MODULE__, :show, 123, 2, []) == "/users/123/comments/2"
assert Helpers.user_comment_path(__MODULE__, :show, 123, 2) == "/users/123/comments/2"
assert Helpers.user_comment_path(__MODULE__, :new, 88, []) == "/users/88/comments/new"
assert Helpers.user_comment_path(__MODULE__, :new, 88) == "/users/88/comments/new"
assert_raise ArgumentError, ~r/no action :skip/, fn ->
Helpers.user_comment_file_path(__MODULE__, :skip, 123, 456)
end
assert_raise ArgumentError, ~r/no action :skip/, fn ->
Helpers.user_comment_file_path(__MODULE__, :skip, 123, 456, foo: "bar")
end
assert_raise ArgumentError, ~r/no function clause for Phoenix.Router.HelpersTest.Router.Helpers.user_comment_path\/3 and action :show/, fn ->
Helpers.user_comment_path(__MODULE__, :show, 123)
end
end
test "multi-level nested resources generated named routes with complex ids" do
assert Helpers.user_comment_path(__MODULE__, :index, "f4/d+~=", []) ==
"/users/f4%2Fd%2B~%3D/comments"
assert Helpers.user_comment_path(__MODULE__, :index, "f4/d+~=") ==
"/users/f4%2Fd%2B~%3D/comments"
assert Helpers.user_comment_path(__MODULE__, :edit, "f4/d+~=", "x-+=/", []) ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F/edit"
assert Helpers.user_comment_path(__MODULE__, :edit, "f4/d+~=", "x-+=/") ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F/edit"
assert Helpers.user_comment_path(__MODULE__, :show, "f4/d+~=", "x-+=/", []) ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F"
assert Helpers.user_comment_path(__MODULE__, :show, "f4/d+~=", "x-+=/") ==
"/users/f4%2Fd%2B~%3D/comments/x-%2B%3D%2F"
assert Helpers.user_comment_path(__MODULE__, :new, "/==/", []) ==
"/users/%2F%3D%3D%2F/comments/new"
assert Helpers.user_comment_path(__MODULE__, :new, "/==/") ==
"/users/%2F%3D%3D%2F/comments/new"
assert Helpers.user_comment_file_path(__MODULE__, :show, "f4/d+~=", "/==/", "x-+=/", []) ==
"/users/f4%2Fd%2B~%3D/comments/%2F%3D%3D%2F/files/x-%2B%3D%2F"
assert Helpers.user_comment_file_path(__MODULE__, :show, "f4/d+~=", "/==/", "x-+=/") ==
"/users/f4%2Fd%2B~%3D/comments/%2F%3D%3D%2F/files/x-%2B%3D%2F"
end
test "2-Level nested resources generates nested named routes for :index, :edit, :show, :new" do
assert Helpers.user_comment_file_path(__MODULE__, :index, 99, 1, []) ==
"/users/99/comments/1/files"
assert Helpers.user_comment_file_path(__MODULE__, :index, 99, 1) ==
"/users/99/comments/1/files"
assert Helpers.user_comment_file_path(__MODULE__, :edit, 88, 1, 2, []) ==
"/users/88/comments/1/files/2/edit"
assert Helpers.user_comment_file_path(__MODULE__, :edit, 88, 1, 2) ==
"/users/88/comments/1/files/2/edit"
assert Helpers.user_comment_file_path(__MODULE__, :show, 123, 1, 2, []) ==
"/users/123/comments/1/files/2"
assert Helpers.user_comment_file_path(__MODULE__, :show, 123, 1, 2) ==
"/users/123/comments/1/files/2"
assert Helpers.user_comment_file_path(__MODULE__, :new, 88, 1, []) ==
"/users/88/comments/1/files/new"
assert Helpers.user_comment_file_path(__MODULE__, :new, 88, 1) ==
"/users/88/comments/1/files/new"
end
test "resources without block generates named routes for :index, :edit, :show, :new" do
assert Helpers.file_path(__MODULE__, :index, []) == "/files"
assert Helpers.file_path(__MODULE__, :index) == "/files"
assert Helpers.file_path(__MODULE__, :edit, 123, []) == "/files/123/edit"
assert Helpers.file_path(__MODULE__, :edit, 123) == "/files/123/edit"
assert Helpers.file_path(__MODULE__, :show, 123, []) == "/files/123"
assert Helpers.file_path(__MODULE__, :show, 123) == "/files/123"
assert Helpers.file_path(__MODULE__, :new, []) == "/files/new"
assert Helpers.file_path(__MODULE__, :new) == "/files/new"
end
test "resource generates named routes for :show, :edit, :new, :update, :delete" do
assert Helpers.account_path(__MODULE__, :show, []) == "/account"
assert Helpers.account_path(__MODULE__, :show) == "/account"
assert Helpers.account_path(__MODULE__, :edit, []) == "/account/edit"
assert Helpers.account_path(__MODULE__, :edit) == "/account/edit"
assert Helpers.account_path(__MODULE__, :new, []) == "/account/new"
assert Helpers.account_path(__MODULE__, :new) == "/account/new"
assert Helpers.account_path(__MODULE__, :update, []) == "/account"
assert Helpers.account_path(__MODULE__, :update) == "/account"
assert Helpers.account_path(__MODULE__, :delete, []) == "/account"
assert Helpers.account_path(__MODULE__, :delete) == "/account"
end
test "2-Level nested resource generates nested named routes for :show" do
assert Helpers.account_page_path(__MODULE__, :show, []) == "/account/page"
assert Helpers.account_page_path(__MODULE__, :show) == "/account/page"
end
test "scoped route helpers generated named routes with :path, and :alias options" do
assert Helpers.message_path(__MODULE__, :index, []) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :index) == "/admin/messages"
assert Helpers.message_path(__MODULE__, :show, 1, []) == "/admin/messages/1"
assert Helpers.message_path(__MODULE__, :show, 1) == "/admin/messages/1"
end
test "scoped route helpers generated named routes with :path, :alias, and :helper options" do
assert Helpers.admin_message_path(__MODULE__, :index, []) == "/admin/new/messages"
assert Helpers.admin_message_path(__MODULE__, :index) == "/admin/new/messages"
assert Helpers.admin_message_path(__MODULE__, :show, 1, []) == "/admin/new/messages/1"
assert Helpers.admin_message_path(__MODULE__, :show, 1) == "/admin/new/messages/1"
end
test "scoped route helpers generated with trailing slashes" do
assert Helpers.trail_path(__MODULE__, :index) == "/trails/"
assert Helpers.trail_path(__MODULE__, :index, id: 5) == "/trails/?id=5"
assert Helpers.trail_path(__MODULE__, :index, %{"id" => "foo"}) == "/trails/?id=foo"
assert Helpers.trail_path(__MODULE__, :index, %{"id" => "foo bar"}) == "/trails/?id=foo+bar"
end
test "scoped route helpers generated with trailing slashes overridden" do
assert Helpers.trail_path(__MODULE__, :open) == "/trails/open"
assert Helpers.trail_path(__MODULE__, :open, id: 5) == "/trails/open?id=5"
assert Helpers.trail_path(__MODULE__, :open, %{"id" => "foo"}) == "/trails/open?id=foo"
assert Helpers.trail_path(__MODULE__, :open, %{"id" => "foo bar"}) == "/trails/open?id=foo+bar"
end
test "scoped route helpers generated with trailing slashes for resource" do
assert Helpers.vista_path(__MODULE__, :index) == "/trails/vistas/"
assert Helpers.vista_path(__MODULE__, :index, []) == "/trails/vistas/"
assert Helpers.vista_path(__MODULE__, :index, id: 5) == "/trails/vistas/?id=5"
assert Helpers.vista_path(__MODULE__, :index, %{"id" => "foo"}) == "/trails/vistas/?id=foo"
assert Helpers.vista_path(__MODULE__, :new) == "/trails/vistas/new/"
assert Helpers.vista_path(__MODULE__, :new, []) == "/trails/vistas/new/"
assert Helpers.vista_path(__MODULE__, :create) == "/trails/vistas/"
assert Helpers.vista_path(__MODULE__, :create, []) == "/trails/vistas/"
assert Helpers.vista_path(__MODULE__, :show, 2) == "/trails/vistas/2/"
assert Helpers.vista_path(__MODULE__, :show, 2, []) == "/trails/vistas/2/"
assert Helpers.vista_path(__MODULE__, :edit, 2) == "/trails/vistas/2/edit/"
assert Helpers.vista_path(__MODULE__, :edit, 2, []) == "/trails/vistas/2/edit/"
assert Helpers.vista_path(__MODULE__, :update, 2) == "/trails/vistas/2/"
assert Helpers.vista_path(__MODULE__, :update, 2, []) == "/trails/vistas/2/"
assert Helpers.vista_path(__MODULE__, :delete, 2) == "/trails/vistas/2/"
assert Helpers.vista_path(__MODULE__, :delete, 2, []) == "/trails/vistas/2/"
end
test "scoped route helpers generated within scoped routes with trailing slashes" do
assert Helpers.trail_path(__MODULE__, :nested_path) == "/trails/nested/path/"
assert Helpers.trail_path(__MODULE__, :nested_path, []) == "/trails/nested/path/"
assert Helpers.trail_path(__MODULE__, :nested_path, [id: 5]) == "/trails/nested/path/?id=5"
assert Helpers.trail_path(__MODULE__, :nested_path, %{"id" => "foo"}) == "/trails/nested/path/?id=foo"
assert Helpers.trail_path(__MODULE__, :nested_path, %{"id" => "foo bar"}) == "/trails/nested/path/?id=foo+bar"
end
test "can pass an {m, f, a} tuple as a plug argument" do
assert Helpers.sub_plug_path(__MODULE__, func: {M, :f, [10]}) == "/mfa_path"
end
## Others
defp conn_with_endpoint do
conn(:get, "/") |> put_private(:phoenix_endpoint, __MODULE__)
end
defp socket_with_endpoint do
%Phoenix.Socket{endpoint: __MODULE__}
end
defp uri do
%URI{scheme: "https", host: "example.com", port: 443}
end
test "helpers module generates a static_path helper" do
assert Helpers.static_path(__MODULE__, "/images/foo.png") == "/images/foo.png"
assert Helpers.static_path(conn_with_endpoint(), "/images/foo.png") == "/images/foo.png"
assert Helpers.static_path(socket_with_endpoint(), "/images/foo.png") == "/images/foo.png"
end
test "helpers module generates a static_url helper" do
url = "https://static.example.com/images/foo.png"
assert Helpers.static_url(__MODULE__, "/images/foo.png") == url
assert Helpers.static_url(conn_with_endpoint(), "/images/foo.png") == url
assert Helpers.static_url(socket_with_endpoint(), "/images/foo.png") == url
end
test "helpers module generates a url helper" do
assert Helpers.url(__MODULE__) == "https://example.com"
assert Helpers.url(conn_with_endpoint()) == "https://example.com"
assert Helpers.url(socket_with_endpoint()) == "https://example.com"
assert Helpers.url(uri()) == "https://example.com"
end
test "helpers module generates a path helper" do
assert Helpers.path(__MODULE__, "/") == "/"
assert Helpers.path(conn_with_endpoint(), "/") == "/"
assert Helpers.path(socket_with_endpoint(), "/") == "/"
assert Helpers.path(uri(), "/") == "/"
end
test "helpers module generates a static_integrity helper" do
assert is_nil(Helpers.static_integrity(__MODULE__, "/images/foo.png"))
assert is_nil(Helpers.static_integrity(conn_with_endpoint(), "/images/foo.png"))
assert is_nil(Helpers.static_integrity(socket_with_endpoint(), "/images/foo.png"))
end
test "helpers module generates named routes url helpers" do
url = "https://example.com/admin/new/messages/1"
assert Helpers.admin_message_url(__MODULE__, :show, 1) == url
assert Helpers.admin_message_url(__MODULE__, :show, 1, []) == url
assert Helpers.admin_message_url(conn_with_endpoint(), :show, 1) == url
assert Helpers.admin_message_url(conn_with_endpoint(), :show, 1, []) == url
assert Helpers.admin_message_url(socket_with_endpoint(), :show, 1) == url
assert Helpers.admin_message_url(socket_with_endpoint(), :show, 1, []) == url
assert Helpers.admin_message_url(uri(), :show, 1) == url
assert Helpers.admin_message_url(uri(), :show, 1, []) == url
end
test "helpers properly encode named and query string params" do
assert Router.Helpers.post_path(__MODULE__, :show, "my path", foo: "my param") ==
"/posts/my%20path?foo=my+param"
end
test "duplicate helpers with unique arities" do
assert Helpers.product_path(__MODULE__, :show) == "/products"
assert Helpers.product_path(__MODULE__, :show, foo: "bar") == "/products?foo=bar"
assert Helpers.product_path(__MODULE__, :show, 123) == "/products/123"
assert Helpers.product_path(__MODULE__, :show, 123, foo: "bar") == "/products/123?foo=bar"
assert Helpers.product_path(__MODULE__, :show, 123, "asc") == "/products/123/asc"
assert Helpers.product_path(__MODULE__, :show, 123, "asc", foo: "bar") == "/products/123/asc?foo=bar"
assert Helpers.product_path(__MODULE__, :show, 123, "asc", 1) == "/products/123/asc/1"
assert Helpers.product_path(__MODULE__, :show, 123, "asc", 1, foo: "bar") == "/products/123/asc/1?foo=bar"
end
## Script name
defmodule ScriptName do
def url do
"https://example.com"
end
def static_url do
"https://static.example.com"
end
def path(path) do
"/api" <> path
end
def static_path(path) do
"/api" <> path
end
end
def conn_with_script_name(script_name \\ ~w(api)) do
conn = conn(:get, "/")
|> put_private(:phoenix_endpoint, ScriptName)
put_in conn.script_name, script_name
end
defp uri_with_script_name do
%URI{scheme: "https", host: "example.com", port: 123, path: "/api"}
end
test "paths use script name" do
assert Helpers.page_path(ScriptName, :root) == "/api/"
assert Helpers.page_path(conn_with_script_name(), :root) == "/api/"
assert Helpers.page_path(uri_with_script_name(), :root) == "/api/"
assert Helpers.post_path(ScriptName, :show, 5) == "/api/posts/5"
assert Helpers.post_path(conn_with_script_name(), :show, 5) == "/api/posts/5"
assert Helpers.post_path(uri_with_script_name(), :show, 5) == "/api/posts/5"
end
test "urls use script name" do
assert Helpers.page_url(ScriptName, :root) ==
"https://example.com/api/"
assert Helpers.page_url(conn_with_script_name(~w(foo)), :root) ==
"https://example.com/foo/"
assert Helpers.page_url(uri_with_script_name(), :root) ==
"https://example.com:123/api/"
assert Helpers.post_url(ScriptName, :show, 5) ==
"https://example.com/api/posts/5"
assert Helpers.post_url(conn_with_script_name(), :show, 5) ==
"https://example.com/api/posts/5"
assert Helpers.post_url(conn_with_script_name(~w(foo)), :show, 5) ==
"https://example.com/foo/posts/5"
assert Helpers.post_url(uri_with_script_name(), :show, 5) ==
"https://example.com:123/api/posts/5"
end
test "static use endpoint script name only" do
assert Helpers.static_path(conn_with_script_name(~w(foo)), "/images/foo.png") ==
"/api/images/foo.png"
assert Helpers.static_url(conn_with_script_name(~w(foo)), "/images/foo.png") ==
"https://static.example.com/api/images/foo.png"
end
## Dynamics
test "phoenix_router_url with string takes precedence over endpoint" do
url = "https://phoenixframework.org"
conn = Phoenix.Controller.put_router_url(conn_with_endpoint(), url)
assert Helpers.url(conn) == url
assert Helpers.admin_message_url(conn, :show, 1) ==
url <> "/admin/new/messages/1"
end
test "phoenix_router_url with URI takes precedence over endpoint" do
uri = %URI{scheme: "https", host: "phoenixframework.org", port: 123, path: "/path"}
conn = Phoenix.Controller.put_router_url(conn_with_endpoint(), uri)
assert Helpers.url(conn) == "https://phoenixframework.org:123/path"
assert Helpers.admin_message_url(conn, :show, 1) ==
"https://phoenixframework.org:123/path/admin/new/messages/1"
end
test "phoenix_static_url with string takes precedence over endpoint" do
url = "https://phoenixframework.org"
conn = Phoenix.Controller.put_static_url(conn_with_endpoint(), url)
assert Helpers.static_url(conn, "/images/foo.png") == url <> "/images/foo.png"
conn = Phoenix.Controller.put_static_url(conn_with_script_name(), url)
assert Helpers.static_url(conn, "/images/foo.png") == url <> "/images/foo.png"
end
test "phoenix_static_url set to string with path results in static url with that path" do
url = "https://phoenixframework.org/path"
conn = Phoenix.Controller.put_static_url(conn_with_endpoint(), url)
assert Helpers.static_url(conn, "/images/foo.png") == url <> "/images/foo.png"
conn = Phoenix.Controller.put_static_url(conn_with_script_name(), url)
assert Helpers.static_url(conn, "/images/foo.png") == url <> "/images/foo.png"
end
test "phoenix_static_url with URI takes precedence over endpoint" do
uri = %URI{scheme: "https", host: "phoenixframework.org", port: 123}
conn = Phoenix.Controller.put_static_url(conn_with_endpoint(), uri)
assert Helpers.static_url(conn, "/images/foo.png") == "https://phoenixframework.org:123/images/foo.png"
conn = Phoenix.Controller.put_static_url(conn_with_script_name(), uri)
assert Helpers.static_url(conn, "/images/foo.png") == "https://phoenixframework.org:123/images/foo.png"
end
test "phoenix_static_url set to URI with path results in static url with that path" do
uri = %URI{scheme: "https", host: "phoenixframework.org", port: 123, path: "/path"}
conn = Phoenix.Controller.put_static_url(conn_with_endpoint(), uri)
assert Helpers.static_url(conn, "/images/foo.png") == "https://phoenixframework.org:123/path/images/foo.png"
conn = Phoenix.Controller.put_static_url(conn_with_script_name(), uri)
assert Helpers.static_url(conn, "/images/foo.png") == "https://phoenixframework.org:123/path/images/foo.png"
end
end
| 44.778135 | 145 | 0.669934 |
f754debe5e8bb5b5ef54048a077fc2bb89d16f63 | 3,011 | ex | Elixir | plugins/ucc_chat/lib/ucc_chat_web/channels/room_channel/reaction.ex | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | plugins/ucc_chat/lib/ucc_chat_web/channels/room_channel/reaction.ex | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | plugins/ucc_chat/lib/ucc_chat_web/channels/room_channel/reaction.ex | josephkabraham/ucx_ucc | 0dbd9e3eb5940336b4870cff033482ceba5f6ee7 | [
"MIT"
] | null | null | null | defmodule UccChatWeb.RoomChannel.Reaction do
use UccLogger
use UcxUccWeb.Gettext
use UccChatWeb.RoomChannel.Constants
# import UccChatWeb.RebelChannel.Client
alias UccChatWeb.Client
alias UccChat.{Reaction, Message}
alias UcxUcc.{Accounts, Repo, UccPubSub}
def select(socket, sender, client \\ Client) do
# Logger.info "sender: #{inspect sender}"
emoji = ":" <> sender["dataset"]["emoji"] <> ":"
user = Accounts.get_user socket.assigns.user_id
message_id = Rebel.get_assigns socket, :reaction
Rebel.put_assigns socket, :reaction, nil
message = Message.get message_id, preload: Message.preloads()
case Enum.find message.reactions, &(&1.emoji == emoji) do
nil ->
insert_reaction socket, emoji, message.id, user.id, client
reaction ->
update_reaction reaction, user.id
end
message = Message.get message_id, preload: Message.preloads()
UccPubSub.broadcast "message:update:reactions", "channel:" <> message.channel_id,
%{message: message}
socket
|> client.async_js("""
chat_emoji.close_picker();
document.querySelector('#{@message_box}').focus();
""")
|> UccChatWeb.RoomChannel.MessageCog.close_cog(message.id, client)
emoji
end
def insert_reaction(socket, emoji, message_id, user_id, client \\ Client) do
case Reaction.create(%{emoji: emoji, message_id: message_id,
user_ids: user_id, count: 1}) do
{:ok, _} ->
nil
{:error, _cs} ->
client.toastr! socket, :error, ~g(Problem adding reaction)
end
end
def update_reaction(reaction, user_id) do
user_ids = reaction_user_ids reaction
case Enum.any?(user_ids, &(&1 == user_id)) do
true ->
remove_user_reaction(reaction, user_id, user_ids)
false ->
add_user_reaction(reaction, user_id, user_ids)
end
end
defp remove_user_reaction(%{count: count} = reaction, user_id, user_ids) do
user_ids =
user_ids
|> Enum.reject(&(&1 == user_id))
|> Enum.join(" ")
if user_ids == "" do
# TODO: change this to reaction.delete
Repo.delete reaction
else
Reaction.update(reaction, %{count: count - 1, user_ids: user_ids})
end
end
defp add_user_reaction(%{count: count} = reaction, user_id, user_ids) do
user_ids =
(user_ids ++ [user_id])
|> Enum.join(" ")
Reaction.update(reaction, %{count: count + 1, user_ids: user_ids})
end
defp reaction_user_ids(reaction) do
String.split(reaction.user_ids, " ", trim: true)
end
def get_reaction_people_names(reaction, user) do
username = user.username
reaction
|> reaction_user_ids
|> Enum.map(&Accounts.get_user/1)
|> Enum.reject(&(is_nil &1))
|> Enum.map(fn user ->
case user.username do
^username -> "you"
username -> "@" <> username
end
end)
|> case do
[one] -> one
[first | rest] ->
Enum.join(rest, ", ") <> " and " <> first
end
end
end
| 27.623853 | 85 | 0.640319 |
f754e882e8c845b73b1606f4c79ce6997128531f | 6,938 | ex | Elixir | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_response_message.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_response_message.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/dialogflow/lib/google_api/dialogflow/v2/model/google_cloud_dialogflow_cx_v3beta1_response_message.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessage do
@moduledoc """
Represents a response message that can be returned by a conversational agent. Response messages are also used for output audio synthesis. The approach is as follows: * If at least one OutputAudioText response is present, then all OutputAudioText responses are linearly concatenated, and the result is used for output audio synthesis. * If the OutputAudioText responses are a mixture of text and SSML, then the concatenated result is treated as SSML; otherwise, the result is treated as either text or SSML as appropriate. The agent designer should ideally use either text or SSML consistently throughout the bot design. * Otherwise, all Text responses are linearly concatenated, and the result is used for output audio synthesis. This approach allows for more sophisticated user experience scenarios, where the text displayed to the user may differ from what is heard.
## Attributes
* `conversationSuccess` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccess.t`, *default:* `nil`) - Indicates that the conversation succeeded.
* `endInteraction` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageEndInteraction.t`, *default:* `nil`) - Output only. A signal that indicates the interaction with the Dialogflow agent has ended. This message is generated by Dialogflow only when the conversation reaches `END_SESSION` page. It is not supposed to be defined by the user. It's guaranteed that there is at most one such message in each response.
* `liveAgentHandoff` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoff.t`, *default:* `nil`) - Hands off conversation to a human agent.
* `mixedAudio` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudio.t`, *default:* `nil`) - Output only. An audio response message composed of both the synthesized Dialogflow agent responses and responses defined via play_audio. This message is generated by Dialogflow only and not supposed to be defined by the user.
* `outputAudioText` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageOutputAudioText.t`, *default:* `nil`) - A text or ssml response that is preferentially used for TTS output audio synthesis, as described in the comment on the ResponseMessage message.
* `payload` (*type:* `map()`, *default:* `nil`) - Returns a response containing a custom, platform-specific payload.
* `playAudio` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessagePlayAudio.t`, *default:* `nil`) - Signal that the client should play an audio clip hosted at a client-specific URI. Dialogflow uses this to construct mixed_audio. However, Dialogflow itself does not try to read or process the URI in any way.
* `telephonyTransferCall` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageTelephonyTransferCall.t`, *default:* `nil`) - A signal that the client should transfer the phone call connected to this agent to a third-party endpoint.
* `text` (*type:* `GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText.t`, *default:* `nil`) - Returns a text response.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:conversationSuccess =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccess.t()
| nil,
:endInteraction =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageEndInteraction.t()
| nil,
:liveAgentHandoff =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoff.t()
| nil,
:mixedAudio =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudio.t()
| nil,
:outputAudioText =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageOutputAudioText.t()
| nil,
:payload => map() | nil,
:playAudio =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessagePlayAudio.t()
| nil,
:telephonyTransferCall =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageTelephonyTransferCall.t()
| nil,
:text =>
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText.t()
| nil
}
field(:conversationSuccess,
as:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageConversationSuccess
)
field(:endInteraction,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageEndInteraction
)
field(:liveAgentHandoff,
as:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageLiveAgentHandoff
)
field(:mixedAudio,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageMixedAudio
)
field(:outputAudioText,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageOutputAudioText
)
field(:payload, type: :map)
field(:playAudio,
as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessagePlayAudio
)
field(:telephonyTransferCall,
as:
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageTelephonyTransferCall
)
field(:text, as: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessageText)
end
defimpl Poison.Decoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessage do
def decode(value, options) do
GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessage.decode(
value,
options
)
end
end
defimpl Poison.Encoder,
for: GoogleApi.Dialogflow.V2.Model.GoogleCloudDialogflowCxV3beta1ResponseMessage do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 59.299145 | 870 | 0.767512 |
f7551e6471bfc710aa077493dfb54e8ff7f77a08 | 589 | ex | Elixir | lib/timber/contexts/job_context.ex | girishramnani/timber-elixir | 7fda5c3cb5e765a34524d2ec21cfbd5b30240bd5 | [
"ISC"
] | null | null | null | lib/timber/contexts/job_context.ex | girishramnani/timber-elixir | 7fda5c3cb5e765a34524d2ec21cfbd5b30240bd5 | [
"ISC"
] | null | null | null | lib/timber/contexts/job_context.ex | girishramnani/timber-elixir | 7fda5c3cb5e765a34524d2ec21cfbd5b30240bd5 | [
"ISC"
] | null | null | null | defmodule Timber.Contexts.JobContext do
@moduledoc """
The job context tracks the execution of background jobs or any isolated
task with a reference. Add it like:
```elixir
%Timber.Contexts.JobContext{attempt: 1, id: "my_job_id", queue_name: "my_job_queue"}
|> Timber.add_context()
```
"""
@type t :: %__MODULE__{
attempt: nil | pos_integer,
id: String.t,
queue_name: nil | String.t
}
@type m :: %{
attempt: nil | pos_integer,
id: String.t,
queue_name: nil | String.t
}
@enforce_keys [:id]
defstruct [:attempt, :id, :queue_name]
end
| 21.814815 | 86 | 0.651952 |
f75532f24410d38d3a88a552c7ba098692e0200a | 1,685 | ex | Elixir | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/non_guaranteed_fixed_price_terms.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/non_guaranteed_fixed_price_terms.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/ad_exchange_buyer/lib/google_api/ad_exchange_buyer/v2beta1/model/non_guaranteed_fixed_price_terms.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.AdExchangeBuyer.V2beta1.Model.NonGuaranteedFixedPriceTerms do
@moduledoc """
Terms for Preferred Deals.
## Attributes
* `fixedPrices` (*type:* `list(GoogleApi.AdExchangeBuyer.V2beta1.Model.PricePerBuyer.t)`, *default:* `nil`) - Fixed price for the specified buyer.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:fixedPrices => list(GoogleApi.AdExchangeBuyer.V2beta1.Model.PricePerBuyer.t()) | nil
}
field(:fixedPrices, as: GoogleApi.AdExchangeBuyer.V2beta1.Model.PricePerBuyer, type: :list)
end
defimpl Poison.Decoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.NonGuaranteedFixedPriceTerms do
def decode(value, options) do
GoogleApi.AdExchangeBuyer.V2beta1.Model.NonGuaranteedFixedPriceTerms.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.AdExchangeBuyer.V2beta1.Model.NonGuaranteedFixedPriceTerms do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.851064 | 150 | 0.764392 |
f75536c02f371e7bb696594b737d09dc30ab2c67 | 1,150 | ex | Elixir | lib/canon_web/endpoint.ex | megalithic/canon | 8178207cdaf1f137fcdf1f42481636e0209dcbeb | [
"MIT"
] | null | null | null | lib/canon_web/endpoint.ex | megalithic/canon | 8178207cdaf1f137fcdf1f42481636e0209dcbeb | [
"MIT"
] | null | null | null | lib/canon_web/endpoint.ex | megalithic/canon | 8178207cdaf1f137fcdf1f42481636e0209dcbeb | [
"MIT"
] | null | null | null | defmodule CanonWeb.Endpoint do
use Phoenix.Endpoint, otp_app: :canon
socket "/socket", CanonWeb.UserSocket,
websocket: true,
longpoll: false
# Serve at "/" the static files from "priv/static" directory.
#
# You should set gzip to true if you are running phx.digest
# when deploying your static files in production.
plug Plug.Static,
at: "/",
from: :canon,
gzip: false,
only: ~w(css fonts images js favicon.ico robots.txt)
# Code reloading can be explicitly enabled under the
# :code_reloader configuration of your endpoint.
if code_reloading? do
plug Phoenix.CodeReloader
end
plug Plug.RequestId
plug Plug.Logger
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
plug Plug.MethodOverride
plug Plug.Head
# The session will be stored in the cookie and signed,
# this means its contents can be read but not tampered with.
# Set :encryption_salt if you would also like to encrypt it.
plug Plug.Session,
store: :cookie,
key: "_canon_key",
signing_salt: "Yd2KTb7M"
plug CanonWeb.Router
end
| 25.555556 | 63 | 0.7 |
f75579dfb4530702a51b79c8d66b0f846401ae62 | 235 | exs | Elixir | priv/repo/migrations/20161215052051_add_user_id_and_endpoint_to_stripe_events.exs | superdev999/Phoenix-project | ab13ac9366cdd0aa9581da7faf993b11aaa5344c | [
"MIT"
] | 275 | 2015-06-23T00:20:51.000Z | 2021-08-19T16:17:37.000Z | priv/repo/migrations/20161215052051_add_user_id_and_endpoint_to_stripe_events.exs | superdev999/Phoenix-project | ab13ac9366cdd0aa9581da7faf993b11aaa5344c | [
"MIT"
] | 1,304 | 2015-06-26T02:11:54.000Z | 2019-12-12T21:08:00.000Z | priv/repo/migrations/20161215052051_add_user_id_and_endpoint_to_stripe_events.exs | superdev999/Phoenix-project | ab13ac9366cdd0aa9581da7faf993b11aaa5344c | [
"MIT"
] | 140 | 2016-01-01T18:19:47.000Z | 2020-11-22T06:24:47.000Z | defmodule CodeCorps.Repo.Migrations.AddUserIdAndEndpointToStripeEvents do
use Ecto.Migration
def change do
alter table(:stripe_events) do
add :endpoint, :string, null: false
add :user_id, :string
end
end
end
| 21.363636 | 73 | 0.72766 |
f755abae303eb867c1503dd8bfe418b6270af9b5 | 418 | ex | Elixir | core/async_job/raft_per_member_options_maker.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 144 | 2018-04-27T07:24:49.000Z | 2022-03-15T05:19:37.000Z | core/async_job/raft_per_member_options_maker.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 123 | 2018-05-01T02:54:43.000Z | 2022-01-28T01:30:52.000Z | core/async_job/raft_per_member_options_maker.ex | sylph01/antikythera | 47a93f3d4c70975f7296725c9bde2ea823867436 | [
"Apache-2.0"
] | 14 | 2018-05-01T02:30:47.000Z | 2022-02-21T04:38:56.000Z | # Copyright(c) 2015-2021 ACCESS CO., LTD. All rights reserved.
use Croma
defmodule AntikytheraCore.AsyncJob.RaftPerMemberOptionsMaker do
@behaviour RaftFleet.PerMemberOptionsMaker
@impl true
defun make(name :: v[atom]) :: [RaftedValue.option()] do
dir = Path.join(AntikytheraCore.Path.raft_persistence_dir_parent(), Atom.to_string(name))
[persistence_dir: dir, spawn_opt: [priority: :high]]
end
end
| 29.857143 | 93 | 0.755981 |
f7560e569140731bf96842f17dfc54e1a6c2d180 | 1,610 | ex | Elixir | lib/cforum_web/views/archive_view.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 16 | 2019-04-04T06:33:33.000Z | 2021-08-16T19:34:31.000Z | lib/cforum_web/views/archive_view.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 294 | 2019-02-10T11:10:27.000Z | 2022-03-30T04:52:53.000Z | lib/cforum_web/views/archive_view.ex | jrieger/cforum_ex | 61f6ce84708cb55bd0feedf69853dae64146a7a0 | [
"MIT"
] | 10 | 2019-02-10T10:39:24.000Z | 2021-07-06T11:46:05.000Z | defmodule CforumWeb.ArchiveView do
use CforumWeb, :view
alias CforumWeb.Paginator
alias CforumWeb.Views.ViewHelpers.Path
defp forum_name(%{current_forum: forum}) when not is_nil(forum), do: forum.name
defp forum_name(_), do: gettext("all forums")
def page_title(:years, assigns), do: gettext("archive – %{forum}", forum: forum_name(assigns))
def page_title(:months, assigns),
do: gettext("archive: %{year} – %{forum}", year: assigns[:year], forum: forum_name(assigns))
def page_title(:threads, assigns) do
gettext("archive: %{month} – %{forum}",
month: Timex.format!(assigns[:start_date], "%B %Y", :strftime),
forum: forum_name(assigns)
)
end
def page_heading(action, assigns), do: page_title(action, assigns)
def body_id(:years, _), do: "archive-years"
def body_id(:months, _), do: "archive-months"
def body_id(:threads, _), do: "archive-threads"
def body_classes(:years, _), do: "archive years"
def body_classes(:months, _), do: "archive months"
def body_classes(:threads, _), do: "archive threads"
def year_title([]), do: ""
def year_title([%NaiveDateTime{} = year | _]), do: to_string(year.year)
def month_link_title(month) do
month_name = Timex.format!(month, "%B", :strftime)
[
String.slice(month_name, 0..2),
{:safe, "<span class=\"full-month\">"},
String.slice(month_name, 3..-1),
{:safe, "</span>"}
]
end
def months_for_year(year) do
year_no = List.first(year).year
for m <- 1..12, do: {%Date{year: year_no, month: m, day: 1}, Enum.find(year, &(&1.month == m)) != nil}
end
end
| 31.568627 | 106 | 0.652174 |
f75618931807d286b764aab74abf3f1e02863deb | 2,493 | ex | Elixir | priv/templates/phx.gen.context/schema_access.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | 8 | 2019-06-02T05:02:36.000Z | 2021-08-11T04:23:10.000Z | priv/templates/phx.gen.context/schema_access.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | 7 | 2019-05-15T08:32:51.000Z | 2020-06-10T07:46:43.000Z | priv/templates/phx.gen.context/schema_access.ex | zorn/phoenix | ac88958550fbd861e2f1e1af6e3c6b787b1a202e | [
"MIT"
] | 1 | 2019-06-02T05:02:47.000Z | 2019-06-02T05:02:47.000Z |
alias <%= inspect schema.module %>
@doc """
Returns the list of <%= schema.plural %>.
## Examples
iex> list_<%= schema.plural %>()
[%<%= inspect schema.alias %>{}, ...]
"""
def list_<%= schema.plural %> do
Repo.all(<%= inspect schema.alias %>)
end
@doc """
Gets a single <%= schema.singular %>.
Raises `Ecto.NoResultsError` if the <%= schema.human_singular %> does not exist.
## Examples
iex> get_<%= schema.singular %>!(123)
%<%= inspect schema.alias %>{}
iex> get_<%= schema.singular %>!(456)
** (Ecto.NoResultsError)
"""
def get_<%= schema.singular %>!(id), do: Repo.get!(<%= inspect schema.alias %>, id)
@doc """
Creates a <%= schema.singular %>.
## Examples
iex> create_<%= schema.singular %>(%{field: value})
{:ok, %<%= inspect schema.alias %>{}}
iex> create_<%= schema.singular %>(%{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def create_<%= schema.singular %>(attrs \\ %{}) do
%<%= inspect schema.alias %>{}
|> <%= inspect schema.alias %>.changeset(attrs)
|> Repo.insert()
end
@doc """
Updates a <%= schema.singular %>.
## Examples
iex> update_<%= schema.singular %>(<%= schema.singular %>, %{field: new_value})
{:ok, %<%= inspect schema.alias %>{}}
iex> update_<%= schema.singular %>(<%= schema.singular %>, %{field: bad_value})
{:error, %Ecto.Changeset{}}
"""
def update_<%= schema.singular %>(%<%= inspect schema.alias %>{} = <%= schema.singular %>, attrs) do
<%= schema.singular %>
|> <%= inspect schema.alias %>.changeset(attrs)
|> Repo.update()
end
@doc """
Deletes a <%= inspect schema.alias %>.
## Examples
iex> delete_<%= schema.singular %>(<%= schema.singular %>)
{:ok, %<%= inspect schema.alias %>{}}
iex> delete_<%= schema.singular %>(<%= schema.singular %>)
{:error, %Ecto.Changeset{}}
"""
def delete_<%= schema.singular %>(%<%= inspect schema.alias %>{} = <%= schema.singular %>) do
Repo.delete(<%= schema.singular %>)
end
@doc """
Returns an `%Ecto.Changeset{}` for tracking <%= schema.singular %> changes.
## Examples
iex> change_<%= schema.singular %>(<%= schema.singular %>)
%Ecto.Changeset{source: %<%= inspect schema.alias %>{}}
"""
def change_<%= schema.singular %>(%<%= inspect schema.alias %>{} = <%= schema.singular %>) do
<%= inspect schema.alias %>.changeset(<%= schema.singular %>, %{})
end
| 25.701031 | 102 | 0.559968 |
f756226b91fb45002968e7a838b508f1ba8c9b68 | 26 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/DecimalWholeNumber.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/DecimalWholeNumber.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/matched_two_operation_parsing_test_case/DecimalWholeNumber.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | 1 ++ 2
3 -- 4
5..6
7 <> 8
| 5.2 | 6 | 0.307692 |
f7563c7e20afdb6e1b195d557683d86d9bae3d88 | 2,959 | exs | Elixir | elixir-agenda/test/hello_web/controllers/phone_controller_test.exs | Tigermisu/clase-lab-web | f71f6f414636355627e26ad2218c932896104b58 | [
"MIT"
] | null | null | null | elixir-agenda/test/hello_web/controllers/phone_controller_test.exs | Tigermisu/clase-lab-web | f71f6f414636355627e26ad2218c932896104b58 | [
"MIT"
] | null | null | null | elixir-agenda/test/hello_web/controllers/phone_controller_test.exs | Tigermisu/clase-lab-web | f71f6f414636355627e26ad2218c932896104b58 | [
"MIT"
] | null | null | null | defmodule HelloWeb.PhoneControllerTest do
use HelloWeb.ConnCase
alias Hello.Agenda
@create_attrs %{address: "some address", email: "some email", last_name: "some last_name", name: "some name", phone: "some phone", phone_type: "some phone_type"}
@update_attrs %{address: "some updated address", email: "some updated email", last_name: "some updated last_name", name: "some updated name", phone: "some updated phone", phone_type: "some updated phone_type"}
@invalid_attrs %{address: nil, email: nil, last_name: nil, name: nil, phone: nil, phone_type: nil}
def fixture(:phone) do
{:ok, phone} = Agenda.create_phone(@create_attrs)
phone
end
describe "index" do
test "lists all phones", %{conn: conn} do
conn = get conn, phone_path(conn, :index)
assert html_response(conn, 200) =~ "Listing Phones"
end
end
describe "new phone" do
test "renders form", %{conn: conn} do
conn = get conn, phone_path(conn, :new)
assert html_response(conn, 200) =~ "New Phone"
end
end
describe "create phone" do
test "redirects to show when data is valid", %{conn: conn} do
conn = post conn, phone_path(conn, :create), phone: @create_attrs
assert %{id: id} = redirected_params(conn)
assert redirected_to(conn) == phone_path(conn, :show, id)
conn = get conn, phone_path(conn, :show, id)
assert html_response(conn, 200) =~ "Show Phone"
end
test "renders errors when data is invalid", %{conn: conn} do
conn = post conn, phone_path(conn, :create), phone: @invalid_attrs
assert html_response(conn, 200) =~ "New Phone"
end
end
describe "edit phone" do
setup [:create_phone]
test "renders form for editing chosen phone", %{conn: conn, phone: phone} do
conn = get conn, phone_path(conn, :edit, phone)
assert html_response(conn, 200) =~ "Edit Phone"
end
end
describe "update phone" do
setup [:create_phone]
test "redirects when data is valid", %{conn: conn, phone: phone} do
conn = put conn, phone_path(conn, :update, phone), phone: @update_attrs
assert redirected_to(conn) == phone_path(conn, :show, phone)
conn = get conn, phone_path(conn, :show, phone)
assert html_response(conn, 200) =~ "some updated address"
end
test "renders errors when data is invalid", %{conn: conn, phone: phone} do
conn = put conn, phone_path(conn, :update, phone), phone: @invalid_attrs
assert html_response(conn, 200) =~ "Edit Phone"
end
end
describe "delete phone" do
setup [:create_phone]
test "deletes chosen phone", %{conn: conn, phone: phone} do
conn = delete conn, phone_path(conn, :delete, phone)
assert redirected_to(conn) == phone_path(conn, :index)
assert_error_sent 404, fn ->
get conn, phone_path(conn, :show, phone)
end
end
end
defp create_phone(_) do
phone = fixture(:phone)
{:ok, phone: phone}
end
end
| 33.247191 | 211 | 0.66171 |
f75646a39929f874b090a07c3407aebde9c5926b | 3,588 | ex | Elixir | lib/exshome_web/live/app_page.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | 2 | 2021-12-21T16:32:56.000Z | 2022-02-22T17:06:39.000Z | lib/exshome_web/live/app_page.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | null | null | null | lib/exshome_web/live/app_page.ex | exshome/exshome | ef6b7a89f11dcd2016856dd49517b74aeebb6513 | [
"MIT"
] | null | null | null | defmodule ExshomeWeb.Live.AppPage do
@moduledoc """
Generic module for app pages.
"""
alias Exshome.Dependency
alias Phoenix.LiveView
alias Phoenix.LiveView.Socket
import Phoenix.LiveView.Helpers
@callback action() :: atom()
@callback app_module() :: atom()
@callback view_module() :: atom()
@callback icon() :: String.t()
@callback path() :: String.t()
@callback dependencies() :: Keyword.t()
def on_mount(_, _params, _session, %Socket{} = socket) do
socket =
LiveView.attach_hook(
socket,
:dependency_hook,
:handle_info,
&__MODULE__.handle_info/2
)
deps =
for {dependency, key} <- get_dependencies(socket), into: %{} do
{key, Dependency.subscribe(dependency)}
end
{:cont, LiveView.assign(socket, deps: deps)}
end
def handle_info({Dependency, {module, value}}, %Socket{} = socket) do
key = get_dependencies(socket)[module]
if key do
socket = LiveView.update(socket, :deps, &Map.put(&1, key, value))
{:halt, socket}
else
{:cont, socket}
end
end
def handle_info(_event, %Socket{} = socket), do: {:cont, socket}
def render(%{socket: %Socket{} = socket, deps: deps} = assigns) do
missing_deps =
deps
|> Enum.filter(fn {_key, value} -> value == Dependency.NotReady end)
|> Enum.map(fn {key, _value} -> key end)
if Enum.any?(missing_deps) do
~H"Missing dependencies: <%= inspect(missing_deps) %>"
else
template = template_name(socket)
view_module(socket).render(template, assigns)
end
end
def validate_module!(%Macro.Env{module: module}, _bytecode) do
NimbleOptions.validate!(
module.__config__(),
dependencies: [type: :keyword_list],
icon: [type: :string]
)
end
defp get_dependencies(%Socket{view: view}), do: view.dependencies()
defp view_module(%Socket{view: view}) do
view.view_module()
end
defp template_name(%Socket{view: view}), do: view.path()
defmacro __using__(config) do
quote do
@action __MODULE__
|> Module.split()
|> List.last()
|> Macro.underscore()
|> String.to_atom()
@view_module __MODULE__
|> Module.split()
|> Enum.slice(0..0)
|> List.insert_at(-1, ["Web", "View"])
|> List.flatten()
|> Module.safe_concat()
@app_module __MODULE__
|> Module.split()
|> Enum.slice(0..0)
|> Module.safe_concat()
alias ExshomeWeb.Live.AppPage
@afer_compile {AppPage, :validate_module!}
@behaviour AppPage
@impl AppPage
def app_module, do: @app_module
@impl AppPage
def action, do: @action
@impl AppPage
def view_module, do: @view_module
@impl AppPage
def path, do: "#{@action}.html"
@impl AppPage
def icon, do: unquote(config[:icon] || "")
@impl AppPage
def dependencies, do: unquote(config[:dependencies])
use ExshomeWeb, :live_view
on_mount(AppPage)
def __config__, do: unquote(config)
@impl Phoenix.LiveView
defdelegate render(assigns), to: AppPage
end
end
@hook_module Application.compile_env(:exshome, :app_page_hook_module)
if @hook_module do
defoverridable(handle_info: 2)
def handle_info(event, %Socket{} = socket) do
original_result = super(event, socket)
@hook_module.handle_info(event, socket, original_result)
end
end
end
| 25.446809 | 74 | 0.603122 |
f756bfc331182af897035a1d2dfc0db9f89d5bc9 | 154 | exs | Elixir | class-1/hello_world/test/hello_world_test.exs | lucdelrio/elixir-training | 24ae5748fc945764dd1b3f673b408593c22f93a2 | [
"MIT"
] | null | null | null | class-1/hello_world/test/hello_world_test.exs | lucdelrio/elixir-training | 24ae5748fc945764dd1b3f673b408593c22f93a2 | [
"MIT"
] | 1 | 2020-05-07T15:39:30.000Z | 2020-05-07T15:39:30.000Z | class-1/hello_world/test/hello_world_test.exs | lucdelrio/elixir-training | 24ae5748fc945764dd1b3f673b408593c22f93a2 | [
"MIT"
] | null | null | null | defmodule HelloWorldTest do
use ExUnit.Case
doctest HelloWorld
test "greets the world" do
assert HelloWorld.hello() == "Hello World"
end
end
| 17.111111 | 46 | 0.727273 |
f756cdef18dd6280095915ab80b89e6076c6418b | 885 | ex | Elixir | lib/blurhash/utils.ex | rinpatch/blurhash | 2905adae167971a9ccc714c648bb43419ffb7118 | [
"MIT"
] | 5 | 2021-06-17T15:44:06.000Z | 2022-03-13T02:49:15.000Z | lib/blurhash/utils.ex | rinpatch/blurhash | 2905adae167971a9ccc714c648bb43419ffb7118 | [
"MIT"
] | null | null | null | lib/blurhash/utils.ex | rinpatch/blurhash | 2905adae167971a9ccc714c648bb43419ffb7118 | [
"MIT"
] | null | null | null | defmodule Blurhash.Utils do
def srgb_to_linear(srgb_color) do
value = srgb_color / 255
if value <= 0.04045,
do: value / 12.92,
else: :math.pow((value + 0.055) / 1.055, 2.4)
end
def linear_to_srgb(linear_color) do
value = max(0, min(1, linear_color))
if value <= 0.0031308,
do: round(value * 12.92 * 255 + 0.5),
else: round((1.055 * :math.pow(value, 1 / 2.4) - 0.055) * 255 + 0.5)
end
defp sign_pow(value, exponent) do
sign =
if value < 0,
do: -1,
else: 1
sign * :math.pow(abs(value), exponent)
end
def unquantize_color(quantized_color, max_ac),
do: sign_pow((quantized_color - 9) / 9, 2) * max_ac
def quantize_color(color, max_ac) do
value = floor(sign_pow(color / max_ac, 0.5) * 9 + 9.5)
cond do
value > 18 -> 18
value < 0 -> 0
true -> value
end
end
end
| 22.125 | 74 | 0.577401 |
f756d9c5488f181663e4b6539086d7912492edd0 | 219 | ex | Elixir | lib/ecto/query/having_builder.ex | knewter/ecto | faacfeef25e35c42b1e97323b03d5bed9ba51416 | [
"Apache-2.0"
] | null | null | null | lib/ecto/query/having_builder.ex | knewter/ecto | faacfeef25e35c42b1e97323b03d5bed9ba51416 | [
"Apache-2.0"
] | null | null | null | lib/ecto/query/having_builder.ex | knewter/ecto | faacfeef25e35c42b1e97323b03d5bed9ba51416 | [
"Apache-2.0"
] | null | null | null | defmodule Ecto.Query.HavingBuilder do
@moduledoc false
alias Ecto.Query.BuilderUtil
# Escapes a having expression, see `BuilderUtil.escape`
def escape(ast, vars) do
BuilderUtil.escape(ast, vars)
end
end
| 19.909091 | 57 | 0.748858 |
f756fc2c91817c419f3cb32b5caec9be46c1210f | 1,777 | ex | Elixir | clients/iap/lib/google_api/iap/v1/model/identity_aware_proxy_client.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | null | null | null | clients/iap/lib/google_api/iap/v1/model/identity_aware_proxy_client.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-12-18T09:25:12.000Z | 2020-12-18T09:25:12.000Z | clients/iap/lib/google_api/iap/v1/model/identity_aware_proxy_client.ex | medikent/elixir-google-api | 98a83d4f7bfaeac15b67b04548711bb7e49f9490 | [
"Apache-2.0"
] | 1 | 2020-10-04T10:12:44.000Z | 2020-10-04T10:12:44.000Z | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.IAP.V1.Model.IdentityAwareProxyClient do
@moduledoc """
Contains the data that describes an Identity Aware Proxy owned client.
## Attributes
* `displayName` (*type:* `String.t`, *default:* `nil`) - Human-friendly name given to the OAuth client.
* `name` (*type:* `String.t`, *default:* `nil`) - Output only. Unique identifier of the OAuth client.
* `secret` (*type:* `String.t`, *default:* `nil`) - Output only. Client secret of the OAuth client.
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:displayName => String.t(),
:name => String.t(),
:secret => String.t()
}
field(:displayName)
field(:name)
field(:secret)
end
defimpl Poison.Decoder, for: GoogleApi.IAP.V1.Model.IdentityAwareProxyClient do
def decode(value, options) do
GoogleApi.IAP.V1.Model.IdentityAwareProxyClient.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.IAP.V1.Model.IdentityAwareProxyClient do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 33.528302 | 107 | 0.714125 |
f7570eceb3cc9a417387a6051b3007e4d6de8da2 | 934 | ex | Elixir | web/controllers/start_controller.ex | Namuraid/backend | 04a10248bfeb156eb291207931621b40585d8f7e | [
"MIT"
] | null | null | null | web/controllers/start_controller.ex | Namuraid/backend | 04a10248bfeb156eb291207931621b40585d8f7e | [
"MIT"
] | null | null | null | web/controllers/start_controller.ex | Namuraid/backend | 04a10248bfeb156eb291207931621b40585d8f7e | [
"MIT"
] | null | null | null | defmodule Namuraid.StartController do
use Namuraid.Web, :controller
require Logger
def index(conn, _params) do
_render(conn)
end
def create(conn, %{"start" => %{"interval" => interval,
"count" => count, "from" => from, "running" => running} = start
} = _params) do
Namuraid.State.set(:startinterval, interval)
Namuraid.State.set(:startcount, count)
Namuraid.State.set(:startfrom, from)
Namuraid.State.set(:startrunning, running)
Namuraid.StartChannel.update(start)
conn
|> put_flash(:info, "Updated starting properties!")
|> redirect(to: start_path(conn, :index))
end
defp _render(conn) do
render(conn, "index.html",
interval: Namuraid.State.get(:startinterval, "300"),
count: Namuraid.State.get(:startcount, 30),
from: Namuraid.State.get(:startfrom, 1),
running: Namuraid.State.get(:startrunning, "false"))
end
end
| 31.133333 | 72 | 0.650964 |
f7572bdd04c631d5e3ab01659b0cbb542167c6d3 | 403 | exs | Elixir | config/test.exs | amattn/ElixirSlackWebAPI | 68071c10e49200b1788b5f7180c7457f9223136d | [
"MIT"
] | null | null | null | config/test.exs | amattn/ElixirSlackWebAPI | 68071c10e49200b1788b5f7180c7457f9223136d | [
"MIT"
] | null | null | null | config/test.exs | amattn/ElixirSlackWebAPI | 68071c10e49200b1788b5f7180c7457f9223136d | [
"MIT"
] | null | null | null | use Mix.Config
# Print only warnings and errors during test
config :logger, level: :warn, truncate: :infinity
# Here's an example of configuring this library to route requests through a Proxyman.io proxy.
# https://proxyman.io
# config :slack_web,
# :web_http_client_opts,
# proxy: {"127.0.0.1", 9090},
# hackney: [{:ssl_options, [{:cacertfile, "/path_to_cert/your_cert.pem"}]}]
| 31 | 94 | 0.689826 |
f75739137f5b72a948bcea64d2a068849a90348e | 1,729 | exs | Elixir | apps/resource_manager/test/resource_manager/identity/commands/get_identity_test.exs | lcpojr/watcher_ex | bd5a9210b5b41a6c9b5d4255de19fc6967d29fb7 | [
"Apache-2.0"
] | 9 | 2020-10-13T14:11:37.000Z | 2021-08-12T18:40:08.000Z | apps/resource_manager/test/resource_manager/identity/commands/get_identity_test.exs | lcpojr/watcher_ex | bd5a9210b5b41a6c9b5d4255de19fc6967d29fb7 | [
"Apache-2.0"
] | 28 | 2020-10-04T14:43:48.000Z | 2021-12-07T16:54:22.000Z | apps/resource_manager/test/resource_manager/identity/commands/get_identity_test.exs | lcpojr/watcher_ex | bd5a9210b5b41a6c9b5d4255de19fc6967d29fb7 | [
"Apache-2.0"
] | 3 | 2020-11-25T20:59:47.000Z | 2021-08-30T10:36:58.000Z | defmodule ResourceManager.Identities.Commands.GetIdentityTest do
@moduledoc false
use ResourceManager.DataCase, async: true
alias ResourceManager.Identities.Commands.GetIdentity
alias ResourceManager.Identities.Commands.Inputs.{GetClientApplication, GetUser}
alias ResourceManager.Identities.Schemas.{ClientApplication, User}
alias ResourceManager.Repo
setup do
{:ok, user: insert!(:user), application: insert!(:client_application)}
end
describe "#{GetIdentity}.execute/2" do
test "succeeds in getting user identity if params are valid", ctx do
input = %{
id: ctx.user.id,
username: ctx.user.username,
status: ctx.user.status
}
assert {:ok, %User{} = user} = GetIdentity.execute(input)
assert user == User |> Repo.one() |> Repo.preload([:password, :scopes, :totp])
end
test "succeeds in getting client application identity if params are valid", ctx do
input = %{
id: ctx.application.id,
client_id: ctx.application.client_id,
name: ctx.application.name,
status: ctx.application.status,
protocol: ctx.application.protocol,
access_type: ctx.application.access_type
}
assert {:ok, %ClientApplication{} = app} = GetIdentity.execute(input)
assert app == ClientApplication |> Repo.one() |> Repo.preload([:public_key, :scopes])
end
test "fails if user does not exist" do
assert {:error, :not_found} = GetIdentity.execute(%GetUser{id: Ecto.UUID.generate()})
end
test "fails if client application does not exist" do
assert {:error, :not_found} =
GetIdentity.execute(%GetClientApplication{id: Ecto.UUID.generate()})
end
end
end
| 33.901961 | 91 | 0.680162 |
f7574ec99ffb51a627174629742b38fbd86f1b45 | 126 | exs | Elixir | test/lwf_test.exs | lwfofficial/autovoting | 0f833415c0250aad3b09c0d286875c3454d9727a | [
"MIT"
] | 3 | 2018-07-12T11:58:34.000Z | 2018-07-14T08:49:22.000Z | test/lwf_test.exs | sgessa/lwf-pool-checker | 0f833415c0250aad3b09c0d286875c3454d9727a | [
"MIT"
] | null | null | null | test/lwf_test.exs | sgessa/lwf-pool-checker | 0f833415c0250aad3b09c0d286875c3454d9727a | [
"MIT"
] | null | null | null | defmodule LWFTest do
use ExUnit.Case
doctest LWF
test "greets the world" do
assert LWF.hello() == :world
end
end
| 14 | 32 | 0.68254 |
f75765ebdebbc9b5918ed7f8a07542692b82d777 | 1,666 | ex | Elixir | clients/classroom/lib/google_api/classroom/v1/model/cloud_pubsub_topic.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2021-12-20T03:40:53.000Z | 2021-12-20T03:40:53.000Z | clients/classroom/lib/google_api/classroom/v1/model/cloud_pubsub_topic.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | 1 | 2020-08-18T00:11:23.000Z | 2020-08-18T00:44:16.000Z | clients/classroom/lib/google_api/classroom/v1/model/cloud_pubsub_topic.ex | pojiro/elixir-google-api | 928496a017d3875a1929c6809d9221d79404b910 | [
"Apache-2.0"
] | null | null | null | # Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This file is auto generated by the elixir code generator program.
# Do not edit this file manually.
defmodule GoogleApi.Classroom.V1.Model.CloudPubsubTopic do
@moduledoc """
A reference to a Cloud Pub/Sub topic. To register for notifications, the owner of the topic must grant `[email protected]` the `projects.topics.publish` permission.
## Attributes
* `topicName` (*type:* `String.t`, *default:* `nil`) - The `name` field of a Cloud Pub/Sub [Topic](https://cloud.google.com/pubsub/docs/reference/rest/v1/projects.topics#Topic).
"""
use GoogleApi.Gax.ModelBase
@type t :: %__MODULE__{
:topicName => String.t() | nil
}
field(:topicName)
end
defimpl Poison.Decoder, for: GoogleApi.Classroom.V1.Model.CloudPubsubTopic do
def decode(value, options) do
GoogleApi.Classroom.V1.Model.CloudPubsubTopic.decode(value, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.Classroom.V1.Model.CloudPubsubTopic do
def encode(value, options) do
GoogleApi.Gax.ModelBase.encode(value, options)
end
end
| 35.446809 | 199 | 0.744898 |
f757edb57522f02bf43d3b07af01dfe1d3056ecc | 5 | ex | Elixir | testData/org/elixir_lang/parser_definition/matched_pipe_operation_parsing_test_case/DecimalWholeNumber.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 1,668 | 2015-01-03T05:54:27.000Z | 2022-03-25T08:01:20.000Z | testData/org/elixir_lang/parser_definition/matched_pipe_operation_parsing_test_case/DecimalWholeNumber.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 2,018 | 2015-01-01T22:43:39.000Z | 2022-03-31T20:13:08.000Z | testData/org/elixir_lang/parser_definition/matched_pipe_operation_parsing_test_case/DecimalWholeNumber.ex | keyno63/intellij-elixir | 4033e319992c53ddd42a683ee7123a97b5e34f02 | [
"Apache-2.0"
] | 145 | 2015-01-15T11:37:16.000Z | 2021-12-22T05:51:02.000Z | 1 | 2 | 5 | 5 | 0.4 |
f7582574068bf83b553e5f9dcc72ac348d010c67 | 2,268 | ex | Elixir | apps/ello_auth/lib/ello_auth/client_properties.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 16 | 2017-06-21T21:31:20.000Z | 2021-05-09T03:23:26.000Z | apps/ello_auth/lib/ello_auth/client_properties.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 25 | 2017-06-07T12:18:28.000Z | 2018-06-08T13:27:43.000Z | apps/ello_auth/lib/ello_auth/client_properties.ex | ello/apex | 4acb096b3ce172ff4ef9a51e5d068d533007b920 | [
"MIT"
] | 3 | 2018-06-14T15:34:07.000Z | 2022-02-28T21:06:13.000Z | defmodule Ello.Auth.ClientProperties do
use Plug.Builder
plug :android
plug :ios_version_from_header
plug :ios_version_from_ua
plug :ios
plug :webapp
plug :nudity
plug :nsfw
defp android(conn, _) do
with [ua | _] <- get_req_header(conn, "user_agent"),
true <- Regex.match?(~r/Ello Android/i, ua) do
assign(conn, :android, true)
else
_ -> assign(conn, :android, false)
end
end
defp ios_version_from_header(%{assigns: %{android: true}} = conn, _),
do: conn
defp ios_version_from_header(conn, _) do
case get_req_header(conn, "x-ios-build-number") do
[build | _] -> assign(conn, :ios_version, String.to_integer(build))
_ -> conn
end
end
defp ios_version_from_ua(%{assigns: %{ios_version: v}} = conn, _)
when is_integer(v),
do: conn
defp ios_version_from_ua(%{assigns: %{android: true}} = conn, _),
do: conn
defp ios_version_from_ua(conn, _) do
with [ua | _] <- get_req_header(conn, "user_agent"),
[_, build] <- Regex.run(~r[^Ello\/(\d{4,6}).*Darwin.*], ua) do
assign(conn, :ios_version, String.to_integer(build))
else
_ -> conn
end
end
defp ios(%{assigns: %{ios_version: v}} = conn, _) when is_integer(v),
do: assign(conn, :ios, true)
defp ios(conn, _),
do: assign(conn, :ios, false)
defp webapp(%{assigns: %{android: false, ios: false}} = conn, _),
do: assign(conn, :webapp, true)
defp webapp(conn, _),
do: assign(conn, :webapp, false)
defp nudity(%{assigns: %{allow_nudity: _preset}} = conn, _), do: conn
defp nudity(%{assigns: %{current_user: %{settings: %{views_adult_content: true}}}} = conn, _),
do: assign(conn, :allow_nudity, true)
defp nudity(%{assigns: %{webapp: true}} = conn, _),
do: assign(conn, :allow_nudity, true)
defp nudity(%{assigns: %{ios: true}} = conn, _),
do: assign(conn, :allow_nudity, true)
defp nudity(conn, _),
do: assign(conn, :allow_nudity, false)
defp nsfw(%{assigns: %{allow_nsfw: _preset}} = conn, _), do: conn
defp nsfw(%{assigns: %{current_user: %{settings: %{views_adult_content: allow_nsfw}}}} = conn, _),
do: assign(conn, :allow_nsfw, allow_nsfw)
defp nsfw(conn, _),
do: assign(conn, :allow_nsfw, false)
end
| 32.4 | 100 | 0.631393 |
f75826a9823f0880d75b3f8e32cc9fe17d8e9e52 | 258 | exs | Elixir | apps/performance_3/config/prod.exs | WhiteRookPL/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | 14 | 2017-08-09T14:21:47.000Z | 2022-03-11T04:10:49.000Z | apps/performance_3/config/prod.exs | nicholasjhenry/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | null | null | null | apps/performance_3/config/prod.exs | nicholasjhenry/elixir-fire-brigade-workshop | 1c6183339fc623842a09f4d10be75bcecf2c37e7 | [
"MIT"
] | 15 | 2017-09-05T15:43:53.000Z | 2020-04-13T16:20:18.000Z | use Mix.Config
config :metrics_collector, MetricsCollector.Web.Endpoint,
on_init: {MetricsCollector.Web.Endpoint, :load_from_system_env, []},
url: [
host: "example.com",
port: 80
]
config :logger, level: :info
import_config "prod.secret.exs" | 21.5 | 70 | 0.72093 |
f75826b8c40afd365419955ca18aa2c2dbb29940 | 1,523 | exs | Elixir | apps/banking_api/mix.exs | kmsskelly/banking_api | 89b8682e9317e045396bb783b7f0282ea8a4e13b | [
"Apache-2.0"
] | null | null | null | apps/banking_api/mix.exs | kmsskelly/banking_api | 89b8682e9317e045396bb783b7f0282ea8a4e13b | [
"Apache-2.0"
] | null | null | null | apps/banking_api/mix.exs | kmsskelly/banking_api | 89b8682e9317e045396bb783b7f0282ea8a4e13b | [
"Apache-2.0"
] | null | null | null | defmodule BankingApi.MixProject do
use Mix.Project
def project do
[
app: :banking_api,
version: "0.1.0",
build_path: "../../_build",
config_path: "../../config/config.exs",
deps_path: "../../deps",
lockfile: "../../mix.lock",
elixir: "~> 1.11",
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: {BankingApi.Application, []},
extra_applications: [:logger, :runtime_tools]
]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "test/support"]
defp elixirc_paths(_), do: ["lib"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[
{:phoenix_pubsub, "~> 2.0"},
{:ecto_sql, "~> 3.4"},
{:postgrex, ">= 0.0.0"},
{:jason, "~> 1.0"},
{:bcrypt_elixir, "~> 2.0"}
]
end
# Aliases are shortcuts or tasks specific to the current project.
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
[
setup: ["deps.get", "ecto.setup"],
"ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
test: ["ecto.create --quiet", "ecto.migrate --quiet", "test"]
]
end
end
| 25.813559 | 79 | 0.582403 |
f758424987f8ed71167b3b4135f7265d4b6e8043 | 529 | exs | Elixir | test/views/file_view_test.exs | ramkrishna70/opencov | 7a3415f8eebb797ad1f7b6c832daa4f04d70af8d | [
"MIT"
] | 189 | 2018-09-25T09:02:41.000Z | 2022-03-09T13:52:06.000Z | test/views/file_view_test.exs | ramkrishna70/opencov | 7a3415f8eebb797ad1f7b6c832daa4f04d70af8d | [
"MIT"
] | 29 | 2018-09-26T05:51:18.000Z | 2021-11-05T08:55:03.000Z | test/views/file_view_test.exs | ramkrishna70/opencov | 7a3415f8eebb797ad1f7b6c832daa4f04d70af8d | [
"MIT"
] | 32 | 2018-10-21T12:28:11.000Z | 2022-03-28T02:20:19.000Z | defmodule Opencov.FileViewTest do
use Opencov.ConnCase, async: true
import Opencov.FileView, only: [filters: 0, short_name: 1]
test "filters" do
assert Enum.count(filters()) == 4
end
test "short_name" do
assert short_name("foo/bar") == "foo/bar"
assert short_name("foo/bar/baz") == "foo/bar/baz"
f15 = String.duplicate("f", 15)
f20 = String.duplicate("f", 20)
assert short_name("foo/bar/baz/#{f20}") == "f/b/b/#{f20}"
assert short_name("foo/bar/baz/#{f15}") == "f/b/baz/#{f15}"
end
end
| 27.842105 | 63 | 0.635161 |
f75868c788f0099324fde5b7b038cf3ba02fb91e | 711 | ex | Elixir | lib/portalcs_web/gettext.ex | pedromcorreia/portal-construindo-sabere | 116402e21d9c1e7b02be2966460c90dcea7d09cd | [
"MIT"
] | null | null | null | lib/portalcs_web/gettext.ex | pedromcorreia/portal-construindo-sabere | 116402e21d9c1e7b02be2966460c90dcea7d09cd | [
"MIT"
] | null | null | null | lib/portalcs_web/gettext.ex | pedromcorreia/portal-construindo-sabere | 116402e21d9c1e7b02be2966460c90dcea7d09cd | [
"MIT"
] | null | null | null | defmodule PortalcsWeb.Gettext do
@moduledoc """
A module providing Internationalization with a gettext-based API.
By using [Gettext](https://hexdocs.pm/gettext),
your module gains a set of macros for translations, for example:
import PortalcsWeb.Gettext
# Simple translation
gettext "Here is the string to translate"
# Plural translation
ngettext "Here is the string to translate",
"Here are the strings to translate",
3
# Domain-based translation
dgettext "errors", "Here is the error message to translate"
See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
"""
use Gettext, otp_app: :portalcs
end
| 28.44 | 72 | 0.682138 |
f75899d445fcddffd3895637cbefe7ca8c9804c5 | 446 | exs | Elixir | backend/test/caffe_web/views/error_view_test.exs | eeng/caffe | d85d0dd56a8204c715052ddaf3d990e47c5df0e9 | [
"MIT"
] | 7 | 2020-03-27T08:26:52.000Z | 2021-08-29T09:50:31.000Z | backend/test/caffe_web/views/error_view_test.exs | eeng/caffe | d85d0dd56a8204c715052ddaf3d990e47c5df0e9 | [
"MIT"
] | null | null | null | backend/test/caffe_web/views/error_view_test.exs | eeng/caffe | d85d0dd56a8204c715052ddaf3d990e47c5df0e9 | [
"MIT"
] | null | null | null | defmodule CaffeWeb.ErrorViewTest do
use CaffeWeb.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(CaffeWeb.ErrorView, "404.json", []) == %{errors: %{detail: "Not Found"}}
end
test "renders 500.json" do
assert render(CaffeWeb.ErrorView, "500.json", []) ==
%{errors: %{detail: "Internal Server Error"}}
end
end
| 27.875 | 90 | 0.67713 |
f7589dacde97d65ca8c0d508a772107423348291 | 68 | ex | Elixir | lib/events_tools_web/views/tag_view.ex | Apps-Team/conferencetools | ce2e16a3e4a521dc4682e736a209e6dd380c050d | [
"Apache-2.0"
] | null | null | null | lib/events_tools_web/views/tag_view.ex | Apps-Team/conferencetools | ce2e16a3e4a521dc4682e736a209e6dd380c050d | [
"Apache-2.0"
] | 6 | 2017-10-05T20:16:34.000Z | 2017-10-05T20:36:11.000Z | lib/events_tools_web/views/tag_view.ex | apps-team/events-tools | ce2e16a3e4a521dc4682e736a209e6dd380c050d | [
"Apache-2.0"
] | null | null | null | defmodule EventsToolsWeb.TagView do
use EventsToolsWeb, :view
end
| 17 | 35 | 0.823529 |
f758b1845341119049d66d54a47029c1b3cc6f35 | 52 | ex | Elixir | lib/ueberauth_linear.ex | withbroadcast/ueberauth-linear | 5ad958ce2556d808a6dd8e6238ae2b4d5af4a25d | [
"MIT"
] | 3 | 2021-07-01T16:18:01.000Z | 2021-07-01T18:27:28.000Z | lib/ueberauth_linear.ex | withbroadcast/ueberauth_linear | 5ad958ce2556d808a6dd8e6238ae2b4d5af4a25d | [
"MIT"
] | null | null | null | lib/ueberauth_linear.ex | withbroadcast/ueberauth_linear | 5ad958ce2556d808a6dd8e6238ae2b4d5af4a25d | [
"MIT"
] | null | null | null | defmodule UeberauthLinear do
@moduledoc false
end
| 13 | 28 | 0.826923 |
f75909dd33a65d595bb0d410fe164c4db7c57f63 | 1,808 | exs | Elixir | onboarding/service/mix.exs | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | 10 | 2018-04-12T22:29:52.000Z | 2021-10-18T17:07:45.000Z | onboarding/service/mix.exs | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | null | null | null | onboarding/service/mix.exs | FoxComm/highlander | 1aaf8f9e5353b94c34d574c2a92206a1c363b5be | [
"MIT"
] | 1 | 2018-07-06T18:42:05.000Z | 2018-07-06T18:42:05.000Z | defmodule OnboardingService.Mixfile do
use Mix.Project
def project do
[app: :onboarding_service,
version: "0.0.1",
elixir: "~> 1.2",
elixirc_paths: elixirc_paths(Mix.env),
erlc_paths: ["erl"],
compilers: [:phoenix, :gettext] ++ Mix.compilers,
build_embedded: Mix.env == :prod,
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: {OnboardingService, []},
applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext,
:phoenix_ecto, :postgrex]]
end
# Specifies which paths to compile per environment.
defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
defp elixirc_paths(_), do: ["lib", "web"]
# Specifies your project dependencies.
#
# Type `mix help deps` for examples and options.
defp deps do
[{:phoenix, "~> 1.2.1"},
{:phoenix_pubsub, "~> 1.0"},
{:phoenix_ecto, "~> 3.0"},
{:postgrex, ">= 0.0.0"},
{:phoenix_html, "~> 2.6"},
{:phoenix_live_reload, "~> 1.0", only: :dev},
{:gettext, "~> 0.11"},
{:cowboy, "~> 1.0"},
{:ecto_state_machine, "~> 0.1.0"},
{:json_web_token, "~> 0.2"},
{:httpoison, "~> 0.9.0"}]
end
# Aliases are shortcuts or tasks specific to the current project.
# For example, to create, migrate and run the seeds file at once:
#
# $ mix ecto.setup
#
# See the documentation for `Mix` for more info on aliases.
defp aliases do
["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
"ecto.reset": ["ecto.drop", "ecto.setup"],
"test": ["ecto.create --quiet", "ecto.migrate", "test"]]
end
end
| 30.644068 | 89 | 0.599558 |
f7594a230a7c9cb7162474bd5a0ee9351ea2f641 | 323 | ex | Elixir | lib/list_process.ex | hacksu/elixir-basics | 37e791d3f6a6af2ee328aadb1cb31c7f67492363 | [
"MIT"
] | null | null | null | lib/list_process.ex | hacksu/elixir-basics | 37e791d3f6a6af2ee328aadb1cb31c7f67492363 | [
"MIT"
] | null | null | null | lib/list_process.ex | hacksu/elixir-basics | 37e791d3f6a6af2ee328aadb1cb31c7f67492363 | [
"MIT"
] | null | null | null | defmodule ListProcess do
def start_link do
Task.start_link fn -> loop([]) end
end
def loop(list) do
receive do
{:get, caller} ->
send caller, list
loop list
{:add, item} ->
loop list ++ [item]
{:remove, item} ->
loop List.delete(list, item)
end
end
end | 19 | 38 | 0.544892 |
f7595db7425e7f17719af1f2baa2f43dcdcc2283 | 3,385 | ex | Elixir | lib/absinthe/type/object.ex | pulkit110/absinthe | fa2060307a401d0943bde72d08267602e4027889 | [
"MIT"
] | null | null | null | lib/absinthe/type/object.ex | pulkit110/absinthe | fa2060307a401d0943bde72d08267602e4027889 | [
"MIT"
] | null | null | null | lib/absinthe/type/object.ex | pulkit110/absinthe | fa2060307a401d0943bde72d08267602e4027889 | [
"MIT"
] | null | null | null | defmodule Absinthe.Type.Object do
@moduledoc """
Represents a non-leaf node in a GraphQL tree of information.
Objects represent a list of named fields, each of which yield a value of a
specific type. Object values are serialized as unordered maps, where the
queried field names (or aliases) are the keys and the result of evaluating the
field is the value.
Also see `Absinthe.Type.Scalar`.
## Examples
Given a type defined as the following (see `Absinthe.Schema.Notation.object/3`):
```
@desc "A person"
object :person do
field :name, :string
field :age, :integer
field :best_friend, :person
field :pets, list_of(:pet)
end
```
The "Person" type (referred inside Absinthe as `:person`) is an object, with
fields that use `Absinthe.Type.Scalar` types (namely `:name` and `:age`), and
other `Absinthe.Type.Object` types (`:best_friend` and `:pets`, assuming
`:pet` is an object).
Given we have a query that supports getting a person by name
(see `Absinthe.Schema`), and a query document like the following:
```graphql
{
person(name: "Joe") {
name
best_friend {
name
age
}
pets {
breed
}
}
}
```
We could get a result like this:
```
%{
data: %{
"person" => %{
"best_friend" => %{
"name" => "Jill",
"age" => 29
},
"pets" => [
%{"breed" => "Wyvern"},
%{"breed" => "Royal Griffon"}
]
}
}
}
```
"""
alias Absinthe.Type
use Absinthe.Introspection.TypeKind, :object
@typedoc """
A defined object type.
Note new object types (with the exception of the root-level `query`, `mutation`, and `subscription`)
should be defined using `Absinthe.Schema.Notation.object/3`.
* `:name` - The name of the object type. Should be a TitleCased `binary`. Set automatically.
* `:description` - A nice description for introspection.
* `:fields` - A map of `Absinthe.Type.Field` structs. Usually built via `Absinthe.Schema.Notation.field/4`.
* `:interfaces` - A list of interfaces that this type guarantees to implement. See `Absinthe.Type.Interface`.
* `:is_type_of` - A function used to identify whether a resolved object belongs to this defined type. For use with `:interfaces` entry and `Absinthe.Type.Interface`. This function will be passed one argument; the object whose type needs to be identified, and should return `true` when the object matches this type.
The `__private__` and `:__reference__` keys are for internal use.
"""
@type t :: %__MODULE__{
identifier: atom,
name: binary,
description: binary,
fields: map,
interfaces: [Absinthe.Type.Interface.t()],
__private__: Keyword.t(),
definition: module,
__reference__: Type.Reference.t()
}
defstruct identifier: nil,
name: nil,
description: nil,
fields: nil,
interfaces: [],
__private__: [],
definition: nil,
__reference__: nil,
is_type_of: nil
@doc false
defdelegate functions, to: Absinthe.Blueprint.Schema.ObjectTypeDefinition
@doc false
@spec field(t, atom) :: Absinthe.Type.Field.t()
def field(%{fields: fields}, identifier) do
fields
|> Map.get(identifier)
end
end
| 28.931624 | 316 | 0.626883 |
f75966931e9dc456546eecf532d6a0f7aac8341d | 2,692 | ex | Elixir | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/export_context.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/export_context.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | null | null | null | clients/sql_admin/lib/google_api/sql_admin/v1beta4/model/export_context.ex | GoNZooo/elixir-google-api | cf3ad7392921177f68091f3d9001f1b01b92f1cc | [
"Apache-2.0"
] | 1 | 2018-07-28T20:50:50.000Z | 2018-07-28T20:50:50.000Z | # Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE: This class is auto generated by the swagger code generator program.
# https://github.com/swagger-api/swagger-codegen.git
# Do not edit the class manually.
defmodule GoogleApi.SQLAdmin.V1beta4.Model.ExportContext do
@moduledoc """
Database instance export context.
## Attributes
- csvExportOptions (ExportContextCsvExportOptions): Defaults to: `null`.
- databases (List[String]): Databases (for example, guestbook) from which the export is made. If fileType is SQL and no database is specified, all databases are exported. If fileType is CSV, you can optionally specify at most one database to export. If csvExportOptions.selectQuery also specifies the database, this field will be ignored. Defaults to: `null`.
- fileType (String): The file type for the specified uri. SQL: The file contains SQL statements. CSV: The file contains CSV data. Defaults to: `null`.
- kind (String): This is always sql#exportContext. Defaults to: `null`.
- sqlExportOptions (ExportContextSqlExportOptions): Defaults to: `null`.
- uri (String): The path to the file in Google Cloud Storage where the export will be stored. The URI is in the form gs://bucketName/fileName. If the file already exists, the operation fails. If fileType is SQL and the filename ends with .gz, the contents are compressed. Defaults to: `null`.
"""
defstruct [
:"csvExportOptions",
:"databases",
:"fileType",
:"kind",
:"sqlExportOptions",
:"uri"
]
end
defimpl Poison.Decoder, for: GoogleApi.SQLAdmin.V1beta4.Model.ExportContext do
import GoogleApi.SQLAdmin.V1beta4.Deserializer
def decode(value, options) do
value
|> deserialize(:"csvExportOptions", :struct, GoogleApi.SQLAdmin.V1beta4.Model.ExportContextCsvExportOptions, options)
|> deserialize(:"sqlExportOptions", :struct, GoogleApi.SQLAdmin.V1beta4.Model.ExportContextSqlExportOptions, options)
end
end
defimpl Poison.Encoder, for: GoogleApi.SQLAdmin.V1beta4.Model.ExportContext do
def encode(value, options) do
GoogleApi.SQLAdmin.V1beta4.Deserializer.serialize_non_nil(value, options)
end
end
| 45.627119 | 361 | 0.758172 |
f75996f1ecda7dc90feaa62279f62e598cd1f7fd | 9,365 | exs | Elixir | test/central_web/controllers/account/forgotten_password_controller_test.exs | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 4 | 2021-07-29T16:23:20.000Z | 2022-02-23T05:34:36.000Z | test/central_web/controllers/account/forgotten_password_controller_test.exs | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 14 | 2021-08-01T02:36:14.000Z | 2022-01-30T21:15:03.000Z | test/central_web/controllers/account/forgotten_password_controller_test.exs | badosu/teiserver | 19b623aeb7c2ab28756405f7486e92b714777c54 | [
"MIT"
] | 7 | 2021-05-13T12:55:28.000Z | 2022-01-14T06:39:06.000Z | defmodule CentralWeb.Account.ForgottenPasswordControllerTest do
use CentralWeb.ConnCase
alias Central.Account
alias Central.Helpers.GeneralTestLib
use Bamboo.Test
setup do
GeneralTestLib.conn_setup([], [:no_login])
end
describe "mark password as forgotten" do
test "render form", %{conn: conn} do
conn = get(conn, Routes.account_session_path(conn, :forgot_password))
assert html_response(conn, 200) =~
"Please enter the email address of your account here. A link to reset your password will be sent to the address."
end
end
describe "submit request" do
test "email2 - not empty", %{conn: conn} do
dummy = GeneralTestLib.make_user()
conn =
post(conn, Routes.account_session_path(conn, :send_password_reset),
email: dummy.email,
email2: dummy.email
)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["success"] == nil
assert conn.private[:phoenix_flash]["warning"] == nil
assert conn.private[:phoenix_flash]["info"] == nil
end
test "just email", %{conn: conn} do
dummy = GeneralTestLib.make_user()
conn =
post(conn, Routes.account_session_path(conn, :send_password_reset),
email: dummy.email,
email2: ""
)
assert html_response(conn, 200) =~ "Password reset request"
assert conn.private[:phoenix_flash]["success"] == nil
assert conn.private[:phoenix_flash]["warning"] == nil
assert conn.private[:phoenix_flash]["info"] == "Form timeout"
end
test "Existing request", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, _code} =
Account.create_code(%{
value: "existing-request-test-code",
purpose: "reset_password",
expires: Timex.now() |> Timex.shift(hours: 24),
user_id: dummy.id
})
conn =
post(conn, Routes.account_session_path(conn, :send_password_reset),
email: dummy.email,
email2: ""
)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["success"] == "Existing password reset already sent out"
assert conn.private[:phoenix_flash]["warning"] == nil
assert conn.private[:phoenix_flash]["info"] == nil
end
test "bad key-value pair", %{conn: conn} do
dummy = GeneralTestLib.make_user()
key = "bad-key-value-pair-key"
value = "bad-key-value-pair-value"
ConCache.put(:codes, key, value)
conn =
post(conn, Routes.account_session_path(conn, :send_password_reset),
email: dummy.email,
email2: "",
key: key,
value: "x"
)
assert html_response(conn, 200) =~ "Password reset request"
assert conn.private[:phoenix_flash]["success"] == nil
assert conn.private[:phoenix_flash]["warning"] == nil
assert conn.private[:phoenix_flash]["info"] == "The form has timed out"
end
test "no user", %{conn: conn} do
key = "no-user-key"
value = "no-user-value"
ConCache.put(:codes, key, value)
params = %{
"email" => "no-user-email@x",
"email2" => "",
"key" => key,
key => value
}
conn = post(conn, Routes.account_session_path(conn, :send_password_reset), params)
assert html_response(conn, 200) =~ "Password reset request"
assert conn.private[:phoenix_flash]["success"] == nil
assert conn.private[:phoenix_flash]["warning"] == nil
assert conn.private[:phoenix_flash]["info"] == "No user by that email"
end
test "correctly submitted", %{conn: conn} do
dummy = GeneralTestLib.make_user()
key = "correctly-submitted-key"
value = "correctly-submitted-value"
ConCache.put(:codes, key, value)
params = %{
"email" => dummy.email,
"email2" => "",
"key" => key,
key => value
}
conn = post(conn, Routes.account_session_path(conn, :send_password_reset), params)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["success"] == "Password reset sent out"
assert conn.private[:phoenix_flash]["warning"] == nil
assert conn.private[:phoenix_flash]["info"] == nil
code =
Account.list_codes(
where: [
user_id: dummy.id,
purpose: "reset_password"
]
)
|> hd
expected_email = Central.Account.Emails.password_reset(dummy, code)
Central.Mailer.deliver_now(expected_email)
assert_delivered_email(expected_email)
end
end
describe "reset password form" do
test "no link", %{conn: conn} do
conn =
get(conn, Routes.account_session_path(conn, :password_reset_form, "--non-valid-code--"))
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["warning"] == "Unable to find link"
end
test "not a reset_password link", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "not-password-reset",
purpose: "not-password-reset",
expires: Timex.now() |> Timex.shift(hours: 24),
user_id: dummy.id
})
conn = get(conn, Routes.account_session_path(conn, :password_reset_form, code.value))
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["warning"] == "Link cannot be found"
end
test "expired", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "expired-password-reset",
purpose: "reset_password",
expires: Timex.now() |> Timex.shift(hours: -24),
user_id: dummy.id
})
conn = get(conn, Routes.account_session_path(conn, :password_reset_form, code.value))
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["warning"] == "Link has expired"
end
test "good link", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "expired-password-reset",
purpose: "reset_password",
expires: Timex.now() |> Timex.shift(hours: 24),
user_id: dummy.id
})
conn = get(conn, Routes.account_session_path(conn, :password_reset_form, code.value))
assert html_response(conn, 200) =~ "Password reset form"
assert html_response(conn, 200) =~ "Please enter your new password."
end
end
describe "reset password post" do
test "nil code", %{conn: conn} do
conn =
post(conn, Routes.account_session_path(conn, :password_reset_post, "--no-code-value--"),
pass1: "",
pass2: ""
)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["warning"] == "Unable to find link"
end
test "bad purpose", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "not-password-reset",
purpose: "not-password-reset",
expires: Timex.now() |> Timex.shift(hours: 24),
user_id: dummy.id
})
conn =
post(conn, Routes.account_session_path(conn, :password_reset_post, code.value),
pass1: "",
pass2: ""
)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["warning"] == "Link cannot be found"
end
test "expired", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "expired-password-reset",
purpose: "reset_password",
expires: Timex.now() |> Timex.shift(hours: -24),
user_id: dummy.id
})
conn =
post(conn, Routes.account_session_path(conn, :password_reset_post, code.value),
pass1: "",
pass2: ""
)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["warning"] == "Link has expired"
end
test "passwords don't line up", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "not-lining-up",
purpose: "reset_password",
expires: Timex.now() |> Timex.shift(hours: 24),
user_id: dummy.id
})
conn =
post(conn, Routes.account_session_path(conn, :password_reset_post, code.value),
pass1: "valid",
pass2: "noooope"
)
assert html_response(conn, 200) =~ "Password reset form"
assert conn.private[:phoenix_flash]["warning"] == "Passwords need to match"
end
test "correct", %{conn: conn} do
dummy = GeneralTestLib.make_user()
{:ok, code} =
Account.create_code(%{
value: "valid-reset",
purpose: "reset_password",
expires: Timex.now() |> Timex.shift(hours: 24),
user_id: dummy.id
})
conn =
post(conn, Routes.account_session_path(conn, :password_reset_post, code.value),
pass1: "password1",
pass2: "password1"
)
assert redirected_to(conn) == "/"
assert conn.private[:phoenix_flash]["success"] == "Your password has been reset."
end
end
end
| 30.907591 | 128 | 0.595729 |
f759a28c929139d5ca4c2b89ed99150d7e4604cb | 3,229 | exs | Elixir | test/ecto/repo/autogenerate_test.exs | jccf091/ecto | 42d47a6da0711f842e1a0e6724a89b318b9b2144 | [
"Apache-2.0"
] | null | null | null | test/ecto/repo/autogenerate_test.exs | jccf091/ecto | 42d47a6da0711f842e1a0e6724a89b318b9b2144 | [
"Apache-2.0"
] | null | null | null | test/ecto/repo/autogenerate_test.exs | jccf091/ecto | 42d47a6da0711f842e1a0e6724a89b318b9b2144 | [
"Apache-2.0"
] | null | null | null | alias Ecto.TestRepo
defmodule Ecto.Repo.AutogenerateTest do
use ExUnit.Case, async: true
defmodule Manager do
use Ecto.Schema
@timestamps_opts [inserted_at: :created_on]
schema "manager" do
timestamps updated_at: :updated_on, type: :utc_datetime
end
end
defmodule Company do
use Ecto.Schema
schema "default" do
field :code, Ecto.UUID, autogenerate: true
has_one :manager, Manager
timestamps()
end
end
## Autogenerate
@uuid "30313233-3435-4637-9839-616263646566"
test "autogenerates values" do
schema = TestRepo.insert!(%Company{})
assert byte_size(schema.code) == 36
changeset = Ecto.Changeset.cast(%Company{}, %{}, [])
schema = TestRepo.insert!(changeset)
assert byte_size(schema.code) == 36
changeset = Ecto.Changeset.cast(%Company{}, %{code: nil}, [])
schema = TestRepo.insert!(changeset)
assert byte_size(schema.code) == 36
changeset = Ecto.Changeset.force_change(changeset, :code, nil)
schema = TestRepo.insert!(changeset)
assert schema.code == nil
changeset = Ecto.Changeset.cast(%Company{}, %{code: @uuid}, [:code])
schema = TestRepo.insert!(changeset)
assert schema.code == @uuid
end
## Timestamps
test "sets inserted_at and updated_at values" do
default = TestRepo.insert!(%Company{})
assert %NaiveDateTime{} = default.inserted_at
assert %NaiveDateTime{} = default.updated_at
assert_received {:insert, _}
# No change
changeset = Ecto.Changeset.change(%Company{id: 1})
default = TestRepo.update!(changeset)
refute default.inserted_at
refute default.updated_at
refute_received {:update, _}
# Change in children
changeset = Ecto.Changeset.change(%Company{id: 1})
default = TestRepo.update!(Ecto.Changeset.put_assoc(changeset, :manager, %Manager{}))
refute default.inserted_at
refute default.updated_at
assert_received {:insert, _}
refute_received {:update, _}
# Force change
changeset = Ecto.Changeset.change(%Company{id: 1})
default = TestRepo.update!(changeset, force: true)
refute default.inserted_at
assert %NaiveDateTime{} = default.updated_at
assert_received {:update, _}
end
test "does not set inserted_at and updated_at values if they were previously set" do
naive_datetime = ~N[2000-01-01 00:00:00]
default = TestRepo.insert!(%Company{inserted_at: naive_datetime,
updated_at: naive_datetime})
assert default.inserted_at == naive_datetime
assert default.updated_at == naive_datetime
changeset = Ecto.Changeset.change(%Company{id: 1}, updated_at: naive_datetime)
default = TestRepo.update!(changeset)
refute default.inserted_at
assert default.updated_at == naive_datetime
end
test "sets custom inserted_at and updated_at values" do
default = TestRepo.insert!(%Manager{})
assert %DateTime{time_zone: "Etc/UTC"} = default.created_on
assert %DateTime{time_zone: "Etc/UTC"} = default.updated_on
default = TestRepo.update!(%Manager{id: 1} |> Ecto.Changeset.change, force: true)
refute default.created_on
assert %DateTime{time_zone: "Etc/UTC"} = default.updated_on
end
end
| 31.048077 | 89 | 0.693404 |
f759bb3ea005daecedaab8ae28fe41e347cdac15 | 189 | ex | Elixir | lib/draft_web/controllers/admin_controller.ex | paulswartz/draft | fc0653d75b39e861c4705545cfb86ad7cd0e2cd2 | [
"MIT"
] | null | null | null | lib/draft_web/controllers/admin_controller.ex | paulswartz/draft | fc0653d75b39e861c4705545cfb86ad7cd0e2cd2 | [
"MIT"
] | null | null | null | lib/draft_web/controllers/admin_controller.ex | paulswartz/draft | fc0653d75b39e861c4705545cfb86ad7cd0e2cd2 | [
"MIT"
] | null | null | null | defmodule DraftWeb.AdminController do
use DraftWeb, :controller
@spec index(Plug.Conn.t(), map) :: Plug.Conn.t()
def index(conn, _params) do
render(conn, "index.html")
end
end
| 21 | 50 | 0.693122 |