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
f7659df16ba40172566be809bf50725c62e7e767
1,641
ex
Elixir
lib/crit/reservations/reservation_impl/write.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
6
2019-07-16T19:31:23.000Z
2021-06-05T19:01:05.000Z
lib/crit/reservations/reservation_impl/write.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
null
null
null
lib/crit/reservations/reservation_impl/write.ex
brownt23/crit19
c45c7b3ae580c193168d83144da0eeb9bc91c8a9
[ "MIT" ]
3
2020-02-24T23:38:27.000Z
2020-08-01T23:50:17.000Z
defmodule Crit.Reservations.ReservationImpl.Write do alias Crit.Schemas alias Crit.Reservations.RestPeriod alias Crit.Sql alias Ecto.Multi alias Crit.Sql.CommonQuery def create(struct, institution) do struct_to_changeset(struct) |> Sql.insert(institution) end def create_noting_conflicts(struct, institution) do animals_query = CommonQuery.start_by_ids(Schemas.Animal, struct.chosen_animal_ids) service_gap_animals_fn = fn _repo, _so_far -> {:ok, Schemas.ServiceGap.unavailable_by(animals_query, struct.date, institution)} end use_animals_fn = fn _repo, _so_far -> {:ok, Schemas.Use.unavailable_by(animals_query, struct.span, institution)} end rest_periods_fn = fn _repo, _so_far -> {:ok, RestPeriod.unavailable_by(struct, institution)} end changeset = struct_to_changeset(struct) {:ok, result} = Multi.new |> Multi.run(:service_gap, service_gap_animals_fn) |> Multi.run(:use, use_animals_fn) |> Multi.run(:rest_period, rest_periods_fn) |> Multi.insert(:insert, changeset, Sql.multi_opts(institution)) |> Sql.transaction(institution) conflicts = %{ service_gap: result.service_gap, use: result.use, rest_period: result.rest_period } {:ok, result.insert, conflicts} end defp struct_to_changeset(struct) do uses = Schemas.Use.cross_product( struct.chosen_animal_ids, struct.chosen_procedure_ids) attrs = Map.from_struct(struct) |> Map.put(:uses, uses) Schemas.Reservation.changeset(%Schemas.Reservation{}, attrs) end end
26.901639
87
0.69348
f765c03d5425f0ecebf477fc4f1a0833696809e6
6
ex
Elixir
testData/org/elixir_lang/parser_definition/eol_to_whitespace/ClosingBracket.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/eol_to_whitespace/ClosingBracket.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/eol_to_whitespace/ClosingBracket.ex
keyno63/intellij-elixir
4033e319992c53ddd42a683ee7123a97b5e34f02
[ "Apache-2.0" ]
145
2015-01-15T11:37:16.000Z
2021-12-22T05:51:02.000Z
[1 ]
1.5
2
0.166667
f765d3da051c5c44de92f372717b3678b1fb6ed6
6,359
ex
Elixir
lib/ex_health.ex
kianmeng/ex_health
f7311d5e23e8cfbb6dd91381a52a420345331535
[ "MIT" ]
null
null
null
lib/ex_health.ex
kianmeng/ex_health
f7311d5e23e8cfbb6dd91381a52a420345331535
[ "MIT" ]
null
null
null
lib/ex_health.ex
kianmeng/ex_health
f7311d5e23e8cfbb6dd91381a52a420345331535
[ "MIT" ]
null
null
null
defmodule ExHealth do @moduledoc """ [![CircleCI](https://circleci.com/gh/Kartstig/ex_health/tree/master.svg?style=svg&circle-token=8ed28fee90111e2a034b0d71e0fcf8ae18bba641)](https://circleci.com/gh/Kartstig/ex_health/tree/master) [![codecov](https://codecov.io/gh/Kartstig/ex_health/branch/master/graph/badge.svg)](https://codecov.io/gh/Kartstig/ex_health) ExHealth is a simple extensible health check utility that monitors your applications. By itself, ExHealth is a supervised GenServer that periodically performs a set of checks, but you can easily configure your it to serve JSON responses that look like: { last_check:"2018-09-18T06:43:53.773719Z", result:{ check_results:[ [ "Database", "ok" ], [ "PhoenixExampleWeb_Endpoint", "ok" ] ], msg:"healthy" } } # Getting Started Configuration for ExHealth must be present the Application environment. This can be done by updating the `:ex_health` values in your `config/config.exs`: config :ex_health, module: MyApplication.HealthChecks, interval_ms: 1000 Then you must define a module `MyApplication.HealthChecks` with some checks: defmodule MyApplication.HealthChecks do process_check(MyApplication.CacheServer) test "Redis" do MyRedis.ping() # This should return :ok | {:error, "Message"} end end # Integrating with Phoenix To integrate with [Phoenix](https://hexdocs.pm/phoenix/Phoenix.html) or any other web framework, you can take advantage of `ExHealth.Plug` which handles serving a JSON response for you. See `ExHealth.Plug` for instructions. """ use Application @function_prefix "hc__" @doc """ Defines a healthcheck function. Takes the following arguments: 1. `name` - a string for the name of the health check 2. `block` - block that returns `:ok | true | {:error, "Reason"}` ## Examples: defmodule MyApp.HealthChecks do health_check("Database") do MyDB.ping() # This should return :ok | true | {:error, "Reason"} end end """ defmacro health_check(name, do: block) do function_name = String.to_atom("#{@function_prefix}" <> name) quote do def unquote(function_name)() do try do unquote(block) rescue _ -> {:error, "Error in HealthCheck"} end end end end @doc """ Defines a healthcheck function for a given process. Returns `:ok` if the process has one of the following statuses: - `:running` - `:waiting` See [Process.info/1](https://hexdocs.pm/elixir/Process.html#info/1) for more information about process status. ## Examples: defmodule MyApp.HealthChecks do process_check(MyApp.SomeImportantService) end """ defmacro process_check({_, _, module_list} = _module) do {module, _} = Code.eval_string(Enum.join(module_list, ".")) function_name = String.to_atom("#{@function_prefix}" <> Enum.join(module_list, "_")) quote do def unquote(function_name)() do with pid when not is_nil(pid) <- Process.whereis(unquote(module)), info <- Process.info(pid), {:ok, status} <- Keyword.fetch(info, :status), status == :running || :waiting do :ok else nil -> {:error, "no proc"} _ -> {:error, "process not running/waiting"} end end end end defimpl Jason.Encoder, for: [Tuple] do def encode(tuple, opts) do Jason.Encode.list(Tuple.to_list(tuple), opts) end end @doc """ Starts the application with empty state """ def start() do start(:normal, state: %ExHealth.Status{}) end def start(_type, args) do import Supervisor.Spec configure(args) initial_state = load_config() children = [ supervisor(ExHealth.HealthServer, [initial_state]) ] opts = [strategy: :one_for_one, name: ExHealth.Supervisor] Supervisor.start_link(children, opts) end @doc """ Synchronously fetches the latest status from `ExHealth.HealthServer` ## Examples: iex(1)> ExHealth.status() %ExHealth.Status{ checks: [ %ExHealth.Check{ mfa: {ExHealth.SelfCheck, :hc__ExHealth_HealthServer, []}, name: "ExHealth_HealthServer" } ], interval_ms: 15000, last_check: nil, result: %{check_results: [], msg: :pending} } """ @spec status() :: ExHealth.Status.t() def status() do GenServer.call(ExHealth.HealthServer, :status) end @doc """ Stops the Application """ @spec stop() :: :ok def stop() do Supervisor.stop(ExHealth.Supervisor, :normal) end defp configure([]), do: nil defp configure([{k, v} | remainder]) do Application.put_env(:ex_health, k, v) configure(remainder) end defp extract_health_checks(module) do hc_regex = ~r/#{@function_prefix}.*/ module.__info__(:functions) |> Enum.filter(fn {func, _arr} -> Atom.to_string(func) =~ hc_regex end) end @spec extract_and_transform(module()) :: list(ExHealth.Check.t()) defp extract_and_transform(module) do function_list = extract_health_checks(module) for {func, _arr} <- function_list do %ExHealth.Check{name: remove_function_prefix(func), mfa: {module, func, []}} end end @spec load_config() :: ExHealth.Status.t() defp load_config() do :ok = case Application.load(:ex_health) do :ok -> :ok {:error, {:already_loaded, :ex_health}} -> :ok end module = Application.get_env(:ex_health, :module) interval_ms = Application.get_env(:ex_health, :interval_ms, 15_000) mfas = case module do nil -> extract_and_transform(ExHealth.SelfCheck) mod -> extract_and_transform(mod) end %ExHealth.Status{ checks: mfas, interval_ms: interval_ms } end defp remove_function_prefix(function) do name_with_prefix = Atom.to_string(function) prefix = String.length(@function_prefix) String.slice(name_with_prefix, prefix, String.length(name_with_prefix)) end end
26.061475
322
0.628872
f765fdeba1045a3c15e9b38ac25462592bf9bc7b
698
exs
Elixir
services/fc_identity/test/fc_identity/commands/add_app_test.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
services/fc_identity/test/fc_identity/commands/add_app_test.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
services/fc_identity/test/fc_identity/commands/add_app_test.exs
dclausen/freshcom
7e1d6397c8ab222cfd03830232cee0718f050490
[ "BSD-3-Clause" ]
null
null
null
defmodule FCIdentity.AddAppTest do use FCIdentity.UnitCase, async: true import FCSupport.Validation alias FCIdentity.AddApp describe "validations" do test "given type is standard" do cmd = %AddApp{ type: "standard" } {:error, {:validation_failed, errors}} = validate(cmd) assert has_error(errors, :account_id, :required) assert has_error(errors, :name, :required) end test "given type is system" do cmd = %AddApp{ type: "system" } {:error, {:validation_failed, errors}} = validate(cmd) refute has_error(errors, :account_id, :required) assert has_error(errors, :name, :required) end end end
23.266667
60
0.644699
f76647714afdea38a08b1d10e252d14ada7d9ee7
1,758
ex
Elixir
clients/dataflow/lib/google_api/dataflow/v1b3/model/autoscaling_settings.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/autoscaling_settings.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/dataflow/lib/google_api/dataflow/v1b3/model/autoscaling_settings.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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.Dataflow.V1b3.Model.AutoscalingSettings do @moduledoc """ Settings for WorkerPool autoscaling. ## Attributes - algorithm (String.t): The algorithm to use for autoscaling. Defaults to: `null`. - Enum - one of [AUTOSCALING_ALGORITHM_UNKNOWN, AUTOSCALING_ALGORITHM_NONE, AUTOSCALING_ALGORITHM_BASIC] - maxNumWorkers (integer()): The maximum number of workers to cap scaling at. Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :algorithm => any(), :maxNumWorkers => any() } field(:algorithm) field(:maxNumWorkers) end defimpl Poison.Decoder, for: GoogleApi.Dataflow.V1b3.Model.AutoscalingSettings do def decode(value, options) do GoogleApi.Dataflow.V1b3.Model.AutoscalingSettings.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Dataflow.V1b3.Model.AutoscalingSettings do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
33.807692
108
0.74744
f76647fc915740c2a6a98bde68d072a25992cdf3
530
exs
Elixir
test/unit/hologram/compiler/transformers/not_equal_to_operator_transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
40
2022-01-19T20:27:36.000Z
2022-03-31T18:17:41.000Z
test/unit/hologram/compiler/transformers/not_equal_to_operator_transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
42
2022-02-03T22:52:43.000Z
2022-03-26T20:57:32.000Z
test/unit/hologram/compiler/transformers/not_equal_to_operator_transformer_test.exs
gregjohnsonsaltaire/hologram
aa8e9ea0d599def864c263cc37cc8ee31f02ac4a
[ "MIT" ]
3
2022-02-10T04:00:37.000Z
2022-03-08T22:07:45.000Z
defmodule Hologram.Compiler.NotEqualToOperatorTransformerTest do use Hologram.Test.UnitCase, async: true alias Hologram.Compiler.{Context, NotEqualToOperatorTransformer} alias Hologram.Compiler.IR.{IntegerType, NotEqualToOperator} test "transform/3" do code = "1 != 2" ast = ast(code) result = NotEqualToOperatorTransformer.transform(ast, %Context{}) expected = %NotEqualToOperator{ left: %IntegerType{value: 1}, right: %IntegerType{value: 2} } assert result == expected end end
25.238095
69
0.720755
f766ae70ec2dddad3189f9657376b6226ad7246b
1,717
ex
Elixir
lib/scidata/iris.ex
goodhamgupta/scidata
0336e188213b2d8629060930143013a43507ce2f
[ "Apache-2.0" ]
null
null
null
lib/scidata/iris.ex
goodhamgupta/scidata
0336e188213b2d8629060930143013a43507ce2f
[ "Apache-2.0" ]
null
null
null
lib/scidata/iris.ex
goodhamgupta/scidata
0336e188213b2d8629060930143013a43507ce2f
[ "Apache-2.0" ]
null
null
null
defmodule Scidata.Iris do @moduledoc """ Module for downloading the [Iris Data Set](https://archive.ics.uci.edu/ml/datasets/iris). """ @base_url "https://archive.ics.uci.edu/ml/machine-learning-databases/iris/" @dataset_file "iris.data" alias Scidata.Utils @doc """ Downloads the Iris dataset or fetches it locally. ## Information ([source](https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.names)) ### Attribute 1. sepal length in cm 2. sepal width in cm 3. petal length in cm 4. petal width in cm ### Label * 0: Iris Setosa * 1: Iris Versicolour * 2: Iris Virginica ## Options. * `:base_url` - Dataset base URL. Defaults to `"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/"` * `:dataset_file` - Dataset filename. Defaults to `"iris.data"` * `:cache_dir` - Cache directory. Defaults to `System.tmp_dir!()` """ def download(opts \\ []) do base_url = opts[:base_url] || @base_url dataset_file = opts[:dataset_file] || @dataset_file Utils.get!(base_url <> dataset_file, opts).body |> String.split() |> Enum.reverse() |> Enum.reduce({[], []}, fn row_str, {feature_acc, label_acc} -> row = String.split(row_str, ",") {features, [label]} = Enum.split(row, 4) features = Enum.map(features, fn val -> {val, ""} = Float.parse(val) val end) label = get_label(label) {[features | feature_acc], [label | label_acc]} end) end defp get_label(label) do cond do label =~ "Iris-setosa" -> 0 label =~ "Iris-versicolor" -> 1 label =~ "Iris-virginica" -> 2 end end end
23.202703
102
0.606872
f766c898c38f878c59dc793a4c38f8fd3914b9ba
1,868
ex
Elixir
clients/compute/lib/google_api/compute/v1/model/target_vpn_gateways_scoped_list.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/target_vpn_gateways_scoped_list.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
null
null
null
clients/compute/lib/google_api/compute/v1/model/target_vpn_gateways_scoped_list.ex
nuxlli/elixir-google-api
ecb8679ac7282b7dd314c3e20c250710ec6a7870
[ "Apache-2.0" ]
1
2020-11-10T16:58:27.000Z
2020-11-10T16:58:27.000Z
# Copyright 2017 Google Inc. # # Licensed under the Apache License, Version 2.0 (the &quot;License&quot;); # 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 &quot;AS IS&quot; 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.Compute.V1.Model.TargetVpnGatewaysScopedList do @moduledoc """ ## Attributes - targetVpnGateways ([TargetVpnGateway]): [Output Only] A list of target vpn gateways contained in this scope. Defaults to: `null`. - warning (AddressesScopedListWarning): Defaults to: `null`. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :targetVpnGateways => list(GoogleApi.Compute.V1.Model.TargetVpnGateway.t()), :warning => GoogleApi.Compute.V1.Model.AddressesScopedListWarning.t() } field(:targetVpnGateways, as: GoogleApi.Compute.V1.Model.TargetVpnGateway, type: :list) field(:warning, as: GoogleApi.Compute.V1.Model.AddressesScopedListWarning) end defimpl Poison.Decoder, for: GoogleApi.Compute.V1.Model.TargetVpnGatewaysScopedList do def decode(value, options) do GoogleApi.Compute.V1.Model.TargetVpnGatewaysScopedList.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Compute.V1.Model.TargetVpnGatewaysScopedList do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
36.627451
133
0.758565
f766f6b9f22e93e7141edb7cd806e7a6eff91c1c
1,376
ex
Elixir
test/support/data_case.ex
ashkan18/onsor
73b75b24f638f1a425de8ebf4454df971040e9f2
[ "MIT" ]
null
null
null
test/support/data_case.ex
ashkan18/onsor
73b75b24f638f1a425de8ebf4454df971040e9f2
[ "MIT" ]
4
2021-03-09T00:47:04.000Z
2022-02-10T15:15:28.000Z
test/support/data_case.ex
ashkan18/onsor
73b75b24f638f1a425de8ebf4454df971040e9f2
[ "MIT" ]
null
null
null
defmodule Onsor.DataCase do @moduledoc """ This module defines the setup for tests requiring access to the application's data layer. You may define functions here to be used as helpers in your tests. Finally, if the test case interacts with the database, it cannot be async. For this reason, every test runs inside a transaction which is reset at the beginning of the test unless the test case is marked as async. """ use ExUnit.CaseTemplate using do quote do alias Onsor.Repo import Ecto import Ecto.Changeset import Ecto.Query import Onsor.DataCase end end setup tags do :ok = Ecto.Adapters.SQL.Sandbox.checkout(Onsor.Repo) unless tags[:async] do Ecto.Adapters.SQL.Sandbox.mode(Onsor.Repo, {:shared, self()}) end :ok end @doc """ A helper that transforms changeset errors into a map of messages. assert {:error, changeset} = Accounts.create_user(%{password: "short"}) assert "password is too short" in errors_on(changeset).password assert %{password: ["password is too short"]} = errors_on(changeset) """ def errors_on(changeset) do Ecto.Changeset.traverse_errors(changeset, fn {message, opts} -> Enum.reduce(opts, message, fn {key, value}, acc -> String.replace(acc, "%{#{key}}", to_string(value)) end) end) end end
25.481481
77
0.678052
f766fa32224489ae023ef395ad6fe4326ce2c8b4
739
exs
Elixir
test/support/mock_adapter.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
1
2016-08-15T21:23:28.000Z
2016-08-15T21:23:28.000Z
test/support/mock_adapter.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
null
null
null
test/support/mock_adapter.exs
yrashk/ecto
1462d5ad4cbb7bf74c292ec405852bc196808daf
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.MockAdapter do @behaviour Ecto.Adapter defmacro __using__(_opts), do: :ok def start_link(_repo, _opts), do: :ok def stop(_repo), do: :ok def all(_repo, _query, _params, _opts), do: [1] def update_all(_repo, _query, _values, _params, _opts), do: 1 def delete_all(_repo, _query, _params, _opts), do: 1 def insert(_repo, _source, fields, _opts), do: fields |> Keyword.values |> List.to_tuple def update(_repo, _source, _filter, fields, _opts), do: fields |> Keyword.values |> List.to_tuple def delete(_repo, _source, _filter, _opts), do: :ok def transaction(_repo, _opts, fun) do # Makes transactions "trackable" in tests send self, {:transaction, fun} {:ok, fun.()} end end
29.56
63
0.677943
f7674227126db6763753edbfd6fd7c02ef36dd0b
125
exs
Elixir
config/config.exs
Waasi/jirex
24f43309183c4702c7cdda956a58202847f5c074
[ "MIT" ]
null
null
null
config/config.exs
Waasi/jirex
24f43309183c4702c7cdda956a58202847f5c074
[ "MIT" ]
null
null
null
config/config.exs
Waasi/jirex
24f43309183c4702c7cdda956a58202847f5c074
[ "MIT" ]
null
null
null
use Mix.Config config :jirex, jira_api_key: System.get_env("JIRA_API_KEY"), jira_api_url: System.get_env("JIRA_API_URL")
25
47
0.776
f7674d18dc3c81b7a70d05952688e0f0d78f022e
1,244
ex
Elixir
apps/database/lib/database/services/account/withdraw.ex
fschuindt/amethyst
0e8d60f83693b3bdb2c05d461cc3a74fa8b88b30
[ "MIT" ]
2
2018-06-23T11:43:34.000Z
2019-01-07T10:52:42.000Z
apps/database/lib/database/services/account/withdraw.ex
fschuindt/amethyst
0e8d60f83693b3bdb2c05d461cc3a74fa8b88b30
[ "MIT" ]
1
2018-06-21T01:20:04.000Z
2018-06-21T01:20:04.000Z
apps/database/lib/database/services/account/withdraw.ex
fschuindt/amethyst
0e8d60f83693b3bdb2c05d461cc3a74fa8b88b30
[ "MIT" ]
1
2018-06-30T21:40:51.000Z
2018-06-30T21:40:51.000Z
defmodule DataBase.Services.Account.Withdraw do @moduledoc """ Acts as a service to **withdraw** assets from a account. """ alias DataBase.Schemas.AccountMovement, as: Movement alias DataBase.Repos.AmethystRepo, as: Repo alias DataBase.Schemas.Account, as: Acc alias Decimal, as: D @doc """ Given a `t:DataBase.Schemas.Account.t/0` and a `t:Decimal.t/0` amount, it performs the withdraw. ## Steps Performed - Checks if the amount is greater than zero. - Checks if the account has the required amount to withdraw. - Debit the account. It's the standard way to withdraw assets from a account. """ @spec perform(Acc.t, D.t) :: Movement.response_t() def perform(%Acc{} = account, %D{} = amount) do respond(Repo.transaction(fn -> with true <- Movement.valid_amount?(amount), true <- Acc.has_funds?(account, amount), {:ok, withdraw} <- Acc.debit(account, amount) do {:ok, withdraw} else _e -> {:error, :failed_withdraw_performance} end end)) end @spec respond(any) :: Movement.response_t() defp respond({:ok, transaction}), do: transaction defp respond(_any), do: {:error, :database_failure} end
31.1
65
0.645498
f7677a797257ab15d6d1e7348a2bb4a427cefd46
3,741
ex
Elixir
lib/scidata/squad.ex
jeantux/scidata
216d7b8ba09e402f7a3e8763af9d28fc8c549a0b
[ "Apache-2.0" ]
null
null
null
lib/scidata/squad.ex
jeantux/scidata
216d7b8ba09e402f7a3e8763af9d28fc8c549a0b
[ "Apache-2.0" ]
null
null
null
lib/scidata/squad.ex
jeantux/scidata
216d7b8ba09e402f7a3e8763af9d28fc8c549a0b
[ "Apache-2.0" ]
null
null
null
defmodule Scidata.Squad do @moduledoc """ Module for downloading the [SQuAD1.1 dataset](https://rajpurkar.github.io/SQuAD-explorer). """ require Scidata.Utils alias Scidata.Utils @base_url "https://rajpurkar.github.io/SQuAD-explorer/dataset/" @train_dataset_file "train-v1.1.json" @test_dataset_file "dev-v1.1.json" @doc """ Downloads the SQuAD training dataset ## Examples iex> Scidata.Squad.download() [ %{ "paragraphs" => [ %{ "context" => "Architecturally, the school has a...", "qas" => [ %{ "answers" => [%{"answer_start" => 515, "text" => "Saint Bernadette Soubirous"}], "id" => "5733be284776f41900661182", "question" => "To whom did the..." }, ... ] } ], "title" => "University_of_Notre_Dame" }, ... ] """ def download() do download_dataset(@train_dataset_file) end @doc """ Downloads the SQuAD test dataset ## Examples iex> Scidata.Squad.download_test() [ %{ "paragraphs" => [ %{ "context" => "Super Bowl 50 was an American football game t...", "qas" => [ %{ "answers" => [ %{"answer_start" => 177, "text" => "Denver Broncos"},... ], "id" => "56be4db0acb8001400a502ec", "question" => "Which NFL team represented the AFC at Super Bowl 50?" }, ] } ], "title" => "Super_Bowl_50" }, ... ] """ def download_test() do download_dataset(@test_dataset_file) end defp download_dataset(dataset_name) do content = Utils.get!(@base_url <> dataset_name).body |> Jason.decode!() content["data"] end @doc """ Convert result of `download/0` or `download_test/0` to map for use with `Explorer.DataFrame`. ## Examples iex> columns_for_df = Scidata.Squad.download() |> Scidata.Squad.to_columns() %{ "answer_start" => [515, ...], "context" => ["Architecturally, the...", ...], "id" => ["5733be284776f41900661182", ...], "question" => ["To whom did the Vir...", ...], "answer_text" => ["Saint Bernadette Soubirous", ...], "title" => ["University_of_Notre_Dame", ...] } iex> Explorer.DataFrame.from_map(columns_for_df) #Explorer.DataFrame< [rows: 87599, columns: 6] ... > """ def to_columns(entries) do table = %{ "answer_start" => [], "context" => [], "id" => [], "question" => [], "answer_text" => [], "title" => [] } for %{"paragraphs" => paragraph, "title" => title} <- entries, %{"context" => context, "qas" => qas} <- paragraph, %{"id" => id, "question" => question, "answers" => answers} <- qas, %{"answer_start" => answer_start, "text" => answer_text} <- answers, reduce: table do %{ "answer_start" => answer_starts, "context" => contexts, "id" => ids, "question" => questions, "answer_text" => answer_texts, "title" => titles } -> %{ "answer_start" => [answer_start | answer_starts], "context" => [context | contexts], "id" => [id | ids], "question" => [question | questions], "answer_text" => [answer_text | answer_texts], "title" => [title | titles] } end |> Enum.map(fn {key, values} -> {key, :lists.reverse(values)} end) |> Enum.into(%{}) end end
27.108696
98
0.493986
f767d2d95b0b180e170820b4616d0e89b68f3034
2,116
ex
Elixir
lib/challenge/message.ex
juan-b-challenge/challenge
4cd55084067891ff1a86f827294dad05122f1059
[ "MIT" ]
null
null
null
lib/challenge/message.ex
juan-b-challenge/challenge
4cd55084067891ff1a86f827294dad05122f1059
[ "MIT" ]
null
null
null
lib/challenge/message.ex
juan-b-challenge/challenge
4cd55084067891ff1a86f827294dad05122f1059
[ "MIT" ]
null
null
null
defmodule Challenge.Message do use Ecto.Schema import Ecto.Changeset alias Challenge.{Message, Repo} schema "messages" do field :metadata, :map field :type, MessageTypeEnum field :sender_id, :id field :recipient_id, :id timestamps() end @doc false def changeset(message, attrs) do message |> cast(attrs, [:type, :metadata, :sender_id, :recipient_id]) |> validate_required([:type, :sender_id, :recipient_id, :metadata]) end def create_message(attrs = %{"content" => %{"type" => "text", "text" => text}}) do attrs = attrs |> transform_common_attrs |> Map.put_new("metadata", %{"text" => text}) perform_create_message(attrs) end def create_message(attrs = %{"content" => %{"type" => "image", "url" => url, "height" => height, "width" => width}}) do attrs = attrs |> transform_common_attrs |> Map.put_new("metadata", %{"url" => url, "height" => height, "width" => width}) perform_create_message(attrs) end def create_message(attrs = %{"content" => %{"type" => "video", "url" => url, "source" => source}}) do case source do value when value in ["youtube", "vimeo"] -> attrs = attrs |> transform_common_attrs |> Map.put_new("metadata", %{"url" => url, "source" => source}) perform_create_message(attrs) value -> {:error, "Invalid Source #{value}"} end end def create_message(_) do {:error, "Bad arguments"} end defp perform_create_message(attrs) do try do %Message{} |> Message.changeset(attrs) |> Repo.insert() rescue e in Ecto.ConstraintError -> {:error, "One of the users does not exist"} e in RuntimeError -> {:error, "An error occurred"} end end defp transform_common_attrs(attrs) do content = Map.get(attrs, "content") attrs |> Map.put_new("recipient_id", Map.get(attrs, "recipient")) |> Map.put_new("sender_id", Map.get(attrs, "sender")) |> Map.put_new("type", Map.get(content, "type")) |> Map.drop(["recipient", "sender"]) end end
27.128205
121
0.603497
f767e14e06a98c2894487c4b5b7bc1da85b0e27c
3,751
ex
Elixir
cp/lib/cpsim/cp/connection.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
cp/lib/cpsim/cp/connection.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
cp/lib/cpsim/cp/connection.ex
azhi/cpsim
a10a3e068a8a319e66cc9cf8a6c9c97457d9bf8b
[ "MIT" ]
null
null
null
defmodule CPSIM.CP.Connection do require Logger def init(state) do {:ok, pid} = __MODULE__.WS.start_link( url: Path.join(state.internal_config.ws_endpoint, state.internal_config.identity), parent: self() ) true = Process.link(pid) state |> put_in([:modules, __MODULE__, :state, :ws], pid) |> put_in([:modules, __MODULE__, :state, :status], :ws_init) end def reset(type, state) do state |> disconnect_ws() |> schedule_reset(type) |> put_in([:modules, __MODULE__, :state, :status], :resetting) end def handle_info({:established, _conn}, state) do Logger.debug("Connected to OCPP server", url: state.internal_config.ws_endpoint) # TODO: initial messages logic - status notifications, etc in case there's no boot notification state |> maybe_send_boot_notification() |> then(&{:noreply, &1}) end def handle_info({:lost, info}, state) do message = case get_in(state, [:modules, __MODULE__, :state, :status]) do :ws_init -> "Can't connect" _other -> "Lost connection" end Logger.debug(message <> " to OCPP server", info: inspect(info, limit: :infinity)) state = CPSIM.CP.Status.reset_reported_at(state) {:noreply, state} end def handle_info(:retry, state) do state |> put_in([:modules, __MODULE__, :state, :status], :ws_init) |> put_in([:modules, __MODULE__, :state, :connection_error], nil) |> put_in([:modules, __MODULE__, :state, :retry_at], nil) |> maybe_send_boot_notification() |> then(&{:noreply, &1}) end def handle_info(:reset_done, state) do init(state) |> then(&{:noreply, &1}) end def handle_info({:call_timeout, call_id}, state) do __MODULE__.Calls.handle_call_timeout(call_id, state) end def handle_call_response(result_or_error, state) do __MODULE__.Calls.handle_call_response(result_or_error, state) end def update_server_time(state, current_time) do now = DateTime.utc_now() case DateTime.from_iso8601(current_time) do {:ok, server_time, _offset} -> put_in(state, [:modules, __MODULE__, :state, :current_time_diff], DateTime.diff(server_time, now, :microsecond)) {:error, reason} -> Logger.error("Received error when parsing current time from server: #{inspect(reason)}") state end end def do_retry(error_message, state, retry_in \\ nil) do retry_in = retry_in || state.modules[__MODULE__].config.default_retry_interval retry_at = DateTime.utc_now() |> DateTime.add(retry_in, :second) Process.send_after(self(), {__MODULE__, :retry}, retry_in * 1_000) state |> put_in([:modules, __MODULE__, :state, :status], :retry) |> put_in([:modules, __MODULE__, :state, :connection_error], error_message) |> put_in([:modules, __MODULE__, :state, :retry_at], retry_at) end defp disconnect_ws(state) do Logger.debug("Disconnecting from OCPP server") __MODULE__.WS.stop(state.modules[__MODULE__].state.ws) put_in(state, [:modules, __MODULE__, :state, :ws], nil) end defp schedule_reset(state, type) do config_key = case type do "Soft" -> :soft_reboot_interval "Hard" -> :hard_reboot_interval end interval = state.modules[__MODULE__].config[config_key] Process.send_after(self(), {__MODULE__, :reset_done}, interval * 1_000) retry_at = DateTime.utc_now() |> DateTime.add(interval, :second) put_in(state, [:modules, __MODULE__, :state, :retry_at], retry_at) end defp maybe_send_boot_notification(state) do case get_in(state, [:modules, __MODULE__, :state, :status]) do :ws_init -> __MODULE__.Calls.BootNotification.send(state) _other -> state end end end
30.745902
120
0.671554
f7680bdc55fe32b4de98b93bb04ecef75183aff8
430
exs
Elixir
config/config.exs
myxplor/exvcr
84aa3ebce2412aff3eff25dea14cd39b08a5a32d
[ "MIT" ]
null
null
null
config/config.exs
myxplor/exvcr
84aa3ebce2412aff3eff25dea14cd39b08a5a32d
[ "MIT" ]
null
null
null
config/config.exs
myxplor/exvcr
84aa3ebce2412aff3eff25dea14cd39b08a5a32d
[ "MIT" ]
null
null
null
use Mix.Config config :exvcr, [ vcr_cassette_library_dir: "fixture/vcr_cassettes", custom_cassette_library_dir: "fixture/custom_cassettes", filter_sensitive_data: [ [pattern: "<PASSWORD>.+</PASSWORD>", placeholder: "PASSWORD_PLACEHOLDER"] ], filter_url_params: false, filter_request_headers: [], response_headers_blacklist: [], ignore_localhost: false, enable_global_settings: false, strict_mode: false ]
26.875
77
0.75814
f768431a1fe1d77067e484fc3629789f32f5464c
5,125
ex
Elixir
lib/qr_code/svg.ex
erickgnavar/qr_code
99bbc9cbc775f39f5818567b06087334dac4d231
[ "BSD-4-Clause" ]
null
null
null
lib/qr_code/svg.ex
erickgnavar/qr_code
99bbc9cbc775f39f5818567b06087334dac4d231
[ "BSD-4-Clause" ]
null
null
null
lib/qr_code/svg.ex
erickgnavar/qr_code
99bbc9cbc775f39f5818567b06087334dac4d231
[ "BSD-4-Clause" ]
null
null
null
defmodule QRCode.Svg do @moduledoc """ SVG structure and helper functions. """ alias MatrixReloaded.Matrix alias QRCode.{QR, SvgSettings} @type t :: %__MODULE__{ xmlns: String.t(), xlink: String.t(), width: ExMaybe.t(integer), height: ExMaybe.t(integer), body: String.t(), rank_matrix: ExMaybe.t(pos_integer) } defstruct xmlns: "http://www.w3.org/2000/svg", xlink: "http://www.w3.org/1999/xlink", width: nil, height: nil, body: nil, rank_matrix: nil @doc """ Create Svg structure from QR matrix as binary. This binary contains svg attributes and svg elements. """ @spec create(QR.t(), SvgSettings.t()) :: binary() def create(%QR{matrix: matrix}, settings \\ %SvgSettings{}) do create_svg(matrix, settings) end @doc """ Saves QR code to svg file. This function returns [Result](https://hexdocs.pm/result/api-reference.html), it means either tuple of `{:ok, "path/to/file.svg"}` or `{:error, reason}`. Also there are a few settings for svg: ```elixir | Setting | Type | Default value | Description | |------------------|---------------------|---------------|-------------------------| | scale | positive integer | 10 | scale for svg QR code | | background_color | string or {r, g, b} | "#ffffff" | background color of svg | | qrcode_color | string or {r, g, b} | "#000000" | color of QR code | | format | :none or :indent | :none | indentation of elements | ``` By this option, you can set the background of QR code, QR code colors or size QR code. The format option is for removing indentation (of elements) in a svg file. Let's see an example below: iex> settings = %QRCode.SvgSettings{qrcode_color: {17, 170, 136}} iex> qr = QRCode.QR.create("your_string") iex> qr |> Result.and_then(&QRCode.Svg.save_as(&1,"/tmp/your_name.svg", settings)) {:ok, "/tmp/your_name.svg"} The svg file will be saved into your tmp directory. ![QR code color](docs/qrcode_color.png) """ @spec save_as(QR.t(), Path.t(), SvgSettings.t()) :: Result.t(String.t() | File.posix() | :badarg | :terminated, Path.t()) def save_as(%QR{matrix: matrix}, svg_name, settings \\ %SvgSettings{}) do matrix |> create_svg(settings) |> save(svg_name) end @doc """ Create Svg structure from QR matrix as binary and encode it into a base 64. This encoded string can be then used in Html as `<img src="data:image/svg+xml; base64, encoded_svg_qr_code" />` """ @spec to_base64(QR.t(), SvgSettings.t()) :: binary() def to_base64(%QR{matrix: matrix}, settings \\ %SvgSettings{}) do matrix |> create_svg(settings) |> Base.encode64() end defp create_svg(matrix, settings) do matrix |> construct_body(%__MODULE__{}, settings) |> construct_svg(settings) end defp construct_body(matrix, svg, %SvgSettings{qrcode_color: qc, scale: scale}) do {rank_matrix, _} = Matrix.size(matrix) %{ svg | body: matrix |> find_nonzero_element() |> Enum.map(&create_rect(&1, scale, qc)), rank_matrix: rank_matrix } end defp construct_svg( %__MODULE__{ xmlns: xmlns, xlink: xlink, body: body, rank_matrix: rank_matrix }, %SvgSettings{background_color: bg, scale: scale, format: format} ) do {:svg, %{ xmlns: xmlns, xlink: xlink, width: rank_matrix * scale, height: rank_matrix * scale }, [background_rect(bg) | body]} |> XmlBuilder.generate(format: format) end defp save(svg, svg_name) do svg_name |> File.open([:write]) |> Result.and_then(&write(&1, svg)) |> Result.and_then(&close(&1, svg_name)) end defp write(file, svg) do case IO.binwrite(file, svg) do :ok -> {:ok, file} err -> err end end defp close(file, svg_name) do case File.close(file) do :ok -> {:ok, svg_name} err -> err end end # Helpers defp create_rect({x_pos, y_pos}, scale, color) do {:rect, %{width: scale, height: scale, x: scale * x_pos, y: scale * y_pos, fill: to_hex(color)}, nil} end defp background_rect(color) do {:rect, %{width: "100%", height: "100%", fill: to_hex(color)}, nil} end defp find_nonzero_element(matrix) do matrix |> Enum.with_index() |> Enum.map(fn {row, i} -> row |> Enum.with_index() |> Enum.reduce([], fn {0, _}, acc -> acc {1, j}, acc -> [{i, j} | acc] end) end) |> List.flatten() end defp to_hex(color) when is_tuple(color) do {r, g, b} = color "#" <> (r |> :binary.encode_unsigned() |> Base.encode16()) <> (g |> :binary.encode_unsigned() |> Base.encode16()) <> (b |> :binary.encode_unsigned() |> Base.encode16()) end defp to_hex(color) do color end end
28.792135
108
0.570927
f7685d2610f884de8b2b26f45da9704aa5d9d4e9
317
exs
Elixir
priv/repo/migrations/20200611081048_create_batteries_table.exs
mekongit/evercam_models
7c36d52f2b47ffc89a3eaca65c2e353716fafacc
[ "MIT" ]
null
null
null
priv/repo/migrations/20200611081048_create_batteries_table.exs
mekongit/evercam_models
7c36d52f2b47ffc89a3eaca65c2e353716fafacc
[ "MIT" ]
null
null
null
priv/repo/migrations/20200611081048_create_batteries_table.exs
mekongit/evercam_models
7c36d52f2b47ffc89a3eaca65c2e353716fafacc
[ "MIT" ]
null
null
null
defmodule Evercam.Repo.Migrations.CreateBatteriesTable do use Ecto.Migration def change do create table(:batteries) do add :name, :string add :source_url, :string add :active, :boolean, default: true, null: false add :user_id, references(:users) timestamps() end end end
21.133333
57
0.671924
f7685f4b14ecc36094bc5f5a660573ee67fecfb1
4,175
ex
Elixir
src/lib/changelog/data/news/news_queue.ex
thenets/docker-chocoquest
856fa5ff41a5831ed67b1ef865cd8951df5af023
[ "MIT" ]
null
null
null
src/lib/changelog/data/news/news_queue.ex
thenets/docker-chocoquest
856fa5ff41a5831ed67b1ef865cd8951df5af023
[ "MIT" ]
null
null
null
src/lib/changelog/data/news/news_queue.ex
thenets/docker-chocoquest
856fa5ff41a5831ed67b1ef865cd8951df5af023
[ "MIT" ]
null
null
null
defmodule Changelog.NewsQueue do use Changelog.Data require Logger alias Changelog.{Buffer, NewsItem, NewsQueue, Notifier} schema "news_queue" do field :position, :float belongs_to :item, NewsItem end def queued(query \\ NewsQueue) do from(q in query, left_join: i in assoc(q, :item), where: is_nil(i.published_at), order_by: q.position) end def scheduled(query \\ NewsQueue) do from(q in query, left_join: i in assoc(q, :item), where: not(is_nil(i.published_at)), order_by: i.published_at) end def past(query), do: from([_q, i] in query, where: i.published_at <= ^Timex.now) def append(item) do entry = change(%NewsQueue{}, %{item_id: item.id}) entries = Repo.all(NewsQueue.queued) entry = if length(entries) > 0 do last_position = List.last(entries).position change(entry, %{position: last_position + 1.0}) else change(entry, %{position: 1.0}) end Repo.insert(entry) NewsItem.queue!(item) end def move(item = %NewsItem{}, to_index) do entry = Repo.get_by(NewsQueue, item_id: item.id) move(entry, to_index) end def move(entry = %NewsQueue{}, to_index) do entries = Repo.all(NewsQueue.queued) current_index = Enum.find_index(entries, &(&1 == entry)) entry = cond do to_index <= 0 -> # move to top first = List.first(entries) change(entry, %{position: first.position / 2}) to_index >= (length(entries) - 1) -> # move to bottom last = List.last(entries) change(entry, %{position: last.position + 1}) to_index < current_index -> # move up pre = Enum.at(entries, to_index - 1) post = Enum.at(entries, to_index) change(entry, %{position: (pre.position + post.position) / 2}) to_index > current_index -> # move down pre = Enum.at(entries, to_index) post = Enum.at(entries, to_index + 1) change(entry, %{position: (pre.position + post.position) / 2}) true -> change(entry, %{}) # no move-y end Repo.update(entry) end def preload_all(query = %Ecto.Query{}), do: Ecto.Query.preload(query, [item: [:author, :logger, :topics]]) def preload_all(entry), do: Repo.preload(entry, [item: [:author, :logger, :topics]]) def prepend(item) do entry = change(%NewsQueue{}, %{item_id: item.id}) entries = NewsQueue.queued |> Repo.all entry = if length(entries) > 0 do first_position = List.first(entries).position change(entry, %{position: first_position / 2}) else change(entry, %{position: 1.0}) end Repo.insert(entry) NewsItem.queue!(item) end def publish_next do NewsQueue.queued |> NewsQueue.limit(1) |> Repo.one |> publish end def publish_scheduled do NewsQueue.scheduled |> NewsQueue.past |> NewsQueue.limit(1) |> Repo.one |> publish end def publish do publish_scheduled() || publish_next_maybe(10 , 60) end def publish(item = %NewsItem{}) do case Repo.get_by(NewsQueue, item_id: item.id) do entry = %NewsQueue{} -> publish(entry) nil -> publish_item(item) end end def publish(entry = %NewsQueue{}) do entry = Repo.preload(entry, :item) publish_item(entry.item) Repo.delete!(entry) true end def publish(nil) do Logger.info("News: Published bupkis") false end defp publish_item(item = %NewsItem{}) do item = NewsItem.publish!(item) Task.start_link(fn -> Buffer.queue(item) end) Task.start_link(fn -> Notifier.notify(item) end) Logger.info("News: Published ##{item.id}") true end defp publish_next_maybe(per_day, interval) do if one_chance_in(5) && nothing_recent(interval) && no_max(per_day) do publish_next() end end defp one_chance_in(n), do: Enum.random(1..n) == 1 defp nothing_recent(interval) do Timex.now |> Timex.shift(minutes: -interval) |> NewsItem.published_since() |> Repo.count |> Kernel.==(0) end defp no_max(per_day) do Timex.now |> Timex.shift(days: -1) |> NewsItem.published_since() |> Repo.count |> Kernel.<(per_day) end end
25.931677
108
0.631138
f768641aac537d9d67faee6cf31e6b731a16f56c
1,479
exs
Elixir
test/exavier_test.exs
filipevarjao/exavier
5e916fcf9ed95255ff937ff595d530e656adfa97
[ "MIT" ]
93
2019-07-22T09:21:31.000Z
2022-02-02T05:49:29.000Z
test/exavier_test.exs
filipevarjao/exavier
5e916fcf9ed95255ff937ff595d530e656adfa97
[ "MIT" ]
21
2019-07-26T12:54:37.000Z
2022-03-10T10:56:47.000Z
test/exavier_test.exs
filipevarjao/exavier
5e916fcf9ed95255ff937ff595d530e656adfa97
[ "MIT" ]
7
2019-11-05T08:32:51.000Z
2020-11-25T19:37:35.000Z
defmodule ExavierTest do use ExUnit.Case, async: true @subject Exavier test "returns quoted code from given file" do {:defmodule, _meta, [{:__aliases__, [line: 1], [module]}, _]} = @subject.file_to_quoted("test/fixtures/foo_bar.ex") assert module == :FooBar end test "translate test module to module" do assert @subject.test_module_to_module(ExavierTest) == Exavier end test "translate test file to module" do assert @subject.test_file_to_module("test/exavier_test.exs") == Exavier end test "when EXAVIER_DEBUG=1 timeout defaults to infinity" do System.put_env("EXAVIER_DEBUG", "1") on_exit(self(), fn -> System.delete_env("EXAVIER_DEBUG") end) assert @subject.timeout(:anything) == :infinity end test "when EXAVIER_DEBUG=true timeout defaults to infinity" do System.put_env("EXAVIER_DEBUG", "true") on_exit(self(), fn -> System.delete_env("EXAVIER_DEBUG") end) assert @subject.timeout(:anything) == :infinity end test "when getting timeout for running whole mutation testing" do assert @subject.timeout(:mutate_everything) == 60_000 end test "when getting timeout for when mutating a module" do assert @subject.timeout(:mutate_module) == 5000 end test "when getting timeout for when reporting" do assert @subject.timeout(:report) == 1000 end test "when getting timeout for unknown action uses default timeout" do assert @subject.timeout(:unknown) == 5000 end end
29
75
0.712644
f7686dc9a285354375e60c8c90e72d7c92df3c8d
101
ex
Elixir
lib/code_corps/repo.ex
roryqueue/code-corps-api
f23007e13fed2d7264fd2e2e97b1497488fb54ba
[ "MIT" ]
null
null
null
lib/code_corps/repo.ex
roryqueue/code-corps-api
f23007e13fed2d7264fd2e2e97b1497488fb54ba
[ "MIT" ]
null
null
null
lib/code_corps/repo.ex
roryqueue/code-corps-api
f23007e13fed2d7264fd2e2e97b1497488fb54ba
[ "MIT" ]
null
null
null
defmodule CodeCorps.Repo do use Ecto.Repo, otp_app: :code_corps use Scrivener, page_size: 10 end
20.2
37
0.772277
f7687efaf6997bcd2dee101bc26edbab4fb0e826
3,305
ex
Elixir
clients/games/lib/google_api/games/v1/api/revisions.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/api/revisions.ex
GoNZooo/elixir-google-api
cf3ad7392921177f68091f3d9001f1b01b92f1cc
[ "Apache-2.0" ]
null
null
null
clients/games/lib/google_api/games/v1/api/revisions.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 &quot;License&quot;); # 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 &quot;AS IS&quot; 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.Games.V1.Api.Revisions do @moduledoc """ API calls for all endpoints tagged `Revisions`. """ alias GoogleApi.Games.V1.Connection import GoogleApi.Games.V1.RequestBuilder @doc """ Checks whether the games client is out of date. ## Parameters - connection (GoogleApi.Games.V1.Connection): Connection to server - client_revision (String): The revision of the client SDK used by your application. Format: [PLATFORM_TYPE]:[VERSION_NUMBER]. Possible values of PLATFORM_TYPE are: - \&quot;ANDROID\&quot; - Client is running the Android SDK. - \&quot;IOS\&quot; - Client is running the iOS SDK. - \&quot;WEB_APP\&quot; - Client is running as a Web App. - opts (KeywordList): [optional] Optional parameters - :alt (String): Data format for the response. - :fields (String): Selector specifying which fields to include in a partial response. - :key (String): API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. - :oauth_token (String): OAuth 2.0 token for the current user. - :pretty_print (Boolean): Returns response with indentations and line breaks. - :quota_user (String): Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. - :user_ip (String): IP address of the site where the request originates. Use this if you want to enforce per-user limits. - :consistency_token (String): The last-seen mutation timestamp. ## Returns {:ok, %GoogleApi.Games.V1.Model.RevisionCheckResponse{}} on success {:error, info} on failure """ @spec games_revisions_check(Tesla.Env.client, String.t, keyword()) :: {:ok, GoogleApi.Games.V1.Model.RevisionCheckResponse.t} | {:error, Tesla.Env.t} def games_revisions_check(connection, client_revision, opts \\ []) do optional_params = %{ :"alt" => :query, :"fields" => :query, :"key" => :query, :"oauth_token" => :query, :"prettyPrint" => :query, :"quotaUser" => :query, :"userIp" => :query, :"consistencyToken" => :query } %{} |> method(:get) |> url("/revisions/check") |> add_param(:query, :"clientRevision", client_revision) |> add_optional_params(optional_params, opts) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%GoogleApi.Games.V1.Model.RevisionCheckResponse{}) end end
45.273973
342
0.708623
f7688ded660bdf652d63d1205c40dddc9f52c8c8
2,531
ex
Elixir
lib/teslamate/repair.ex
markusdd/teslamate
baada9c5455da2d3c400bf916ab29834772f6a88
[ "MIT" ]
null
null
null
lib/teslamate/repair.ex
markusdd/teslamate
baada9c5455da2d3c400bf916ab29834772f6a88
[ "MIT" ]
null
null
null
lib/teslamate/repair.ex
markusdd/teslamate
baada9c5455da2d3c400bf916ab29834772f6a88
[ "MIT" ]
null
null
null
defmodule TeslaMate.Repair do use GenServer require Logger import Ecto.Query alias TeslaMate.Log.{Drive, Position, ChargingProcess} alias TeslaMate.{Repo, Locations} # API def start_link(opts) do GenServer.start_link(__MODULE__, opts, name: __MODULE__) end # Callbacks @impl true def init(_opts) do {:ok, _ref} = :timer.send_interval(:timer.hours(6), self(), :repair) send(self(), :repair) {:ok, nil} end @impl true def handle_info(:repair, state) do from(d in Drive, where: (is_nil(d.start_address_id) or is_nil(d.end_address_id)) and (not is_nil(d.start_position_id) and not is_nil(d.end_position_id)), preload: [:start_position, :end_position] ) |> Repo.all() |> repair() from(c in ChargingProcess, where: is_nil(c.address_id) and not is_nil(c.position_id), preload: [:position] ) |> Repo.all() |> repair() {:noreply, state} end # Private defp repair([]), do: :ok defp repair([entity | rest]) do case entity do %Drive{} = drive -> Logger.info("Repairing drive ##{drive.id} ...") drive |> Drive.changeset(%{ start_address_id: get_address_id(drive.start_position), end_address_id: get_address_id(drive.end_position) }) |> Repo.update() %ChargingProcess{} = charge -> Logger.info("Repairing charging process ##{charge.id} ...") charge |> ChargingProcess.changeset(%{address_id: get_address_id(charge.position)}) |> Repo.update() end |> case do {:error, reason} -> Logger.warn("Failure: #{inspect(reason, pretty: true)}") {:ok, _entity} -> Logger.info("OK") end Process.sleep(3000) repair(rest) end defp get_address_id(nil), do: nil defp get_address_id(%Position{} = position) do case :fuse.ask(:addr_fuse, :sync) do :ok -> case Locations.find_address(position) do {:error, reason} -> :fuse.melt(:addr_fuse) Logger.warn("Address not found: #{inspect(reason)}") nil {:ok, %Locations.Address{display_name: _name, id: id}} -> id end :blown -> nil {:error, :not_found} -> Logger.debug("Installing circuit-breaker :addr_fuse ...") :fuse.install( :addr_fuse, {{:standard, 2, :timer.minutes(3)}, {:reset, :timer.minutes(15)}} ) get_address_id(position) end end end
22.801802
84
0.5887
f768a1f0d6ca5c0fe034403b289f90c7226e3126
1,214
exs
Elixir
mix.exs
pedromvieira/cloud_storage
306c062e4d5c2b217c72fb01c712bb330b666bb4
[ "MIT" ]
12
2017-08-14T13:06:53.000Z
2020-04-29T19:28:27.000Z
mix.exs
pedromvieira/cloud_storage
306c062e4d5c2b217c72fb01c712bb330b666bb4
[ "MIT" ]
null
null
null
mix.exs
pedromvieira/cloud_storage
306c062e4d5c2b217c72fb01c712bb330b666bb4
[ "MIT" ]
1
2020-01-08T20:51:31.000Z
2020-01-08T20:51:31.000Z
defmodule CloudStorage.Mixfile do use Mix.Project def project do [ app: :cloud_storage, version: "0.5.1", elixir: "~> 1.4", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps(), name: "Cloud Storage", source_url: "https://github.com/pedromvieira/cloud_storage" ] end def application do [ extra_applications: [:logger] ] end defp description do """ Elixir package to interact via REST API with Azure Storage and Google Cloud Storage. """ end defp package do [ name: :cloud_storage, files: ["lib", "mix.exs", "LICENSE", "README.md"], maintainers: ["Pedro Vieira - [email protected]"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/pedromvieira/cloud_storage"} ] end defp deps do [ {:httpoison, ">= 1.4.0"}, {:elixir_xml_to_map, ">= 0.1.2"}, {:mime, ">= 1.3.0"}, {:jason, ">= 1.1.0"}, {:joken, ">= 2.0.0"}, {:goth, ">= 1.0.0"}, {:ex_doc, ">= 0.19.1", only: :dev, runtime: false}, {:timex, ">= 3.2.0"}, ] end end
22.481481
88
0.541186
f768bbb6db2a2ce1fbc6d3897d4fdf764fafeb5d
3,068
ex
Elixir
clients/content/lib/google_api/content/v2/model/account_status.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/account_status.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/account_status.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-10-04T10:12:44.000Z
2020-10-04T10:12:44.000Z
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V2.Model.AccountStatus do @moduledoc """ The status of an account, i.e., information about its products, which is computed offline and not returned immediately at insertion time. ## Attributes * `accountId` (*type:* `String.t`, *default:* `nil`) - The ID of the account for which the status is reported. * `accountLevelIssues` (*type:* `list(GoogleApi.Content.V2.Model.AccountStatusAccountLevelIssue.t)`, *default:* `nil`) - A list of account level issues. * `dataQualityIssues` (*type:* `list(GoogleApi.Content.V2.Model.AccountStatusDataQualityIssue.t)`, *default:* `nil`) - DEPRECATED - never populated. * `kind` (*type:* `String.t`, *default:* `content#accountStatus`) - Identifies what kind of resource this is. Value: the fixed string "`content#accountStatus`" * `products` (*type:* `list(GoogleApi.Content.V2.Model.AccountStatusProducts.t)`, *default:* `nil`) - List of product-related data by channel, destination, and country. Data in this field may be delayed by up to 30 minutes. * `websiteClaimed` (*type:* `boolean()`, *default:* `nil`) - Whether the account's website is claimed or not. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :accountId => String.t(), :accountLevelIssues => list(GoogleApi.Content.V2.Model.AccountStatusAccountLevelIssue.t()), :dataQualityIssues => list(GoogleApi.Content.V2.Model.AccountStatusDataQualityIssue.t()), :kind => String.t(), :products => list(GoogleApi.Content.V2.Model.AccountStatusProducts.t()), :websiteClaimed => boolean() } field(:accountId) field(:accountLevelIssues, as: GoogleApi.Content.V2.Model.AccountStatusAccountLevelIssue, type: :list ) field(:dataQualityIssues, as: GoogleApi.Content.V2.Model.AccountStatusDataQualityIssue, type: :list ) field(:kind) field(:products, as: GoogleApi.Content.V2.Model.AccountStatusProducts, type: :list) field(:websiteClaimed) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.AccountStatus do def decode(value, options) do GoogleApi.Content.V2.Model.AccountStatus.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.AccountStatus do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
42.027397
227
0.718383
f768c6532941b5d2d845b0ed484a8034435cbee5
535
ex
Elixir
apps/get_functional_tree/lib/get_functional_tree/supervisor.ex
taylonr/get_functional_elixir
a519eb3689749883e3fe5dd59a17253571c5fd33
[ "MIT" ]
4
2017-04-16T21:07:36.000Z
2021-07-21T10:27:10.000Z
apps/get_functional_tree/lib/get_functional_tree/supervisor.ex
taylonr/get_functional_elixir
a519eb3689749883e3fe5dd59a17253571c5fd33
[ "MIT" ]
null
null
null
apps/get_functional_tree/lib/get_functional_tree/supervisor.ex
taylonr/get_functional_elixir
a519eb3689749883e3fe5dd59a17253571c5fd33
[ "MIT" ]
null
null
null
defmodule GetFunctionalTree.Supervisor do use Supervisor def start_link(balance) do result = {:ok, sup} = Supervisor.start_link(__MODULE__, [balance]) start_workers(sup, balance) result end def start_workers(sup, balance) do {:ok, stash} = Supervisor.start_child(sup, worker(GetFunctionalTree.Stash, [balance])) Supervisor.start_child(sup, supervisor(GetFunctionalTree.SubSupervisor, [stash])) end def init(_) do supervise [], strategy: :one_for_one end end
31.470588
94
0.678505
f768cef1689401891f89ed8649b23543c51721cf
2,971
exs
Elixir
test/elixir/test/view_test.exs
denyadb/couchdb
ac33e853cef2a6a108aa64269eb196d32b235529
[ "Apache-2.0" ]
1
2020-09-11T19:23:27.000Z
2020-09-11T19:23:27.000Z
test/elixir/test/view_test.exs
denyadb/couchdb
ac33e853cef2a6a108aa64269eb196d32b235529
[ "Apache-2.0" ]
null
null
null
test/elixir/test/view_test.exs
denyadb/couchdb
ac33e853cef2a6a108aa64269eb196d32b235529
[ "Apache-2.0" ]
null
null
null
defmodule ViewTest do use CouchTestCase @moduletag :view @moduletag kind: :single_node @moduledoc """ Test CouchDB /{db}/_design/{ddoc}/_view/{view} """ setup_all do db_name = random_db_name() {:ok, _} = create_db(db_name) on_exit(fn -> delete_db(db_name) end) {:ok, _} = create_doc( db_name, %{ _id: "foo", bar: "baz" } ) {:ok, _} = create_doc( db_name, %{ _id: "foo2", bar: "baz2" } ) map_fun = """ function(doc) { emit(doc._id, doc.bar); } """ body = %{ :docs => [ %{ _id: "_design/map", views: %{ some: %{ map: map_fun } } } ] } resp = Couch.post("/#{db_name}/_bulk_docs", body: body) Enum.each(resp.body, &assert(&1["ok"])) {:ok, [db_name: db_name]} end test "GET with no parameters", context do resp = Couch.get( "/#{context[:db_name]}/_design/map/_view/some" ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 2 end test "GET with one key", context do resp = Couch.get( "/#{context[:db_name]}/_design/map/_view/some", query: %{ :key => "\"foo\"", } ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 1 end test "GET with multiple keys", context do resp = Couch.get( "/#{context[:db_name]}/_design/map/_view/some", query: %{ :keys => "[\"foo\", \"foo2\"]", } ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 2 end test "POST with empty body", context do resp = Couch.post( "/#{context[:db_name]}/_design/map/_view/some", body: %{} ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 2 end test "POST with keys and limit", context do resp = Couch.post( "/#{context[:db_name]}/_design/map/_view/some", body: %{ :keys => ["foo", "foo2"], :limit => 1 } ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 1 end test "POST with query parameter and JSON body", context do resp = Couch.post( "/#{context[:db_name]}/_design/map/_view/some", query: %{ :limit => 1 }, body: %{ :keys => ["foo", "foo2"] } ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 1 end test "POST edge case with colliding parameters - query takes precedence", context do resp = Couch.post( "/#{context[:db_name]}/_design/map/_view/some", query: %{ :limit => 1 }, body: %{ :keys => ["foo", "foo2"], :limit => 2 } ) assert resp.status_code == 200 assert length(Map.get(resp, :body)["rows"]) == 1 end end
20.489655
86
0.511612
f768d749d2714a4b68a537eb00e988bd23445c62
1,819
ex
Elixir
phx/praxkit/lib/praxkit_web/telemetry.ex
zoosky/praxkit
4b4fe1af274e79e1a4f728a94ff58468f0fe13e0
[ "Apache-2.0" ]
null
null
null
phx/praxkit/lib/praxkit_web/telemetry.ex
zoosky/praxkit
4b4fe1af274e79e1a4f728a94ff58468f0fe13e0
[ "Apache-2.0" ]
5
2021-02-28T14:39:51.000Z
2021-02-28T14:43:10.000Z
phx/praxkit/lib/praxkit_web/telemetry.ex
zoosky/praxkit
4b4fe1af274e79e1a4f728a94ff58468f0fe13e0
[ "Apache-2.0" ]
1
2018-09-19T17:53:28.000Z
2018-09-19T17:53:28.000Z
defmodule PraxkitWeb.Telemetry do use Supervisor import Telemetry.Metrics def start_link(arg) do Supervisor.start_link(__MODULE__, arg, name: __MODULE__) end @impl true def init(_arg) do children = [ # Telemetry poller will execute the given period measurements # every 10_000ms. Learn more here: https://hexdocs.pm/telemetry_metrics {:telemetry_poller, measurements: periodic_measurements(), period: 10_000} # Add reporters as children of your supervision tree. # {Telemetry.Metrics.ConsoleReporter, metrics: metrics()} ] Supervisor.init(children, strategy: :one_for_one) end def metrics do [ # Phoenix Metrics summary("phoenix.endpoint.stop.duration", unit: {:native, :millisecond} ), summary("phoenix.router_dispatch.stop.duration", tags: [:route], unit: {:native, :millisecond} ), # Database Metrics summary("praxkit.repo.query.total_time", unit: {:native, :millisecond}), summary("praxkit.repo.query.decode_time", unit: {:native, :millisecond}), summary("praxkit.repo.query.query_time", unit: {:native, :millisecond}), summary("praxkit.repo.query.queue_time", unit: {:native, :millisecond}), summary("praxkit.repo.query.idle_time", unit: {:native, :millisecond}), # VM Metrics summary("vm.memory.total", unit: {:byte, :kilobyte}), summary("vm.total_run_queue_lengths.total"), summary("vm.total_run_queue_lengths.cpu"), summary("vm.total_run_queue_lengths.io") ] end defp periodic_measurements do [ # A module, function and arguments to be invoked periodically. # This function must call :telemetry.execute/3 and a metric must be added above. # {PraxkitWeb, :count_users, []} ] end end
32.482143
86
0.671798
f768dbcf88244a5e34e13ccb78ec580ce877d4d3
177
ex
Elixir
vendor/tree-sitter-elixir/test/highlight/identifiers.ex
jessesna/difftastic
2c6545fae403f360c8b4d0e64fb3ece2baa8deea
[ "MIT" ]
125
2021-09-30T10:55:46.000Z
2022-03-16T10:49:32.000Z
vendor/tree-sitter-elixir/test/highlight/identifiers.ex
jessesna/difftastic
2c6545fae403f360c8b4d0e64fb3ece2baa8deea
[ "MIT" ]
21
2021-10-01T22:47:58.000Z
2022-03-25T19:43:13.000Z
vendor/tree-sitter-elixir/test/highlight/identifiers.ex
jessesna/difftastic
2c6545fae403f360c8b4d0e64fb3ece2baa8deea
[ "MIT" ]
9
2021-10-13T13:06:11.000Z
2022-02-12T17:16:06.000Z
abc_123 # ^ variable _018OP # ^ comment.unused A__0 # ^ module __MODULE__ ; __STACKTRACE__ # ^ constant.builtin # ^ constant.builtin __OTHER__ # ^ comment.unused
11.0625
31
0.677966
f768de6e3eb69e2e019eda9586f1e6d9c4a3bd12
1,170
exs
Elixir
config/dev.exs
matthewphilyaw/basic_auth_test
9bd6b62c8680ec603314adab940b8840e50b240c
[ "MIT" ]
null
null
null
config/dev.exs
matthewphilyaw/basic_auth_test
9bd6b62c8680ec603314adab940b8840e50b240c
[ "MIT" ]
null
null
null
config/dev.exs
matthewphilyaw/basic_auth_test
9bd6b62c8680ec603314adab940b8840e50b240c
[ "MIT" ]
null
null
null
use Mix.Config # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with brunch.io to recompile .js and .css sources. config :foo_api, FooApi.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, cache_static_lookup: false, check_origin: false, watchers: [] # Watch static and templates for browser reloading. config :foo_api, FooApi.Endpoint, live_reload: [ patterns: [ ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$}, ~r{web/views/.*(ex)$}, ~r{web/templates/.*(eex)$} ] ] # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. # Do not configure such in production as keeping # and calculating stacktraces is usually expensive. config :phoenix, :stacktrace_depth, 20 # Configure your database config :foo_api, FooApi.Repo, adapter: Ecto.Adapters.Postgres, username: "postgres", password: "postgres", database: "foo_api_dev", pool_size: 10
27.857143
60
0.719658
f768f54838f99455f457b805983696b5ff2870b7
941
exs
Elixir
mix.exs
danieledangeli/oanda_elixir
11d10c5603b1048ec9a31831bd1bc7c08198eb98
[ "Apache-2.0" ]
2
2018-02-28T06:02:32.000Z
2020-11-09T19:40:40.000Z
mix.exs
danieledangeli/oanda_elixir
11d10c5603b1048ec9a31831bd1bc7c08198eb98
[ "Apache-2.0" ]
null
null
null
mix.exs
danieledangeli/oanda_elixir
11d10c5603b1048ec9a31831bd1bc7c08198eb98
[ "Apache-2.0" ]
null
null
null
defmodule OandaApi.Mixfile do use Mix.Project def project do [app: :oanda_api, version: "0.1.0", elixir: "~> 1.3", build_embedded: Mix.env == :prod, start_permanent: Mix.env == :prod, description: description(), package: package(), deps: deps()] end def application do [applications: [:logger, :httpoison]] end defp deps do [ {:httpoison, "~> 0.9"}, {:poison, "~> 3.0"}, {:ex_doc, ">= 0.0.0", only: :dev} ] end defp description do """ Oanda Elixir client wrapper """ end defp package do [# These are the default files included in the package name: :oanda_api, files: ["lib", "mix.exs", "README*", "LICENSE*"], maintainers: ["Daniele D'Angeli"], licenses: ["Apache 2.0"], links: %{"GitHub" => "https://github.com/danieledangeli/oanda_elixir", "Docs" => "https://github.com/danieledangeli/oanda_elixir"}] end end
23.525
86
0.587673
f76924666f13aecdf6ee70c00e16678eca3c99e8
3,760
ex
Elixir
lib/bike_brigade_web/live/sms_message_live/conversation_component.ex
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
28
2021-10-11T01:53:53.000Z
2022-03-24T17:45:55.000Z
lib/bike_brigade_web/live/sms_message_live/conversation_component.ex
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
20
2021-10-21T08:12:31.000Z
2022-03-31T13:35:53.000Z
lib/bike_brigade_web/live/sms_message_live/conversation_component.ex
bikebrigade/dispatch
eb622fe4f6dab7c917d678d3d7a322a01f97da44
[ "Apache-2.0" ]
null
null
null
defmodule BikeBrigadeWeb.SmsMessageLive.ConversationComponent do use BikeBrigadeWeb, :live_component import BikeBrigadeWeb.MessagingHelpers alias BikeBrigade.Messaging alias BikeBrigade.MediaStorage alias BikeBrigade.SmsService @impl Phoenix.LiveComponent def mount(socket) do socket = socket |> allow_upload(:media, accept: ~w(.gif .png .jpg .jpeg), max_entries: 10) |> assign_confirm_send_warning() {:ok, socket, temporary_assigns: [scrollback: [], conversation: []]} end def assign_confirm_send_warning(socket) do assign(socket, :confirm_send, SmsService.sending_confirmation_message()) end @impl Phoenix.LiveComponent def update(%{rider: rider} = assigns, socket) do conversation = Messaging.latest_messages(rider) earliest_timestamp = case conversation do [first | _] -> first.sent_at [] -> nil end {:ok, socket |> assign(assigns) |> assign_new_sms_message() |> assign(conversation: conversation) |> assign(earliest_timestamp: earliest_timestamp) |> assign(phx_update: "append")} end @impl Phoenix.LiveComponent def update(%{conversation: conversation} = assigns, socket) do {:ok, socket |> assign(assigns) |> assign(conversation: conversation) |> assign(phx_update: "append") |> push_event("new-message", %{})} end @impl Phoenix.LiveComponent def update(assigns, socket) do {:ok, socket |> assign(assigns)} end @impl Phoenix.LiveComponent def handle_event("cancel-upload", %{"ref" => ref}, socket) do {:noreply, cancel_upload(socket, :media, ref)} end @impl Phoenix.LiveComponent def handle_event("validate", %{"sms_message" => sms_message_params}, socket) do changeset = Messaging.send_sms_message_changeset(socket.assigns.sms_message, sms_message_params) {:noreply, socket |> assign(changeset: changeset)} end @impl Phoenix.LiveComponent def handle_event( "send", %{"sms_message" => sms_message_params}, socket ) do media = consume_uploaded_entries(socket, :media, fn %{path: path}, %{client_type: content_type} -> # TODO do some guards on content type here MediaStorage.upload_file!(path, content_type) end) {:noreply, send_sms_message(socket, Map.put(sms_message_params, "media", media))} end @impl Phoenix.LiveComponent def handle_event("load-more", _params, socket) do %{rider: rider, earliest_timestamp: earliest_timestamp} = socket.assigns conversation = Messaging.latest_messages(rider, earliest_timestamp) case conversation do [first | _] -> {:reply, %{}, socket |> assign(:conversation, conversation) |> assign(:earliest_timestamp, first.sent_at) |> assign(:phx_update, "prepend")} [] -> {:reply, %{}, socket} end end defp send_sms_message(socket, params) do case Messaging.send_sms_message(socket.assigns.sms_message, params) do {:ok, _sent_sms_message} -> assign_new_sms_message(socket) {:error, %Ecto.Changeset{} = changeset} -> assign(socket, :changeset, changeset) end end defp assign_new_sms_message(socket) do sms_message = Messaging.new_sms_message(socket.assigns.rider, sent_by: socket.assigns.current_user) changeset = Messaging.send_sms_message_changeset(sms_message) socket |> assign(changeset: changeset) |> assign(sms_message: sms_message) end def error_to_string(:too_large), do: "Too large" def error_to_string(:too_many_files), do: "You have selected too many files" def error_to_string(:not_accepted), do: "You have selected an unacceptable file type" end
28.70229
96
0.681915
f76944dada5df8d9103f617c9f2493a601df8edf
503
ex
Elixir
unscheduled/live_view_performance_tips/code/lv_performance/lib/lv_performance_web/views/error_view.ex
rellen/talks
97e123e6cb331b78fa737c90cedc2974a35243e4
[ "CC-BY-4.0" ]
1
2022-02-16T09:00:34.000Z
2022-02-16T09:00:34.000Z
unscheduled/live_view_performance_tips/code/lv_performance/lib/lv_performance_web/views/error_view.ex
rellen/talks
97e123e6cb331b78fa737c90cedc2974a35243e4
[ "CC-BY-4.0" ]
null
null
null
unscheduled/live_view_performance_tips/code/lv_performance/lib/lv_performance_web/views/error_view.ex
rellen/talks
97e123e6cb331b78fa737c90cedc2974a35243e4
[ "CC-BY-4.0" ]
null
null
null
defmodule LvPerformanceWeb.ErrorView do use LvPerformanceWeb, :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.588235
61
0.741551
f769798164ea68ee116d7b44818485f24e1359d6
235
exs
Elixir
apps/snitch_core/priv/repo/migrations/20180223102833_create_constraints_on_payment_subtypes.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
456
2018-09-20T02:40:59.000Z
2022-03-07T08:53:48.000Z
apps/snitch_core/priv/repo/migrations/20180223102833_create_constraints_on_payment_subtypes.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
273
2018-09-19T06:43:43.000Z
2021-08-07T12:58:26.000Z
apps/snitch_core/priv/repo/migrations/20180223102833_create_constraints_on_payment_subtypes.exs
Acrecio/avia
54d264fc179b5b5f17d174854bdca063e1d935e9
[ "MIT" ]
122
2018-09-26T16:32:46.000Z
2022-03-13T11:44:19.000Z
defmodule Core.Repo.Migrations.CreateConstraintsOnPaymentSubtypes do use Ecto.Migration def change do create constraint("snitch_card_payments", :card_exclusivity, check: "payment_exclusivity(payment_id, 'ccd') = 1") end end
29.375
117
0.791489
f7699fe6ab98146d07bc95e812f9e430d247dd0b
32,270
ex
Elixir
lib/webdriver/protocol.ex
bosko/elixir-webdriver
e7037312decab6646b2107b7345f2974b24a9d15
[ "MIT" ]
104
2015-02-11T02:57:53.000Z
2022-01-12T14:28:12.000Z
lib/webdriver/protocol.ex
bosko/elixir-webdriver
e7037312decab6646b2107b7345f2974b24a9d15
[ "MIT" ]
3
2015-07-23T18:48:11.000Z
2016-10-12T14:28:43.000Z
lib/webdriver/protocol.ex
bosko/elixir-webdriver
e7037312decab6646b2107b7345f2974b24a9d15
[ "MIT" ]
28
2015-01-09T22:05:27.000Z
2021-04-29T13:55:13.000Z
defmodule WebDriver.Protocol do use Jazz @moduledoc """ Implements the HTTP JSON wire protocol for WebDriver. This is the internal protocol and is supposed to be called via the WebDriver session server rather than directly. https://code.google.com/p/selenium/wiki/JsonWireProtocol All these calls take a WebDriver.Config record as a first parameter. The other parameters depend on the specific protocol call. All successful calls return {:ok, response} where response is a WebDriver.Protocol.Response record. Failed calls return {:error, status, body} where the status is the HTTP status returned and the body is the raw body of the returned response. A WebDriver response consists of a session id, status and return value. The session id is an opaque string provided by the server. The status can be one of the WebDriver status codes: https://code.google.com/p/selenium/wiki/JsonWireProtocol#/status The value varies according to the call made. The Response struct defined here also appends the request details to that response. """ defmodule Response do defstruct session_id: :null, status: 0, value: :null, request: :null end defmodule Request do defstruct method: "GET", url: "", headers: :null, body: :null end def shutdown(root_url) do get root_url, ["shutdown"] end @doc """ Returns the status of the WebDriver server. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/status ## Examples: iex> config = WebDriver.Config[host: "localhost", port: 8080] iex> resp = WebDriver.Protocol.status(config) iex> resp.status 0 iex> resp.session_id :null iex> resp.value [{"build",[{"version","1.0.3"}]},{"os",[{"name","mac"},{"version","10.8 (Mountain Lion)"},{"arch","32bit"}]}] """ def status(root_url, _session_id \\ :null) do get root_url, ["status"] end @doc """ Creates a new session on the server. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session Parameters: [desiredCapabilities: WebDriver.Protocol.Capabilities] ## Examples: iex> config = WebDriver.Config[host: "localhost", port: 8080] iex> resp = WebDriver.Protocol.start_session(config, [desiredCapabilities: []]) iex> resp.session_id "370f0750-e1dd-11e2-af7a-8562953caa56" """ def start_session(root_url, parameters) do post root_url, ["session"], parameters end @doc """ Gets a list of all sessions on the server. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/sessions """ def sessions(root_url, _session_id \\ :null) do get root_url, ["sessions"] end @doc """ Retreive information about a session. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId """ def session(root_url, session_id) do get root_url, ["session", session_id] end @doc """ Stop the current session on the server. https://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId """ def stop_session(root_url, session_id) do delete root_url, ["session", session_id] end @doc """ Set timeouts on the server. Parameters must include the type of timeout and the length in milliseconds (ms). Valid types are "script" and "implicit" Parameters [type: "script"|"implicit", ms: number] """ def set_timeout(root_url, session_id, parameters) do session_post root_url, session_id, "timeouts", parameters end @doc """ Set the script timeout for the session. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/timeouts/async_script Parameters: [ms: number] """ def set_async_script_timeout(root_url, session_id, parameters) do post root_url, ["session", session_id, "timeouts", "async_script"], parameters end @doc """ Set the implicit wait timeout for the session. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/timeouts/implicit_wait Parameters: [ms: number] """ def set_implicit_wait_timeout(root_url, session_id, parameters) do post root_url, ["session", session_id, "timeouts", "implicit_wait"], parameters end @doc """ Get the current window handle for the session. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/window_handle """ def window_handle(root_url, session_id) do session_get root_url, session_id, "window_handle" end @doc """ Retreive a list of window handles available for the session. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/window_handles """ def window_handles(root_url, session_id) do session_get root_url, session_id, "window_handles" end @doc """ Retreive the URL of the current page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/url """ def url(root_url, session_id) do session_get root_url, session_id, "url" end @doc """ Navigate to a new URL. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/url Parameters: [url: new_url] """ def url(root_url, session_id, parameters) do session_post root_url, session_id, "url", parameters end @doc """ Navigate forward to the next page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/forward """ def forward(root_url, session_id) do session_post root_url, session_id, "forward" end @doc """ Navigate back to the previous page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/back """ def back(root_url, session_id) do session_post root_url, session_id, "back" end @doc """ Refresh the current page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/refresh """ def refresh(root_url, session_id) do session_post root_url, session_id, "refresh" end @doc """ Execute Javascript on the page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/execute Parameters: [script: string, args: list] ## Example: iex> config = WebDriver.Config[host: "localhost", port: 8080] iex> sid = WebDriver.Protocol.start_session(config, [desiredCapabilities: []]).session_id iex> resp = WebDriver.Protocol.execute(config, sid, [script: "return 1+1", args: []]) iex> resp.value 2 """ def execute(root_url, session_id, parameters) do session_post root_url, session_id, "execute", parameters end @doc """ Execute asynchronous Javascript on the page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/execute_async Parameters: [script: string, args: list] """ def execute_async(root_url, session_id, parameters) do session_post root_url, session_id, "execute_async", parameters end @doc """ Retreive a screenshot of the current page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/screenshot Returns a base64 encoded PNG image. """ def screenshot(root_url, session_id) do session_get root_url, session_id, "screenshot" end @doc """ IME FUNCTIONS ARE NOT YET IMPLEMENTED """ def ime(_root_url, _session_id) do raise "Not Implemented" end @doc """ Change the frame that has focus in the current window. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/frame Parameters: [id: string | number | :null | WebElement] """ def frame(root_url, session_id, parameters) do session_post root_url, session_id, "frame", parameters end @doc """ Change the focus to another window. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/window The window may be specified by the server assigned window handle or the value of it's name attribute. Parameters: [name: string] """ def window(root_url, session_id, parameters) do session_post root_url, session_id, "window", parameters end @doc """ Closes the current window. https://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/window """ def close_window(root_url, session_id) do session_delete root_url, session_id, "window" end @doc """ Retreive the window size. If a window handle is not specified it retreives the current window. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/window/:windowHandle/size When the parameters are specified this will change the window size. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/window/:windowHandle/size Parameters: [height: number, width: number] """ def window_size(root_url, session_id, window_handle \\ "current", parameters \\ :null) do do_window_size(root_url, session_id, window_handle, parameters) end defp do_window_size(root_url, session_id, window_handle, :null) do session_get root_url, session_id, "window/#{window_handle}/size" end defp do_window_size(root_url, session_id, window_handle, parameters) do session_post root_url, session_id, "window/#{window_handle}/size", parameters end @doc """ Retreive the window position for the specified window or if not specified, the current window. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/window/:windowHandle/position Set the window position for the specified window if parameters are sent. Set window handle to "current" to set the current window position. Parameters: [x: number, y: number] """ def window_position(root_url, session_id, window_handle \\ "current", parameters \\ :null) do do_window_position(root_url, session_id, window_handle, parameters) end defp do_window_position(root_url, session_id, window_handle, :null) do session_get root_url, session_id, "window/#{window_handle}/position" end defp do_window_position(root_url, session_id, window_handle, parameters) do session_post root_url, session_id, "window/#{window_handle}/position", parameters end @doc """ Maximise the specified window. Use "current" or simply do not specify a handle to maximise the current window. """ def maximize_window(root_url, session_id, window_handle \\ "current") do session_post root_url, session_id, "window/#{window_handle}/maximize" end @doc """ Retreive all the cookies associated with the current page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/cookie """ def cookies(root_url, session_id) do session_get root_url, session_id, "cookie" end @doc """ Set a cookie for the current page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/cookie Parameters: [cookie: object] """ def set_cookie(root_url, session_id, parameters) do session_post root_url, session_id, "cookie", parameters end @doc """ Delete all cookies for the current page. https://code.google.com/p/selenium/wiki/JsonWireProtocol#DELETE_/session/:sessionId/cookie """ def delete_cookies(root_url, session_id) do session_delete root_url, session_id, "cookie" end @doc """ Delete the cookie with the given name. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/cookie/:name """ def delete_cookie(root_url, session_id, name) do session_delete root_url, session_id, "cookie/#{name}" end @doc """ Retreive the curent page source. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/source """ def source(root_url, session_id) do session_get root_url, session_id, "source" end @doc """ Retreive the current page title. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/title """ def title(root_url, session_id) do session_get root_url, session_id, "title" end @doc """ Retreive an element from the page using the specified search strategy. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element Parameters [using: "class name" | "css selector" | "id" | "name" | "link text" | "partial link test" | "tag name" | "xpath", value: string] """ def element(root_url, session_id, parameters) do session_post root_url, session_id, "element", parameters end @doc """ Retreive an element from the page starting from the specified element using the specified search strategy. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/element Parameters [using: "class name" | "css selector" | "id" | "name" | "link text" | "partial link test" | "tag name" | "xpath", value: string] """ def element(root_url, session_id, element_id, parameters) do element_post root_url, session_id, element_id, "element", parameters end @doc """ Retreive all elements from the page using the specified search strategy. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element Parameters [using: "class name" | "css selector" | "id" | "name" | "link text" | "partial link test" | "tag name" | "xpath", value: string] """ def elements(root_url, session_id, parameters) do session_post root_url, session_id, "elements", parameters end @doc """ Retreive all elements starting from the specified element using the specified search strategy. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/elements Parameters [using: "class name" | "css selector" | "id" | "name" | "link text" | "partial link test" | "tag name" | "xpath", value: string] """ def elements(root_url, session_id, element_id, parameters) do element_post root_url, session_id, element_id, "elements", parameters end @doc """ Get the element on the page that currently has focus. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/active """ def active_element(root_url, session_id) do session_get root_url, session_id, "element/active" end @doc """ Get the element identified by the id. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id """ def element_by_id(root_url, session_id, element_id) do session_get root_url, session_id, "element/#{element_id}" end @doc """ Click on the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/click """ def click(root_url, session_id, element_id) do element_post root_url, session_id, element_id, "click" end @doc """ Submit a FORM element. May be applied to any descendent of a FORM element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/submit """ def submit(root_url, session_id, element_id) do element_post root_url, session_id, element_id, "submit" end @doc """ Retreives the visible text of the element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/text """ def text(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "text" end @doc """ Send a list of keystrokes to the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/element/:id/value Parameters: [value: Array<string>] """ def value(root_url, session_id, element_id, parameters) do element_post root_url, session_id, element_id, "value", parameters end @doc """ Send a list of keystrokes to the currently active element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/keys Parameters: [value: Array<string>] """ def keys(root_url, session_id, parameters) do session_post root_url, session_id, "keys", parameters end @doc """ Get the name of the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/name """ def name(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "name" end @doc """ Clears the specified form field or textarea element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/clear """ def clear(root_url, session_id, element_id) do element_post root_url, session_id, element_id, "clear" end @doc """ Returns a boolean denoting if the element is selected or not. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/selected """ def selected(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "selected" end @doc """ Returns a boolean denoting if the element is enabled or not. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/enabled """ def enabled(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "enabled" end @doc """ Returns the value of the given element's attribute. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/attribute/:name """ def attribute(root_url, session_id, element_id, name) do element_get root_url, session_id, element_id, "attribute/#{name}" end @doc """ Determine if two element ids refer to the same DOM element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/equals/:other """ def equals(root_url, session_id, element_id, other_id) do element_get root_url, session_id, element_id, "equals/#{other_id}" end @doc """ Returns a boolean denoting if the element is currently visible. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/displayed """ def displayed(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "displayed" end @doc """ Returns the current location of the specified element https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location """ def location(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "location" end @doc """ Determine an element's location once it has been scrolled into view. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/location_in_view """ def location_in_view(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "location_in_view" end @doc """ Get the size of an element in pixels. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/size """ def size(root_url, session_id, element_id) do element_get root_url, session_id, element_id, "size" end @doc """ Get the computed value of an element's CSS property. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/element/:id/css/:propertyName """ def css(root_url, session_id, element_id, property_name) do element_get root_url, session_id, element_id, "css/#{property_name}" end @doc """ Get the current browser screen orientation. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/orientation """ def orientation(root_url, session_id) do session_get root_url, session_id, "orientation" end @doc """ Set the current browser screen orientation https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/orientation """ def orientation(root_url, session_id, parameters) do session_post root_url, session_id, "orientation", parameters end @doc """ Gets the text of the currently displayed JavaScript alert(), confirm(), or prompt() dialog. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/alert_text """ def alert_text(root_url, session_id) do session_get root_url, session_id, "alert_text" end @doc """ Sends keystrokes to a Javascript prompt() dialog. """ def alert_text(root_url, session_id, parameters) do session_post root_url, session_id, "alert_text", parameters end @doc """ Accepts the currently displayed alert dialog https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/accept_alert """ def accept_alert(root_url, session_id) do session_post root_url, session_id, "accept_alert" end @doc """ Dismisses the currently displayed alert dialog https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/dismiss_alert """ def dismiss_alert(root_url, session_id) do session_post root_url, session_id, "dismiss_alert" end @doc """ Move the mouse by an offset to the specified element. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/moveto Parameters: [element: element_id, offsetx: number, offsety: number] """ def move_to(root_url, session_id, parameters) do session_post root_url, session_id, "moveto", parameters end @doc """ Send a mouse click at the position of the last move_to command. The parameter is a number indicating which button is to be clicked. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/click Defaults to the left button if not specified. Parameters: [button: 1(left) | 2(middle) | 3(right)] """ def mouse_click(root_url, session_id, parameters \\ %{}) do session_post root_url, session_id, "click", parameters end @doc """ Send a mouse button down event. The parameter is a number indicating which button is to be pressed. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/buttondown Defaults to the left button if not specified. Parameters: [button: 1(left) | 2(middle) | 3(right)] """ def mouse_button_down(root_url, session_id, parameters \\ %{}) do session_post root_url, session_id, "buttondown", parameters end @doc """ Send a mouse button up event. Every button down event needs to be followed by this. The parameter is a number indicating which button is to be raised. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/buttondown Defaults to the left button if not specified. Parameters: [button: 1(left) | 2(middle) | 3(right)] """ def mouse_button_up(root_url, session_id, parameters \\ %{}) do session_post root_url, session_id, "buttonup", parameters end @doc """ Send a double click at the position of the last move_to command. The parameter is a number indicating which button is to be double clicked. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/click Defaults to the left button if not specified. Parameters: [button: 1(left) | 2(middle) | 3(right)] """ def mouse_double_click(root_url, session_id, parameters \\ %{}) do session_post root_url, session_id, "doubleclick", parameters end @doc """ Finger tap on an element on the screen. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/click Parameters: [element: element_id] The element to tap on. """ def touch_click(root_url, session_id, parameters) do session_post root_url, session_id, "touch/click", parameters end @doc """ Finger down on the screen. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/down Parameters: [x: number, y: number] """ def touch_down(root_url, session_id, parameters) do session_post root_url, session_id, "touch/down", parameters end @doc """ Finger up on the screen https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/up Parameters: [x: number, y: number] """ def touch_up(root_url, session_id, parameters) do session_post root_url, session_id, "touch/up", parameters end @doc """ Move the finger on the screen to the specified position. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/move Parameters: [x: number, y: number] """ def touch_move(root_url, session_id, parameters) do session_post root_url, session_id, "touch/move", parameters end @doc """ Scroll on the touch screen using finger based motion events. The element parameter is optional and can be left out if you dont care where the scroll starts. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_session/:sessionId/touch/scroll Parameters [element: element, x: number, y:number] """ def touch_scroll(root_url, session_id, parameters) do session_post root_url, session_id, "touch/scroll", parameters end @doc """ Double finger tap on an element on the screen. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/doubleclick Parameters: [element: element_id] The element to tap on. """ def touch_double_click(root_url, session_id, parameters) do session_post root_url, session_id, "touch/doubleclick", parameters end @doc """ Long finger tap on an element on the screen. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/longclick Parameters: [element: element_id] The element to tap on. """ def touch_long_click(root_url, session_id, parameters) do session_post root_url, session_id, "touch/longclick", parameters end @doc """ Flick on the touch screen using finger motion events. The element, xoffset and yoffset parameters are optional if you do not care where the flick starts. https://code.google.com/p/selenium/wiki/JsonWireProtocol#/session/:sessionId/touch/flick Parameters: [element: element_id, xoffset: number, yoffset: number, xSpeed: number, ySpeed: number] """ def touch_flick(root_url, session_id, parameters) do session_post root_url, session_id, "touch/flick", parameters end @doc """ Retreive the current geo location of the browser. https://code.google.com/p/selenium/wiki/JsonWireProtocol#GET_/session/:sessionId/location """ def geo_location(root_url, session_id) do session_get root_url, session_id, "location" end @doc """ Set the current geo location of the browser. https://code.google.com/p/selenium/wiki/JsonWireProtocol#POST_/session/:sessionId/location Parameters: [lattitude: number, longitude: number, altitude: number] """ def geo_location(root_url, session_id, parameters) do session_post root_url, session_id, "location", parameters end @doc """ LOCAL STORAGE NOT YET IMPLEMENTED """ def local_storage do end ########################################################################### # Private Functions ########################################################################### defp url_for root_url, path_elements do path = Enum.join(path_elements, "/") "#{root_url}/#{path}" end defp session_get root_url, session_id, command do get root_url, ["session", session_id, command] end defp element_get root_url, session_id, element_id, command do get root_url, ["session", session_id, "element", element_id, command] end defp get root_url, path_elements do url = url_for root_url, path_elements request = %Request{method: :GET, url: url, headers: [{"Accept", "application/json;charset=UTF-8"}]} send_request root_url, request end defp session_post root_url, session_id, command, params \\ %{} do post root_url, ["session", session_id, command], params end defp element_post root_url, session_id, element_id, command, params \\ %{} do post root_url, ["session", session_id, "element", element_id, command], params end defp post root_url, path_elements, params do url = url_for root_url, path_elements json = JSON.encode! params request = %Request{method: :POST, url: url, headers: ["Content-Type": "application/json;charset=UTF-8","Content-Length": byte_size(json)], body: json} send_request root_url, request end defp session_delete root_url, session_id, command do delete root_url, ["session", session_id, command] end defp delete root_url, path_elements do url = url_for root_url, path_elements request = %Request{method: :DELETE, url: url, headers: [{"Accept", "application/json;charset=UTF-8"}]} send_request root_url, request end defp send_request root_url, request do send_request root_url, request, 0 end defp send_request root_url, _request, 100 do raise "We seem to have lost the connection to the browser at #{root_url}" end # Send the request to the underlying HTTP protocol. defp send_request root_url, request, attempts do if :application.get_env(:debug_browser) == {:ok, true} do IO.puts "SENDING REQUEST: #{request.method}" IO.puts "URL: #{request.url}" #IO.puts "HEADERS: #{request.headers}" IO.puts "BODY: #{request.body}" end try do case request.method do :GET -> HTTPotion.get(request.url, [headers: request.headers]) :POST -> HTTPotion.post(request.url, [body: request.body, headers: request.headers]) :DELETE -> HTTPotion.delete(request.url, [headers: request.headers]) end |> handle_response(root_url) |> add_request(request) rescue [HTTPotion.HTTPError, :econnrefused] -> # Try again a bit later cause Firefox is a sluggard. :timer.sleep(:random.uniform(1000) + 200) send_request root_url, request, (attempts + 1) end end defp handle_response(%HTTPotion.Response{body: body, status_code: status, headers: _headers}, _root_url) when status in 200..299 do if :application.get_env(:debug_browser) == {:ok, true} do IO.inspect body end # Chromedriver sends failed commands with a 200 status. response = parse_response_body(body) case response.status do 0 -> {:ok, response} _ -> {:failed_command, response.status, response} end end defp handle_response(%HTTPotion.Response{body: _body, status_code: status, headers: headers}, root_url) when status in 302..303 do # Cause some use upper case and some dont... url = Keyword.get(headers, :Location, Keyword.get(headers, :location)) # Follow redirect request = Request[method: :GET, url: url, headers: [{"Accept", "application/json;charset=UTF-8"}]] send_request root_url, request end defp handle_response(%HTTPotion.Response{body: body, status_code: status, headers: _headers}, _root_url) when status in 400..499 do {:invalid_request, status, body} end defp handle_response(%HTTPotion.Response{body: body, status_code: status, headers: _headers}, _root_url) when status in 500..599 do response = parse_response_body(body) {:failed_command, status, response} end defp parse_response_body body do build_response JSON.decode!(body) end defp build_response(%{"sessionId" => session_id, "status" => status, "value" => value })do %Response{ session_id: session_id, status: status, value: value } end defp build_response(%{"name" => _name, "sessionId" => session_id, "status" => status, "value" => value })do %Response{ session_id: session_id, status: status, value: value } end # Append the Request record to a response. defp add_request {:ok, response}, request do {:ok, %{response | request: request}} end defp add_request {:failed_command, _status, response}, request do {WebDriver.Error.summary(response.status), %{response | request: request}} end defp add_request {:invalid_request, status, response}, request do {:invalid_request, status, response, request} end end
34.886486
115
0.709266
f769a58a24d933f7414045acb321607048708e74
1,270
exs
Elixir
benchmarks.exs
ckampfe/ox
d8da521a580dd14df27406ac2fe35ab8890f979a
[ "MIT" ]
null
null
null
benchmarks.exs
ckampfe/ox
d8da521a580dd14df27406ac2fe35ab8890f979a
[ "MIT" ]
null
null
null
benchmarks.exs
ckampfe/ox
d8da521a580dd14df27406ac2fe35ab8890f979a
[ "MIT" ]
null
null
null
alias Ox.LeftistHeap, as: Heap random = StreamData.integer() |> Stream.map(&abs/1) [random_int] = StreamData.integer() |> Stream.map(&abs/1) |> Enum.take(1) small = random |> Enum.take(100) medium = random |> Enum.take(10_000) large = random |> Enum.take(1_000_000) int_compare_fn = fn x, y -> x <= y end small_heap = Heap.new(small, int_compare_fn) medium_heap = Heap.new(medium, int_compare_fn) large_heap = Heap.new(large, int_compare_fn) Benchee.run( %{ "new small" => fn -> Heap.new(small, int_compare_fn) end, "new medium" => fn -> Heap.new(medium, int_compare_fn) end, "new large" => fn -> Heap.new(large, int_compare_fn) end, "insert small" => fn -> Heap.insert(small_heap, random_int) end, "insert medium" => fn -> Heap.insert(medium_heap, random_int) end, "insert large" => fn -> Heap.insert(large_heap, random_int) end, "min small" => fn -> Heap.min(small_heap) end, "min medium" => fn -> Heap.min(medium_heap) end, "min large" => fn -> Heap.min(large_heap) end, "delete_min small" => fn -> Heap.delete_min(small_heap) end, "delete_min medium" => fn -> Heap.delete_min(medium_heap) end, "delete_min large" => fn -> Heap.delete_min(large_heap) end }, memory_time: 2, print: [fast_warning: false] )
36.285714
73
0.666929
f769b6af8d2203e2dd71935c92ad4bc1f9dbc9f8
1,570
exs
Elixir
config/config.exs
zmstone/kastlex
3478bc230f08bde99e768067787b0ef3f8e1c026
[ "Apache-2.0" ]
38
2016-10-21T08:26:15.000Z
2021-03-19T23:10:40.000Z
config/config.exs
zmstone/kastlex
3478bc230f08bde99e768067787b0ef3f8e1c026
[ "Apache-2.0" ]
32
2017-02-19T08:57:35.000Z
2020-02-05T13:15:11.000Z
config/config.exs
zmstone/kastlex
3478bc230f08bde99e768067787b0ef3f8e1c026
[ "Apache-2.0" ]
6
2017-11-24T16:02:20.000Z
2022-02-22T07:44:36.000Z
# 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. use Mix.Config # Configures the endpoint config :kastlex, Kastlex.Endpoint, root: Path.dirname(__DIR__), secret_key_base: "2N8sGXA6wijnGpzmiEl3y6H2YCf7RbeBbi7xgE58txpm6AxDWS+A4TYrUY0jYYGV", render_errors: [accepts: ~w(json), default_format: ~w(json)], pubsub: [name: Phoenix.PubSub, adapter: Phoenix.PubSub.PG2] config :kastlex, Kastlex.MetadataCache, refresh_timeout_ms: 30000 config :kastlex, Kastlex.TokenStorage, topic: "_kastlex_tokens" # Configures Elixir's Logger config :logger, :console, format: "$time [$level] $message $metadata\n", metadata: [:request_id, :remote_ip, :module, :function, :line], handle_otp_reports: true, handle_sasl_reports: true # Configure phoenix generators config :phoenix, :generators, migration: true, binary_id: false config :phoenix, :json_library, Jason config :mime, :types, %{ "*/*" => ["json"], "application/json" => ["json"], "application/binary" => ["binary"], } config :guardian, Guardian, allowed_algos: ["ES512"], verify_module: Guardian.JWT, issuer: "Kastlex", ttl: { 30, :days }, verify_issuer: true, secret_key_file: "priv/jwk.pem", serializer: Kastlex.GuardianSerializer # 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"
28.545455
86
0.735669
f769c3034876e4d8d395323e57843f1bff309bc2
5,381
ex
Elixir
lib/central/general/startup.ex
Teifion/teiserver
131e002160e1e948cb55e56d62370ba66a972cba
[ "MIT" ]
6
2021-02-08T10:42:53.000Z
2021-04-25T12:12:03.000Z
lib/central/general/startup.ex
Jazcash/teiserver
fec14784901cb2965d8c1350fe84107c57451877
[ "MIT" ]
null
null
null
lib/central/general/startup.ex
Jazcash/teiserver
fec14784901cb2965d8c1350fe84107c57451877
[ "MIT" ]
2
2021-02-23T22:34:00.000Z
2021-04-08T13:31:36.000Z
defmodule Central.General.Startup do use CentralWeb, :startup def startup do QuickAction.add_items([ %{ label: "Admin index", icons: [Central.Admin.AdminLib.icon(), :list], url: "/admin", permissions: "admin.admin.limited" }, %{ label: "Tools", icons: [Central.Admin.ToolLib.icon()], url: "/admin/tools", permissions: "admin.dev.developer" }, %{ label: "List users", icons: [Central.Account.UserLib.icon(), :list], input: "s", method: "get", placeholder: "Search username and/or email", url: "/admin/users", permissions: "admin.admin.limited" }, %{ label: "List groups", icons: [Central.Account.GroupLib.icon(), :list], input: "s", method: "get", placeholder: "Search name", url: "/admin/groups", permissions: "admin.admin.limited" }, %{ label: "Coverage", icons: ["far fa-percent"], url: "/admin/tools/coverage", permissions: "admin.dev.developer" }, %{label: "Home", icons: ["far fa-home"], url: "/"} ]) add_user_config_type(%{ key: "general.Rate limit", section: "General", type: "integer", visible: false, permissions: ["admin.dev.developer"], description: "Page rate limit per minute", opts: [], default: nil }) add_user_config_type(%{ key: "general.User message", section: "General", type: "boolean", visible: false, permissions: ["admin.dev.developer"], description: "A message displayed on every page the user visits", opts: [], default: nil }) add_user_config_type(%{ key: "module.Quick action", section: "Modules", type: "boolean", visible: true, permissions: [], description: "Enables the 'Quick Action' shortcut: Ctrl + .", opts: [], default: nil }) add_user_config_type(%{ key: "general.Homepage", section: "General", type: "string", visible: true, permissions: [], description: "Sets the default homepage for when you first log in", opts: [], default: "/" }) add_user_config_type(%{ key: "general.Sidebar", section: "General", type: "boolean", visible: true, permissions: [], description: "Shows the sidebar menu", opts: [], default: true }) add_user_config_type(%{ key: "general.Screen size", section: "General", type: "string", visible: false, permissions: ["admin.dev.developer"], description: "Last recoreded screen size of the user, used for sizing certain windows accordingly", opts: [], default: nil }) add_user_config_type(%{ key: "general.Advanced configs", section: "General", type: "boolean", visible: false, permissions: ["admin.dev.developer"], description: "Changes the default behaviour of showing or hiding advanced options on the forms supporting them.", opts: [], default: false }) # Need to get the timezones zones = 'timedatectl list-timezones' |> :os.cmd() |> to_string |> String.split("\n") add_user_config_type(%{ key: "general.Timezone", section: "General", type: "select", visible: true, permissions: [], description: "The timezone you are present in for conversion of timestamps.", opts: [ choices: zones ], default: Application.get_env(:central, Central.Config)[:defaults].tz }) add_user_config_type(%{ key: "general.Language", section: "General", type: "select", visible: false, permissions: [], description: "Language used on the site (currently only English).", opts: ~w(English), default: false }) # Example site configs # add_site_config_type(%{ # key: "general.Allow site registrations", # section: "General", # type: "boolean", # permissions: ["admin.dev.developer"], # description: "Allow/disallow registrations via the main site page.", # opts: [], # default: true # }) # add_site_config_type(%{ # key: "general.Text test", # section: "General", # type: "string", # permissions: ["admin.dev.developer"], # description: "Allow/disallow registrations via the main site page.", # opts: [], # default: "abc" # }) # add_site_config_type(%{ # key: "general.Drop test", # section: "General", # type: "select", # permissions: ["admin.dev.developer"], # description: "Allow/disallow registrations via the main site page.", # opts: [choices: ["aaa", "bbb", "ccc"]], # default: "aaa" # }) add_permission_set("admin", "debug", ~w(debug)) add_permission_set("admin", "dev", ~w(developer structure)) add_permission_set("admin", "admin", ~w(limited full)) add_permission_set("admin", "report", ~w(show update delete report)) add_permission_set("admin", "user", ~w(show create update delete report)) add_permission_set("admin", "group", ~w(show create update delete report config)) end end
27.594872
108
0.568482
f769ca261ffbfcef2c3e22f81c7731abf3cbe91a
16,557
ex
Elixir
Microsoft.Azure.Management.EventHub/lib/microsoft/azure/management/event_hub/api/disaster_recovery_configs.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
4
2018-09-29T03:43:15.000Z
2021-04-01T18:30:46.000Z
Microsoft.Azure.Management.EventHub/lib/microsoft/azure/management/event_hub/api/disaster_recovery_configs.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
Microsoft.Azure.Management.EventHub/lib/microsoft/azure/management/event_hub/api/disaster_recovery_configs.ex
chgeuer/ex_microsoft_azure_management
99cd9f7f2ff1fdbe69ca5bac55b6e2af91ba3603
[ "Apache-2.0" ]
null
null
null
# 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 Microsoft.Azure.Management.EventHub.Api.DisasterRecoveryConfigs do @moduledoc """ API calls for all endpoints tagged `DisasterRecoveryConfigs`. """ alias Microsoft.Azure.Management.EventHub.Connection import Microsoft.Azure.Management.EventHub.RequestBuilder @doc """ This operation disables the Disaster Recovery and stops replicating changes from primary to secondary namespaces ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_break_pairing(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def disaster_recovery_configs_break_pairing(connection, resource_group_name, namespace_name, alias, api_version, subscription_id, _opts \\ []) do %{} |> method(:post) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}/breakPairing") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Check the give Namespace name availability. ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - parameters (CheckNameAvailabilityParameter): Parameters to check availability of the given Alias name - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.CheckNameAvailabilityResult{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_check_name_availability(Tesla.Env.client, String.t, String.t, String.t, String.t, Microsoft.Azure.Management.EventHub.Model.CheckNameAvailabilityParameter.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.CheckNameAvailabilityResult.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_check_name_availability(connection, api_version, subscription_id, resource_group_name, namespace_name, parameters, _opts \\ []) do %{} |> method(:post) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/CheckNameAvailability") |> add_param(:query, :"api-version", api_version) |> add_param(:body, :body, parameters) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.CheckNameAvailabilityResult{}) end @doc """ Creates or updates a new Alias(Disaster Recovery configuration) ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - parameters (ArmDisasterRecovery): Parameters required to create an Alias(Disaster Recovery configuration) - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_create_or_update(Tesla.Env.client, String.t, String.t, String.t, Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery.t, String.t, String.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_create_or_update(connection, resource_group_name, namespace_name, alias, parameters, api_version, subscription_id, _opts \\ []) do %{} |> method(:put) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}") |> add_param(:body, :body, parameters) |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery{}) end @doc """ Deletes an Alias(Disaster Recovery configuration) ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_delete(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def disaster_recovery_configs_delete(connection, resource_group_name, namespace_name, alias, api_version, subscription_id, _opts \\ []) do %{} |> method(:delete) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ envokes GEO DR failover and reconfigure the alias to point to the secondary namespace ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_fail_over(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} def disaster_recovery_configs_fail_over(connection, resource_group_name, namespace_name, alias, api_version, subscription_id, _opts \\ []) do %{} |> method(:post) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}/failover") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(false) end @doc """ Retrieves Alias(Disaster Recovery configuration) for primary or secondary namespace ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_get(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_get(connection, resource_group_name, namespace_name, alias, api_version, subscription_id, _opts \\ []) do %{} |> method(:get) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecovery{}) end @doc """ Gets an AuthorizationRule for a Namespace by rule name. ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - authorization_rule_name (String.t): The authorization rule name. - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.AuthorizationRule{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_get_authorization_rule(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.AuthorizationRule.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_get_authorization_rule(connection, resource_group_name, namespace_name, alias, authorization_rule_name, api_version, subscription_id, _opts \\ []) do %{} |> method(:get) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}/AuthorizationRules/#{authorization_rule_name}") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.AuthorizationRule{}) end @doc """ Gets all Alias(Disaster Recovery configurations) ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecoveryListResult{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_list(Tesla.Env.client, String.t, String.t, String.t, String.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecoveryListResult.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_list(connection, resource_group_name, namespace_name, api_version, subscription_id, _opts \\ []) do %{} |> method(:get) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.ArmDisasterRecoveryListResult{}) end @doc """ Gets a list of authorization rules for a Namespace. ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.AuthorizationRuleListResult{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_list_authorization_rules(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.AuthorizationRuleListResult.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_list_authorization_rules(connection, resource_group_name, namespace_name, alias, api_version, subscription_id, _opts \\ []) do %{} |> method(:get) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}/AuthorizationRules") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.AuthorizationRuleListResult{}) end @doc """ Gets the primary and secondary connection strings for the Namespace. ## Parameters - connection (Microsoft.Azure.Management.EventHub.Connection): Connection to server - resource_group_name (String.t): Name of the resource group within the azure subscription. - namespace_name (String.t): The Namespace name - alias (String.t): The Disaster Recovery configuration name - authorization_rule_name (String.t): The authorization rule name. - api_version (String.t): Client API Version. - subscription_id (String.t): Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. - opts (KeywordList): [optional] Optional parameters ## Returns {:ok, %Microsoft.Azure.Management.EventHub.Model.AccessKeys{}} on success {:error, info} on failure """ @spec disaster_recovery_configs_list_keys(Tesla.Env.client, String.t, String.t, String.t, String.t, String.t, String.t, keyword()) :: {:ok, Microsoft.Azure.Management.EventHub.Model.AccessKeys.t} | {:error, Tesla.Env.t} def disaster_recovery_configs_list_keys(connection, resource_group_name, namespace_name, alias, authorization_rule_name, api_version, subscription_id, _opts \\ []) do %{} |> method(:post) |> url("/subscriptions/#{subscription_id}/resourceGroups/#{resource_group_name}/providers/Microsoft.EventHub/namespaces/#{namespace_name}/disasterRecoveryConfigs/#{alias}/AuthorizationRules/#{authorization_rule_name}/listKeys") |> add_param(:query, :"api-version", api_version) |> Enum.into([]) |> (&Connection.request(connection, &1)).() |> decode(%Microsoft.Azure.Management.EventHub.Model.AccessKeys{}) end end
53.756494
308
0.749834
f769fcb4ca4b2d1174afe9811af5480cc6051777
1,861
ex
Elixir
lib/exred_node_gpio_out.ex
exredorg/exred_node_gpio_out
59dfcd59b2a1c8c28904eb0418e8ed203dd2ec02
[ "MIT" ]
null
null
null
lib/exred_node_gpio_out.ex
exredorg/exred_node_gpio_out
59dfcd59b2a1c8c28904eb0418e8ed203dd2ec02
[ "MIT" ]
null
null
null
lib/exred_node_gpio_out.ex
exredorg/exred_node_gpio_out
59dfcd59b2a1c8c28904eb0418e8ed203dd2ec02
[ "MIT" ]
null
null
null
defmodule Exred.Node.GPIOOut do @moduledoc """ Sends data to a GPIO pin. Uses [Elixir ALE](https://github.com/fhunleth/elixir_ale) to interface with GPIO. ##Incoming Message format msg = %{payload :: 0 | 1 | true | false} ##Outgoing Message format msg = %{ payload :: :ok | :error, error :: term } """ @name "GPIO Out" @category "output" @info @moduledoc @config %{ name: %{ info: "Visible node name", value: @name, type: "string", attrs: %{max: 20} }, pin_number: %{ info: "GPIO pin number the node will write to", value: 0, type: "number", attrs: %{min: 0} } } @ui_attributes %{ fire_button: false, right_icon: "send", config_order: [:name, :pin_number] } use Exred.NodePrototype alias ElixirALE.GPIO require Logger @impl true def node_init(state) do GenServer.cast(self(), :do_init) Map.put(state, :init, :starting) end @impl true def handle_cast(:do_init, %{init: :starting} = state) do # start GPIO process {:ok, pid} = GPIO.start_link(state.config.pin_number.value, :output) new_state = state |> Map.put(:pid, pid) |> Map.put(:init, :done) {:noreply, new_state} end @impl true def handle_msg(msg, %{init: :starting} = state) do Logger.warn( "UNHANDLED MSG DURING INIT node: #{state.node_id} #{get_in(state.config, [:name, :value])} msg: #{ inspect(msg) }" ) {nil, state} end def handle_msg(msg, %{init: :done} = state) do msg_out = case GPIO.write(state.pid, msg.payload) do :ok -> %{msg | payload: :ok} {:error, error} -> # put the error info in the outgoing msg %{msg | payload: :error} |> Map.put(:error, error) end {msg_out, state} end end
20.450549
104
0.572273
f76a361b1620c6644c62093599b1d864c937a9cb
2,593
ex
Elixir
clients/content/lib/google_api/content/v2/model/orders_custom_batch_response_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_custom_batch_response_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
clients/content/lib/google_api/content/v2/model/orders_custom_batch_response_entry.ex
medikent/elixir-google-api
98a83d4f7bfaeac15b67b04548711bb7e49f9490
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.Content.V2.Model.OrdersCustomBatchResponseEntry do @moduledoc """ ## Attributes * `batchId` (*type:* `integer()`, *default:* `nil`) - The ID of the request entry this entry responds to. * `errors` (*type:* `GoogleApi.Content.V2.Model.Errors.t`, *default:* `nil`) - A list of errors defined if and only if the request failed. * `executionStatus` (*type:* `String.t`, *default:* `nil`) - The status of the execution. Only defined if - the request was successful; and - the method is not get, getByMerchantOrderId, or one of the test methods. Acceptable values are: - "duplicate" - "executed" * `kind` (*type:* `String.t`, *default:* `content#ordersCustomBatchResponseEntry`) - Identifies what kind of resource this is. Value: the fixed string "content#ordersCustomBatchResponseEntry". * `order` (*type:* `GoogleApi.Content.V2.Model.Order.t`, *default:* `nil`) - The retrieved order. Only defined if the method is get and if the request was successful. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :batchId => integer(), :errors => GoogleApi.Content.V2.Model.Errors.t(), :executionStatus => String.t(), :kind => String.t(), :order => GoogleApi.Content.V2.Model.Order.t() } field(:batchId) field(:errors, as: GoogleApi.Content.V2.Model.Errors) field(:executionStatus) field(:kind) field(:order, as: GoogleApi.Content.V2.Model.Order) end defimpl Poison.Decoder, for: GoogleApi.Content.V2.Model.OrdersCustomBatchResponseEntry do def decode(value, options) do GoogleApi.Content.V2.Model.OrdersCustomBatchResponseEntry.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Content.V2.Model.OrdersCustomBatchResponseEntry do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
39.892308
196
0.708446
f76a42da1d329a8a956fff8d8ac4bd6392fb2187
2,143
ex
Elixir
2020/day24/lib/day24.ex
faried/advent
1d3817a3c305963ff22e844630bbafd3af242d3e
[ "MIT" ]
null
null
null
2020/day24/lib/day24.ex
faried/advent
1d3817a3c305963ff22e844630bbafd3af242d3e
[ "MIT" ]
null
null
null
2020/day24/lib/day24.ex
faried/advent
1d3817a3c305963ff22e844630bbafd3af242d3e
[ "MIT" ]
null
null
null
defmodule Day24 do @dirs %{ "w" => {0, -1}, "e" => {0, 1}, "nw" => {0.5, -0.5}, "ne" => {0.5, 0.5}, "se" => {-0.5, 0.5}, "sw" => {-0.5, -0.5} } def readinput() do File.read!("24.input.txt") |> String.split("\n", trim: true) |> Enum.map(fn line -> Regex.scan(~r/(se|ne|sw|nw|w|e)/, line, capture: :all_but_first) |> List.flatten() |> Enum.map(&Map.get(@dirs, &1)) end) end def part1(input \\ readinput()) do flip(input, %{{0, 0} => :white}) |> blacktiles() end def flip([], floor), do: floor def flip([path | paths], floor) do tile = Enum.reduce(path, {0, 0}, fn {ns, ew}, {nsacc, ewacc} -> {nsacc + ns, ewacc + ew} end) case Map.get(floor, tile, :white) do :black -> flip(paths, Map.put(floor, tile, :white)) :white -> flip(paths, Map.put(floor, tile, :black)) end end def blacktiles(floor) do floor |> Map.values() |> Enum.count(&(&1 == :black)) end def part2(input \\ readinput()) do flip(input, %{{0, 0} => :white}) |> dayflip(100) |> blacktiles() end def dayflip(floor, 0), do: floor def dayflip(floor, count) do expand(floor) |> Enum.reduce(%{}, fn {tile, color} = t, newfloor -> blacks = adjtiles(tile) |> Enum.map(&Map.get(floor, &1)) |> Enum.count(&(&1 == :black)) cond do color == :black and (blacks == 0 or blacks > 2) -> Map.put(newfloor, tile, :white) color == :white and blacks == 2 -> Map.put(newfloor, tile, :black) true -> if t in floor, do: Map.put(newfloor, tile, color), else: newfloor end end) |> dayflip(count - 1) end def expand(floor) do floor |> Enum.flat_map(fn {tile, _} -> adjtiles(tile) end) |> MapSet.new() |> Enum.reduce(%{}, fn tile, newfloor -> Map.put(newfloor, tile, Map.get(floor, tile, :white)) end) end def adjtiles({ns, ew}) do [ {ns + 0.5, ew + 0.5}, {ns + 0.5, ew - 0.5}, {ns - 0.5, ew + 0.5}, {ns - 0.5, ew - 0.5}, {ns, ew + 1}, {ns, ew - 1} ] end end
23.043011
97
0.497434
f76a539921654623c2443a6f7fa1e381d9799e72
1,077
exs
Elixir
test/lib/code_corps/emails/project_approval_request_email_test.exs
fikape/code-corps-api
c21674b0b2a19fa26945c94268db8894420ca181
[ "MIT" ]
275
2015-06-23T00:20:51.000Z
2021-08-19T16:17:37.000Z
test/lib/code_corps/emails/project_approval_request_email_test.exs
fikape/code-corps-api
c21674b0b2a19fa26945c94268db8894420ca181
[ "MIT" ]
1,304
2015-06-26T02:11:54.000Z
2019-12-12T21:08:00.000Z
test/lib/code_corps/emails/project_approval_request_email_test.exs
fikape/code-corps-api
c21674b0b2a19fa26945c94268db8894420ca181
[ "MIT" ]
140
2016-01-01T18:19:47.000Z
2020-11-22T06:24:47.000Z
defmodule CodeCorps.Emails.ProjectApprovalRequestEmailTest do use CodeCorps.ModelCase use Bamboo.Test alias CodeCorps.Emails.ProjectApprovalRequestEmail test "request email works" do project = insert(:project) admin1 = insert(:user, admin: true) admin2 = insert(:user, admin: true) email = ProjectApprovalRequestEmail.create(project) assert email.from == "Code Corps<[email protected]>" assert Enum.count(email.to) == 2 assert Enum.member?(email.to, admin1.email) assert Enum.member?(email.to, admin2.email) template_model = email.private.template_model assert template_model == %{ admin_project_show_url: "http://localhost:4200/admin/projects/#{project.id}", project_description: project.description, project_logo_url: "#{Application.get_env(:code_corps, :asset_host)}/icons/project_default_large_.png", project_title: project.title, project_url: "http://localhost:4200/#{project.organization.slug}/#{project.slug}", subject: "#{project.title} is asking to be approved" } end end
35.9
108
0.725162
f76a7fd651486650a2e541ce2c061377bd1da4e7
296
ex
Elixir
aoc2019_elixir/apps/days/lib/supervisor.ex
mjm/advent-of-code-2019
a30599c1cba05d574fb30b6de98acdcec1ddc643
[ "MIT" ]
1
2019-12-09T07:43:02.000Z
2019-12-09T07:43:02.000Z
aoc2019_elixir/apps/days/lib/supervisor.ex
mjm/advent-of-code-2019
a30599c1cba05d574fb30b6de98acdcec1ddc643
[ "MIT" ]
null
null
null
aoc2019_elixir/apps/days/lib/supervisor.ex
mjm/advent-of-code-2019
a30599c1cba05d574fb30b6de98acdcec1ddc643
[ "MIT" ]
null
null
null
defmodule Days.Supervisor do @moduledoc false use Supervisor def start_link(opts) do Supervisor.start_link(__MODULE__, :ok, opts) end @impl true def init(:ok) do children = [ {Day01, name: Day01} ] Supervisor.init(children, strategy: :one_for_one) end end
15.578947
53
0.668919
f76ad92add25b64b838615f836123c26a9c09c1f
1,344
exs
Elixir
elixir_spec/mix.exs
bit4bit/phoenixchannels.cr
ef0956ba233b3a2e6ea0c4ba0f1806dc77959df3
[ "MIT" ]
null
null
null
elixir_spec/mix.exs
bit4bit/phoenixchannels.cr
ef0956ba233b3a2e6ea0c4ba0f1806dc77959df3
[ "MIT" ]
null
null
null
elixir_spec/mix.exs
bit4bit/phoenixchannels.cr
ef0956ba233b3a2e6ea0c4ba0f1806dc77959df3
[ "MIT" ]
null
null
null
defmodule ElixirSpec.MixProject do use Mix.Project def project do [ app: :elixir_spec, version: "0.1.0", elixir: "~> 1.12", elixirc_paths: elixirc_paths(Mix.env()), compilers: Mix.compilers(), 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: {ElixirSpec.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, "~> 1.6.6"}, {:swoosh, "~> 1.3"}, {:telemetry_metrics, "~> 0.6"}, {:telemetry_poller, "~> 1.0"}, {:jason, "~> 1.2"}, {:plug_cowboy, "~> 2.5"} ] end # Aliases are shortcuts or tasks specific to the current project. # For example, to install project dependencies and perform other setup tasks, run: # # $ mix setup # # See the documentation for `Mix` for more info on aliases. defp aliases do [ setup: ["deps.get"] ] end end
23.578947
84
0.598958
f76af0a8c79ee0c0063016fab272f5bbd045c820
182
exs
Elixir
elixir/elixir-sips/samples/ecto_test/config/config.exs
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
2
2015-12-09T02:16:51.000Z
2021-07-26T22:53:43.000Z
elixir/elixir-sips/samples/ecto_test/config/config.exs
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
null
null
null
elixir/elixir-sips/samples/ecto_test/config/config.exs
afronski/playground-erlang
6ac4b58b2fd717260c22a33284547d44a9b5038e
[ "MIT" ]
1
2016-05-08T18:40:31.000Z
2016-05-08T18:40:31.000Z
use Mix.Config config :ecto_test, EctoTest.Repo, adapter: Ecto.Adapters.Postgres, database: "ecto_test", username: "postgres", password: "postgres", hostname: "localhost"
20.222222
34
0.725275
f76b14cb2a93602ead592cecdb59d04b05f0ab84
3,198
ex
Elixir
lib/bagg.ex
quantified-self-tools/bagg
46675b4fe3c0c8c74bc6084b6c6fb2483a3a1c87
[ "MIT" ]
1
2020-11-26T17:01:42.000Z
2020-11-26T17:01:42.000Z
lib/bagg.ex
quantified-self-tools/bagg
46675b4fe3c0c8c74bc6084b6c6fb2483a3a1c87
[ "MIT" ]
null
null
null
lib/bagg.ex
quantified-self-tools/bagg
46675b4fe3c0c8c74bc6084b6c6fb2483a3a1c87
[ "MIT" ]
null
null
null
defmodule Bagg do alias Bagg.{Aggday, Datapoint} @valid_aggdays for {name, 1} <- Aggday.__info__(:functions), do: Atom.to_string(name) @type aggregate_opt() :: {:aggday, atom() | String.t()} | {:kyoom, boolean()} | {:odom, boolean()} @type aggregate_error() :: {:invalid_aggday, any()} | :no_datapoints @spec aggregate_goal(map()) :: {:ok, [%Datapoint{}]} | {:error, aggregate_error()} def aggregate_goal(%{ "datapoints" => datapoints, "odom" => odom, "kyoom" => kyoom, "aggday" => aggday }) when is_list(datapoints) do datapoints = datapoints |> Enum.sort_by(fn %{"timestamp" => t, "daystamp" => d} -> {d, t} end) |> Enum.map(&Datapoint.new/1) aggregate(datapoints, odom: odom, kyoom: kyoom, aggday: aggday ) end def aggregate_goal(%{"odom" => _, "kyoom" => _, "aggday" => _}) do {:error, :no_datapoints} end @spec aggregate([%Datapoint{}], [aggregate_opt()]) :: {:ok, [%Datapoint{}]} | {:error, aggregate_error()} def aggregate(data, opts \\ []) do kyoom = Keyword.get(opts, :kyoom, false) odom = Keyword.get(opts, :odom, false) aggday = to_string(Keyword.get(opts, :aggday, if(kyoom, do: :sum, else: :last))) cond do Enum.empty?(data) -> {:error, :no_datapoints} aggday not in @valid_aggdays -> {:error, {:invalid_aggday, aggday}} true -> aggday = String.to_existing_atom(aggday) data = if odom, do: odomify(data), else: data data = data |> Enum.group_by(& &1.date) |> Enum.map(fn {date, datapoints} -> aggregate_day(date, datapoints, aggday) end) |> Enum.sort(&compare_dates/2) data = if kyoom, do: kyoomify(data), else: data {:ok, data} end end defp aggregate_day(date, datapoints, aggday) do values = Enum.map(datapoints, & &1.value) aggregated = apply(Aggday, aggday, [values]) hashtags = Enum.reduce(datapoints, MapSet.new(), fn %{hashtags: hashtags}, acc -> MapSet.union(hashtags, acc) end) %Datapoint{ date: date, value: aggregated, hashtags: hashtags } end defp compare_dates(%Datapoint{date: first}, %Datapoint{date: second}) do Date.compare(first, second) == :lt end defp odomify([first | rest]) do %{out: out} = Enum.reduce(rest, %{out: [first], prev: first, curradd: 0}, fn datapoint, %{out: out, prev: prev, curradd: curradd} -> curradd = if datapoint.value == 0, do: curradd + prev.value, else: curradd new_datapoint = %Datapoint{datapoint | value: datapoint.value + curradd} %{curradd: curradd, prev: datapoint, out: [new_datapoint | out]} end) Enum.reverse(out) end defp kyoomify(data) do %{out: out} = Enum.reduce(data, %{pre: 0, out: []}, fn datapoint, %{pre: pre, out: out} -> datapoint = %Datapoint{datapoint | value: datapoint.value + pre} %{pre: datapoint.value, out: [datapoint | out]} end) Enum.reverse(out) end end
26.87395
87
0.56723
f76b18f5b4f9eb3eb889cc0eb430a1632f84496a
934
ex
Elixir
debian/postrm.ex
mikeyb/GameCredits
4c1844a3ffecfbd222ee68cbac1f1fc7ec2072e5
[ "MIT", "Unlicense" ]
12
2016-09-02T22:48:17.000Z
2022-01-07T03:00:20.000Z
debian/postrm.ex
mikeyb/GameCredits
4c1844a3ffecfbd222ee68cbac1f1fc7ec2072e5
[ "MIT", "Unlicense" ]
1
2018-04-04T04:38:58.000Z
2021-04-13T02:39:22.000Z
debian/postrm.ex
mikeyb/GameCredits
4c1844a3ffecfbd222ee68cbac1f1fc7ec2072e5
[ "MIT", "Unlicense" ]
5
2016-08-07T08:26:50.000Z
2020-10-11T20:45:44.000Z
#!/bin/sh # postrm script for gamecredits # # see: dh_installdeb(1) set -e # summary of how this script can be called: # * <postrm> `remove' # * <postrm> `purge' # * <old-postrm> `upgrade' <new-version> # * <new-postrm> `failed-upgrade' <old-version> # * <new-postrm> `abort-install' # * <new-postrm> `abort-install' <old-version> # * <new-postrm> `abort-upgrade' <old-version> # * <disappearer's-postrm> `disappear' <overwriter> # <overwriter-version> # for details, see http://www.debian.org/doc/debian-policy/ or # the debian-policy package case "$1" in purge|remove|upgrade|failed-upgrade|abort-install|abort-upgrade|disappear) ;; *) echo "postrm called with unknown argument \`$1'" >&2 exit 1 ;; esac # dh_installdeb will replace this with shell code automatically # generated by other debhelper scripts. #DEBHELPER# exit 0
24.578947
78
0.62955
f76b1f0bd6fc0f69a237b024a3f6c610c9ef79b6
1,447
ex
Elixir
clients/service_control/lib/google_api/service_control/v1/model/quota_properties.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/service_control/lib/google_api/service_control/v1/model/quota_properties.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/service_control/lib/google_api/service_control/v1/model/quota_properties.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.ServiceControl.V1.Model.QuotaProperties do @moduledoc """ Represents the properties needed for quota operations. ## Attributes * `quotaMode` (*type:* `String.t`, *default:* `nil`) - Quota mode for this operation. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :quotaMode => String.t() | nil } field(:quotaMode) end defimpl Poison.Decoder, for: GoogleApi.ServiceControl.V1.Model.QuotaProperties do def decode(value, options) do GoogleApi.ServiceControl.V1.Model.QuotaProperties.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.ServiceControl.V1.Model.QuotaProperties do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
30.787234
89
0.741534
f76b4e720c6b17cf91b5ee6504c2906733e503db
18,286
exs
Elixir
test/livebook/session_test.exs
danhuynhdev/livebook
d20d4f6bf123d58e4666c064027b55e3b300702f
[ "Apache-2.0" ]
null
null
null
test/livebook/session_test.exs
danhuynhdev/livebook
d20d4f6bf123d58e4666c064027b55e3b300702f
[ "Apache-2.0" ]
null
null
null
test/livebook/session_test.exs
danhuynhdev/livebook
d20d4f6bf123d58e4666c064027b55e3b300702f
[ "Apache-2.0" ]
null
null
null
defmodule Livebook.SessionTest do use ExUnit.Case, async: true alias Livebook.{Session, Delta, Runtime, Utils, Notebook} # Note: queueing evaluation in most of the tests below # requires the runtime to synchronously start first, # so we use a longer timeout just to make sure the tests # pass reliably @evaluation_wait_timeout 3_000 setup do session_id = start_session() %{session_id: session_id} end describe "insert_section/2" do test "sends an insert opreation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() Session.insert_section(session_id, 0) assert_receive {:operation, {:insert_section, ^pid, 0, _id}} end end describe "insert_cell/4" do test "sends an insert opreation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() Session.insert_section(session_id, 0) assert_receive {:operation, {:insert_section, ^pid, 0, section_id}} Session.insert_cell(session_id, section_id, 0, :elixir) assert_receive {:operation, {:insert_cell, ^pid, ^section_id, 0, :elixir, _id}} end end describe "delete_section/3" do test "sends a delete opreation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {section_id, _cell_id} = insert_section_and_cell(session_id) Session.delete_section(session_id, section_id, false) assert_receive {:operation, {:delete_section, ^pid, ^section_id, false}} end end describe "delete_cell/2" do test "sends a delete opreation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) Session.delete_cell(session_id, cell_id) assert_receive {:operation, {:delete_cell, ^pid, ^cell_id}} end end describe "restore_cell/2" do test "sends a restore opreation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) Session.delete_cell(session_id, cell_id) Session.restore_cell(session_id, cell_id) assert_receive {:operation, {:restore_cell, ^pid, ^cell_id}} end end describe "queue_cell_evaluation/2" do test "sends a queue evaluation operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) Session.queue_cell_evaluation(session_id, cell_id) assert_receive {:operation, {:queue_cell_evaluation, ^pid, ^cell_id}}, @evaluation_wait_timeout end test "triggers evaluation and sends update operation once it finishes", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") {_section_id, cell_id} = insert_section_and_cell(session_id) Session.queue_cell_evaluation(session_id, cell_id) assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, _, %{evaluation_time_ms: _time_ms}}}, @evaluation_wait_timeout end end describe "cancel_cell_evaluation/2" do test "sends a cancel evaluation operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) Session.queue_cell_evaluation(session_id, cell_id) Session.cancel_cell_evaluation(session_id, cell_id) assert_receive {:operation, {:cancel_cell_evaluation, ^pid, ^cell_id}}, @evaluation_wait_timeout end end describe "set_notebook_name/2" do test "sends a notebook name update operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() Session.set_notebook_name(session_id, "Cat's guide to life") assert_receive {:operation, {:set_notebook_name, ^pid, "Cat's guide to life"}} end end describe "set_section_name/3" do test "sends a section name update operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {section_id, _cell_id} = insert_section_and_cell(session_id) Session.set_section_name(session_id, section_id, "Chapter 1") assert_receive {:operation, {:set_section_name, ^pid, ^section_id, "Chapter 1"}} end end describe "apply_cell_delta/4" do test "sends a cell delta operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) delta = Delta.new() |> Delta.insert("cats") revision = 1 Session.apply_cell_delta(session_id, cell_id, delta, revision) assert_receive {:operation, {:apply_cell_delta, ^pid, ^cell_id, ^delta, ^revision}} end end describe "report_cell_revision/3" do test "sends a revision report operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) revision = 1 Session.report_cell_revision(session_id, cell_id, revision) assert_receive {:operation, {:report_cell_revision, ^pid, ^cell_id, ^revision}} end end describe "set_cell_attributes/3" do test "sends an attributes update operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {_section_id, cell_id} = insert_section_and_cell(session_id) attrs = %{metadata: %{"disable_formatting" => true}} Session.set_cell_attributes(session_id, cell_id, attrs) assert_receive {:operation, {:set_cell_attributes, ^pid, ^cell_id, ^attrs}} end end describe "connect_runtime/2" do test "sends a runtime update operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {:ok, runtime} = Livebook.Runtime.Embedded.init() Session.connect_runtime(session_id, runtime) assert_receive {:operation, {:set_runtime, ^pid, ^runtime}} end end describe "disconnect_runtime/1" do test "sends a runtime update operation to subscribers", %{session_id: session_id} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() {:ok, runtime} = Livebook.Runtime.Embedded.init() Session.connect_runtime(session_id, runtime) Session.disconnect_runtime(session_id) assert_receive {:operation, {:set_runtime, ^pid, nil}} end end describe "set_path/1" do @tag :tmp_dir test "sends a path update operation to subscribers", %{session_id: session_id, tmp_dir: tmp_dir} do Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") pid = self() path = Path.join(tmp_dir, "notebook.livemd") Session.set_path(session_id, path) assert_receive {:operation, {:set_path, ^pid, ^path}} end @tag :tmp_dir test "broadcasts an error if the path is already in use", %{session_id: session_id, tmp_dir: tmp_dir} do path = Path.join(tmp_dir, "notebook.livemd") start_session(path: path) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") Session.set_path(session_id, path) assert_receive {:error, "failed to set new path because it is already in use"} end @tag :tmp_dir test "moves images to the new directory", %{session_id: session_id, tmp_dir: tmp_dir} do %{images_dir: images_dir} = Session.get_summary(session_id) File.mkdir_p!(images_dir) images_dir |> Path.join("test.jpg") |> File.touch!() path = Path.join(tmp_dir, "notebook.livemd") Session.set_path(session_id, path) # Wait for the session to deal with the files Process.sleep(50) assert File.exists?(Path.join([tmp_dir, "images", "test.jpg"])) refute File.exists?(images_dir) end @tag :tmp_dir test "does not remove images from the previous dir if not temporary", %{session_id: session_id, tmp_dir: tmp_dir} do path = Path.join(tmp_dir, "notebook.livemd") Session.set_path(session_id, path) %{images_dir: images_dir} = Session.get_summary(session_id) File.mkdir_p!(images_dir) images_dir |> Path.join("test.jpg") |> File.touch!() Session.set_path(session_id, nil) # Wait for the session to deal with the files Process.sleep(50) assert File.exists?(Path.join(images_dir, "test.jpg")) %{images_dir: new_images_dir} = Session.get_summary(session_id) assert File.exists?(Path.join(new_images_dir, "test.jpg")) end end describe "save/1" do @tag :tmp_dir test "persists the notebook to the associated file and notifies subscribers", %{session_id: session_id, tmp_dir: tmp_dir} do path = Path.join(tmp_dir, "notebook.livemd") Session.set_path(session_id, path) # Perform a change, so the notebook is dirty Session.set_notebook_name(session_id, "My notebook") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") refute File.exists?(path) Session.save(session_id) assert_receive {:operation, {:mark_as_not_dirty, _}} assert File.exists?(path) assert File.read!(path) =~ "My notebook" end @tag :tmp_dir test "creates nonexistent directories", %{session_id: session_id, tmp_dir: tmp_dir} do path = Path.join(tmp_dir, "nonexistent/dir/notebook.livemd") Session.set_path(session_id, path) # Perform a change, so the notebook is dirty Session.set_notebook_name(session_id, "My notebook") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") refute File.exists?(path) Session.save(session_id) assert_receive {:operation, {:mark_as_not_dirty, _}} assert File.exists?(path) assert File.read!(path) =~ "My notebook" end end describe "close/1" do @tag :tmp_dir test "saves the notebook and notifies subscribers once the session is closed", %{session_id: session_id, tmp_dir: tmp_dir} do path = Path.join(tmp_dir, "notebook.livemd") Session.set_path(session_id, path) # Perform a change, so the notebook is dirty Session.set_notebook_name(session_id, "My notebook") Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") refute File.exists?(path) Process.flag(:trap_exit, true) Session.close(session_id) assert_receive :session_closed assert File.exists?(path) assert File.read!(path) =~ "My notebook" end test "clears session temporary directory", %{session_id: session_id} do %{images_dir: images_dir} = Session.get_summary(session_id) File.mkdir_p!(images_dir) assert File.exists?(images_dir) Process.flag(:trap_exit, true) Session.close(session_id) # Wait for the session to deal with the files Process.sleep(50) refute File.exists?(images_dir) end end describe "start_link/1" do @tag :tmp_dir test "fails if the given path is already in use", %{tmp_dir: tmp_dir} do path = Path.join(tmp_dir, "notebook.livemd") start_session(path: path) assert {:error, "the given path is already in use"} == Session.start_link(id: Utils.random_id(), path: path) end @tag :tmp_dir test "copies images when :copy_images_from option is specified", %{tmp_dir: tmp_dir} do tmp_dir |> Path.join("image.jpg") |> File.touch!() session_id = start_session(copy_images_from: tmp_dir) %{images_dir: images_dir} = Session.get_summary(session_id) assert File.exists?(Path.join(images_dir, "image.jpg")) end test "saves images when :images option is specified" do images = %{"image.jpg" => "binary content"} session_id = start_session(images: images) %{images_dir: images_dir} = Session.get_summary(session_id) assert Path.join(images_dir, "image.jpg") |> File.read!() == "binary content" end end # For most tests we use the lightweight embedded runtime, # so that they are cheap to run. Here go several integration # tests that actually start a Elixir standalone runtime (default in production) # to verify session integrates well with it properly. test "starts a standalone runtime upon first evaluation if there was none set explicitly" do session_id = Utils.random_id() {:ok, _} = Session.start_link(id: session_id) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") {_section_id, cell_id} = insert_section_and_cell(session_id) Session.queue_cell_evaluation(session_id, cell_id) # Give it a bit more time as this involves starting a system process. assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, _, %{evaluation_time_ms: _time_ms}}}, @evaluation_wait_timeout end test "if the runtime node goes down, notifies the subscribers" do session_id = Utils.random_id() {:ok, _} = Session.start_link(id: session_id) {:ok, runtime} = Runtime.ElixirStandalone.init() Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") # Wait for the runtime to be set Session.connect_runtime(session_id, runtime) assert_receive {:operation, {:set_runtime, _, ^runtime}} # Terminate the other node, the session should detect that Node.spawn(runtime.node, System, :halt, []) assert_receive {:operation, {:set_runtime, _, nil}} assert_receive {:info, "runtime node terminated unexpectedly"} end test "on user change sends an update operation subscribers", %{session_id: session_id} do user = Livebook.Users.User.new() Session.register_client(session_id, self(), user) Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") updated_user = %{user | name: "Jake Peralta"} Livebook.Users.broadcast_change(updated_user) assert_receive {:operation, {:update_user, _pid, ^updated_user}} end # Integration tests concerning input communication # between runtime and session describe "user input" do test "replies to runtime input request" do input_cell = %{Notebook.Cell.new(:input) | name: "name", value: "Jake Peralta"} elixir_cell = %{ Notebook.Cell.new(:elixir) | source: """ IO.gets("name: ") """ } notebook = %{ Notebook.new() | sections: [ %{Notebook.Section.new() | cells: [input_cell, elixir_cell]} ] } session_id = start_session(notebook: notebook) cell_id = elixir_cell.id Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") Session.queue_cell_evaluation(session_id, cell_id) assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, {:text, text_output}, %{evaluation_time_ms: _time_ms}}}, @evaluation_wait_timeout assert text_output =~ "Jake Peralta" end test "replies with error when no matching input is found" do elixir_cell = %{ Notebook.Cell.new(:elixir) | source: """ IO.gets("name: ") """ } notebook = %{ Notebook.new() | sections: [ %{Notebook.Section.new() | cells: [elixir_cell]} ] } session_id = start_session(notebook: notebook) cell_id = elixir_cell.id Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") Session.queue_cell_evaluation(session_id, cell_id) assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, {:text, text_output}, %{evaluation_time_ms: _time_ms}}}, @evaluation_wait_timeout assert text_output =~ "no matching Livebook input found" end test "replies with error when the matching input is invalid" do input_cell = %{Notebook.Cell.new(:input) | type: :url, name: "url", value: "invalid"} elixir_cell = %{ Notebook.Cell.new(:elixir) | source: """ IO.gets("name: ") """ } notebook = %{ Notebook.new() | sections: [ %{Notebook.Section.new() | cells: [input_cell, elixir_cell]} ] } session_id = start_session(notebook: notebook) cell_id = elixir_cell.id Phoenix.PubSub.subscribe(Livebook.PubSub, "sessions:#{session_id}") Session.queue_cell_evaluation(session_id, cell_id) assert_receive {:operation, {:add_cell_evaluation_response, _, ^cell_id, {:text, text_output}, %{evaluation_time_ms: _time_ms}}}, @evaluation_wait_timeout assert text_output =~ "no matching Livebook input found" end end defp start_session(opts \\ []) do session_id = Utils.random_id() {:ok, _} = Session.start_link(Keyword.merge(opts, id: session_id)) session_id end defp insert_section_and_cell(session_id) do Session.insert_section(session_id, 0) assert_receive {:operation, {:insert_section, _, 0, section_id}} Session.insert_cell(session_id, section_id, 0, :elixir) assert_receive {:operation, {:insert_cell, _, ^section_id, 0, :elixir, cell_id}} {section_id, cell_id} end end
33.675875
94
0.670622
f76b7a6f0c25541f97bbe48dcdad638d59c8ed9b
1,194
ex
Elixir
lib/majudge/application.ex
coltonw/majudge
4f81a66abe6a2e82f42131982e7a9b26951b9124
[ "MIT" ]
null
null
null
lib/majudge/application.ex
coltonw/majudge
4f81a66abe6a2e82f42131982e7a9b26951b9124
[ "MIT" ]
1
2021-05-10T04:23:56.000Z
2021-05-10T04:23:56.000Z
lib/majudge/application.ex
coltonw/majudge
4f81a66abe6a2e82f42131982e7a9b26951b9124
[ "MIT" ]
null
null
null
defmodule Majudge.Application do # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications @moduledoc false use Application def start(_type, _args) do # List all child processes to be supervised children = [ # Start the Ecto repository # Majudge.Repo, # DynamicSupervisor which runs AWS related tasks {DynamicSupervisor, name: Majudge.SleepRDSSupervisor, strategy: :one_for_one}, # KeepAlive task which keeps RDS alive when needed then puts it to sleep when not Majudge.SleepRDS.KeepAlive, # Start the endpoint when the application starts MajudgeWeb.Endpoint # Starts a worker by calling: Majudge.Worker.start_link(arg) # {Majudge.Worker, arg}, ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Majudge.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do MajudgeWeb.Endpoint.config_change(changed, removed) :ok end end
33.166667
87
0.71943
f76bb578dc8f3640fd45e68a57561c8a21a1af1b
959
ex
Elixir
lib/headers.ex
SkyllaTech/set_locale
68d709fb4d7a623d76bfbe9a97926da3d6226174
[ "WTFPL" ]
64
2016-11-03T12:56:08.000Z
2021-12-05T07:22:20.000Z
lib/headers.ex
SkyllaTech/set_locale
68d709fb4d7a623d76bfbe9a97926da3d6226174
[ "WTFPL" ]
28
2016-11-25T11:52:38.000Z
2021-06-10T18:37:46.000Z
lib/headers.ex
SkyllaTech/set_locale
68d709fb4d7a623d76bfbe9a97926da3d6226174
[ "WTFPL" ]
33
2016-11-25T11:06:27.000Z
2021-06-09T21:49:35.000Z
defmodule SetLocale.Headers do def extract_accept_language(conn) do case Plug.Conn.get_req_header(conn, "accept-language") do [value | _] -> value |> String.split(",") |> Enum.map(&parse_language_option/1) |> Enum.sort(&(&1.quality > &2.quality)) |> Enum.map(& &1.tag) |> Enum.reject(&is_nil/1) |> ensure_language_fallbacks() _ -> [] end end defp parse_language_option(string) do captures = Regex.named_captures(~r/^\s?(?<tag>[\w\-]+)(?:;q=(?<quality>[\d\.]+))?$/i, string) quality = case Float.parse(captures["quality"] || "1.0") do {val, _} -> val _ -> 1.0 end %{tag: captures["tag"], quality: quality} end defp ensure_language_fallbacks(tags) do Enum.flat_map(tags, fn tag -> [language | _] = String.split(tag, "-") if Enum.member?(tags, language), do: [tag], else: [tag, language] end) end end
25.918919
97
0.561001
f76bbbd6d8d091170b63e734c3d01fbc8a19256b
342
ex
Elixir
lib/tube_streamer_web/plug/locale.ex
surik/tube_streamer
c353e8512ec6b7521c18e8bdad927d8abad0d346
[ "MIT" ]
1
2018-02-06T17:28:51.000Z
2018-02-06T17:28:51.000Z
lib/tube_streamer_web/plug/locale.ex
surik/tube_streamer
c353e8512ec6b7521c18e8bdad927d8abad0d346
[ "MIT" ]
null
null
null
lib/tube_streamer_web/plug/locale.ex
surik/tube_streamer
c353e8512ec6b7521c18e8bdad927d8abad0d346
[ "MIT" ]
null
null
null
defmodule TubeStreamerWeb.Plug.Locale do import Plug.Conn def init(_opts), do: nil def call(conn, _opts) do case conn.params["locale"] || get_session(conn, :locale) do nil -> conn locale -> Gettext.put_locale(TubeStreamerWeb.Gettext, locale) conn |> put_session(:locale, locale) end end end
22.8
63
0.649123
f76bbc7e76e75c9ead6c5b505234b50bbc9fac84
778
ex
Elixir
lib/phoenix/live_dashboard/components/card_usage_component.ex
PaulOstazeski/phoenix_live_dashboard
c68eac2640d6579d16f222fe58c1eb669342a1f2
[ "MIT" ]
2
2020-05-06T14:51:56.000Z
2020-05-06T14:52:21.000Z
deps/phoenix_live_dashboard/lib/phoenix/live_dashboard/components/card_usage_component.ex
rwtrecs/rocketseat-nlw5-inmana
8ce8bc32e0bdd005c423394bb163945747b557e2
[ "MIT" ]
3
2021-06-20T14:51:14.000Z
2021-06-25T00:56:11.000Z
deps/phoenix_live_dashboard/lib/phoenix/live_dashboard/components/card_usage_component.ex
rwtrecs/rocketseat-nlw5-inmana
8ce8bc32e0bdd005c423394bb163945747b557e2
[ "MIT" ]
1
2020-05-16T22:44:14.000Z
2020-05-16T22:44:14.000Z
defmodule Phoenix.LiveDashboard.CardUsageComponent do use Phoenix.LiveDashboard.Web, :live_component def render(assigns) do ~L""" <div class="card progress-section mb-4"> <%= live_component @socket, Phoenix.LiveDashboard.TitleBarComponent, dom_id: "#{@dom_id}-title-bar", class: "card-body", percent: percentage(@usage, @limit), csp_nonces: @csp_nonces do %> <div> <%= render_block @inner_block, [] %> </div> <div> <small class="text-muted pr-2"> <%= @usage %> / <%= @limit %> </small> <strong> <%= used(@usage, @limit) %>% </strong> </div> <% end %> </div> """ end defp used(usage, limit) do trunc(usage / limit * 100) end end
27.785714
193
0.550129
f76bc9091781e26b8514d55564f177b04450b34d
130
exs
Elixir
apps/gullintanni_web/test/gullintanni_web_test.exs
gullintanni/gullintanni
63c58b7ea438a4c6885a13842d8e33d3b1273ced
[ "0BSD" ]
15
2016-08-09T21:27:54.000Z
2020-12-03T11:21:10.000Z
apps/gullintanni_web/test/gullintanni_web_test.exs
gullintanni/gullintanni
63c58b7ea438a4c6885a13842d8e33d3b1273ced
[ "0BSD" ]
15
2016-08-04T21:11:05.000Z
2017-08-02T17:46:17.000Z
apps/gullintanni_web/test/gullintanni_web_test.exs
gullintanni/gullintanni
63c58b7ea438a4c6885a13842d8e33d3b1273ced
[ "0BSD" ]
null
null
null
defmodule GullintanniWebTest do use ExUnit.Case doctest GullintanniWeb test "the truth" do assert 1 + 1 == 2 end end
14.444444
31
0.707692
f76bd9d2d7f67497feca4a8b30f6ac47fcf8acc6
1,604
exs
Elixir
mix.exs
valiot/tycmdex
94caa4f90a1e4f51f1f7e315173b9b3148f3d03b
[ "MIT" ]
null
null
null
mix.exs
valiot/tycmdex
94caa4f90a1e4f51f1f7e315173b9b3148f3d03b
[ "MIT" ]
null
null
null
mix.exs
valiot/tycmdex
94caa4f90a1e4f51f1f7e315173b9b3148f3d03b
[ "MIT" ]
null
null
null
defmodule Tycmdex.MixProject do use Mix.Project def project do [ app: :tycmdex, version: "0.1.0", elixir: "~> 1.9", name: "Tycmdex", description: description(), package: package(), source_url: "https://github.com/valiot/tycmdex", start_permanent: Mix.env() == :prod, compilers: [:cmake] ++ Mix.compilers(), docs: [extras: ["README.md"], main: "readme"], build_embedded: true, deps: deps() ] end # Run "mix help compile.app" to learn about applications. def application do [ extra_applications: [:logger] ] end defp description() do "Elixir wrapper for tycmd (tytools), for programming Teensy boards." end defp package() do [ files: [ "lib", "src/tytools/src/libhs", "src/tytools/src/libty", "src/tytools/src/tycmd", "src/tytools/cmake", "src/tytools/tests", "CMakeLists.txt", "test", "mix.exs", "README.md", "LICENSE" ], maintainers: ["valiot"], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/valiot/abex"} ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:elixir_cmake, github: "valiot/elixir-cmake", branch: "multi-projects"}, #{:elixir_cmake, "~> 0.1.0"}, {:ex_doc, "~> 0.19", only: :dev}, {:jason, "~> 1.1"}, {:muontrap, "~> 0.5.0"} # {:dep_from_hexpm, "~> 0.3.0"}, # {:dep_from_git, git: "https://github.com/elixir-lang/my_dep.git", tag: "0.1.0"} ] end end
24.30303
87
0.543017
f76bea3086535eedc3e2f6e52381ce5ce7227951
5,569
ex
Elixir
lib/mix/lib/mix/local/installer.ex
jovannypcg/elixir
de3f5df7fdcda79e2661f9cee6005707e7e8d030
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/local/installer.ex
jovannypcg/elixir
de3f5df7fdcda79e2661f9cee6005707e7e8d030
[ "Apache-2.0" ]
null
null
null
lib/mix/lib/mix/local/installer.ex
jovannypcg/elixir
de3f5df7fdcda79e2661f9cee6005707e7e8d030
[ "Apache-2.0" ]
null
null
null
defmodule Mix.Local.Installer do @moduledoc """ This module implements pieces of functionality shared by the archive- and escript-related tasks. """ @doc """ Checks that the argument given to install is supported by the respective module. """ @callback check_path_or_url(String.t) :: :ok | {:error, String.t} @doc """ Returns a list of already installed version of the same archive or escript. """ @callback find_previous_versions(String.t, Path.t) :: [Path.t] @doc """ Custom actions to be performed before the actual installation. """ @callback before_install(String.t, Path.t) :: :ok | {:error, String.t} @doc """ Custom actions to be performed after the installation has succeeded. """ @callback after_install(Path.t, [Path.t]) :: term @doc """ Common implementation of installation for archives and escripts. Relies on a few callbacks provided by respective callback modules for customizing certain steps in the installation process. """ @spec install({module, atom}, OptionParser.argv, Keyword.t) :: boolean def install({module, name}, argv, switches) do {opts, args, _} = OptionParser.parse(argv, switches: switches) case args do [src] -> with :ok <- check_argument(src), :ok <- module.check_path_or_url(src) do do_install({module, name}, src, opts) else {:error, message} -> Mix.raise message <> "\n" <> usage(name) end [] -> src = Mix.Local.name_for(name, Mix.Project.config) if File.exists?(src) do do_install({module, name}, src, opts) else Mix.raise "Expected an #{name} to exist in the current directory " <> "or an argument to be given.\n#{usage(name)}" end _ -> Mix.raise "Unexpected arguments.\n#{usage(name)}" end end defp check_argument(arg) do if local_path?(arg) or file_url?(arg) do :ok else {:error, "Expected a local file path or a file URL."} end end defp local_path?(url_or_path) do File.regular?(url_or_path) end defp file_url?(url_or_path) do URI.parse(url_or_path).scheme in ["http", "https"] end defp usage(name), do: "Usage: mix #{name}.install <path or url>" defp do_install({module, name}, src, opts) do src_basename = Path.basename(URI.parse(src).path) dst_file_path = Path.join(Mix.Local.path_for(name), src_basename) dst_dir_path = Path.dirname(dst_file_path) previous_files = module.find_previous_versions(src, dst_file_path) if opts[:force] || should_install?(name, src, previous_files) do case module.before_install(src, dst_file_path) do :ok -> :ok {:error, message} -> Mix.raise message end case Mix.Utils.read_path(src, opts) do {:ok, binary} -> File.mkdir_p!(dst_dir_path) File.write!(dst_file_path, binary) :badpath -> Mix.raise "Expected #{inspect src} to be a URL or a local file path" {:local, message} -> Mix.raise message {kind, message} when kind in [:remote, :checksum] -> Mix.raise """ #{message} Could not fetch #{name} at: #{src} Please download the #{name} above manually to your current directory and run: mix #{name}.install ./#{src_basename} """ end Mix.shell.info [:green, "* creating ", :reset, Path.relative_to_cwd(dst_file_path)] _ = module.after_install(dst_file_path, previous_files) true else false end end defp should_install?(name, src, previous_files) do message = case previous_files do [] -> "Are you sure you want to install #{name} #{inspect src}?" [file] -> "Found existing #{name}: #{file}.\n" <> "Are you sure you want to replace it with #{inspect src}?" files -> "Found existing #{name}s: #{Enum.map_join(files, ", ", &Path.basename/1)}.\n" <> "Are you sure you want to replace them with #{inspect src}?" end Mix.shell.yes?(message) end @doc """ Print a list of items in a uniform way. Used for printing the list of installed archives and escripts. """ @spec print_list(atom, [String.t]) :: :ok def print_list(type, []) do Mix.shell.info "No #{type}s currently installed." end def print_list(type, items) do Enum.each items, fn item -> Mix.shell.info ["* ", item] end item_name = String.capitalize("#{type}") Mix.shell.info "#{item_name}s installed at: #{Mix.Local.path_for(type)}" end @doc """ A common implementation for uninstalling archives and scripts. """ @spec uninstall(atom, OptionParser.argv) :: boolean def uninstall(type, argv) do {_, argv, _} = OptionParser.parse(argv) item_name = "#{type}" item_plural = "#{type}s" root = Mix.Local.path_for(type) if name = List.first(argv) do path = Path.join(root, name) cond do not File.regular?(path) -> Mix.shell.error "Could not find a local #{item_name} named #{inspect name}. "<> "Existing #{item_plural} are:" Mix.Task.run item_name nil should_uninstall?(path, item_name) -> File.rm!(path) path true -> nil end else Mix.raise "No #{item_name} was given to #{item_name}.uninstall" end end defp should_uninstall?(path, item_name) do Mix.shell.yes?("Are you sure you want to uninstall #{item_name} #{path}?") end end
30.102703
94
0.618783
f76c80003b0f6353b9528ba92e9f2ccfcf446b28
2,063
ex
Elixir
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/build_bazel_remote_execution_v2_priority_capabilities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/build_bazel_remote_execution_v2_priority_capabilities.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/remote_build_execution/lib/google_api/remote_build_execution/v2/model/build_bazel_remote_execution_v2_priority_capabilities.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.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilities do @moduledoc """ Allowed values for priority in ResultsCachePolicy and ExecutionPolicy Used for querying both cache and execution valid priority ranges. ## Attributes * `priorities` (*type:* `list(GoogleApi.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilitiesPriorityRange.t)`, *default:* `nil`) - """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :priorities => list( GoogleApi.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilitiesPriorityRange.t() ) | nil } field(:priorities, as: GoogleApi.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilitiesPriorityRange, type: :list ) end defimpl Poison.Decoder, for: GoogleApi.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilities do def decode(value, options) do GoogleApi.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilities.decode( value, options ) end end defimpl Poison.Encoder, for: GoogleApi.RemoteBuildExecution.V2.Model.BuildBazelRemoteExecutionV2PriorityCapabilities do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
34.383333
160
0.759573
f76c89ce3b9457cea9b875029cfcdd1cf99438fe
879
ex
Elixir
lib/annon_api/configuration/schemas/api.ex
gabheadz/annon.api
9921d98e44c8472c133554dd55ea649c0f55726c
[ "MIT" ]
328
2017-05-05T15:19:46.000Z
2022-03-11T10:52:45.000Z
lib/annon_api/configuration/schemas/api.ex
gabheadz/annon.api
9921d98e44c8472c133554dd55ea649c0f55726c
[ "MIT" ]
83
2017-04-30T10:36:15.000Z
2019-10-14T13:14:34.000Z
lib/annon_api/configuration/schemas/api.ex
gabheadz/annon.api
9921d98e44c8472c133554dd55ea649c0f55726c
[ "MIT" ]
29
2017-05-02T14:36:50.000Z
2021-09-03T13:36:17.000Z
defmodule Annon.Configuration.Schemas.API do @moduledoc """ Schema for API's entity. """ use Ecto.Schema @derive {Poison.Encoder, except: [:__meta__, :plugins]} @primary_key {:id, :binary_id, autogenerate: false} schema "apis" do field :name, :string field :description, :string, default: "" field :docs_url, :string, default: "" field :health, :string, default: "operational" field :disclose_status, :boolean, default: false field :matching_priority, :integer, default: 1 embeds_one :request, Request, primary_key: false, on_replace: :update do field :scheme, :string field :host, :string field :port, :integer field :path, :string field :methods, {:array, :string} end has_many :plugins, Annon.Configuration.Schemas.Plugin, on_delete: :delete_all timestamps(type: :utc_datetime) end end
29.3
81
0.678043
f76ca0889f03070b070ca1c8385c8aba9addba62
3,203
ex
Elixir
lib/bonny/config.ex
victoriavilasb/bonny
c5f2b3f69d8f4750d796a619d71692d76445b509
[ "MIT" ]
null
null
null
lib/bonny/config.ex
victoriavilasb/bonny
c5f2b3f69d8f4750d796a619d71692d76445b509
[ "MIT" ]
null
null
null
lib/bonny/config.ex
victoriavilasb/bonny
c5f2b3f69d8f4750d796a619d71692d76445b509
[ "MIT" ]
null
null
null
defmodule Bonny.Config do @moduledoc """ Operator configuration interface """ @doc """ Kubernetes API Group of this operator """ @spec group() :: binary def group do default = "#{project_name()}.example.com" Application.get_env(:bonny, :group, default) end @doc """ The name of the operator. Name must consist of only lowercase letters and hyphens. Defaults to hyphenated mix project app name. E.g.: `:hello_operator` becomes `hello-operator` """ @spec name() :: binary def name() do :bonny |> Application.get_env(:operator_name, project_name()) |> dns_safe_name end @doc """ Kubernetes service account name to run operator as. *Note:* if a kube config file is provided, this service account will still be created and assigned to pods, but the *config file auth will be used* when making requests to the Kube API. Name must consist of only lowercase letters and hyphens. Defaults to hyphenated mix project app name. E.g.: `:hello_operator` becomes `hello-operator` """ @spec service_account() :: binary def service_account() do :bonny |> Application.get_env(:service_account_name, project_name()) |> dns_safe_name end defp project_name() do Mix.Project.config() |> Keyword.fetch!(:app) |> Atom.to_string() |> String.replace("_", "-") end defp dns_safe_name(str) do str |> String.downcase() |> String.replace(~r/[^a-z-]/, "-\\1\\g{1}") end @doc """ Labels to apply to all operator resources. *Note:* These are only applied to the resoures that compose the operator itself, not the resources created by the operator. This can be set in config.exs: ``` config :bonny, labels: %{foo: "bar", quz: "baz"} ``` """ @spec labels() :: map() def labels() do Application.get_env(:bonny, :labels, %{}) end @doc """ List of all controller modules to watch. This *must* be set in config.exs: ``` config :bonny, controllers: [MyController1, MyController2] ``` """ @spec controllers() :: list(atom) def controllers() do Application.get_env(:bonny, :controllers, []) end @doc """ The namespace to watch for `Namespaced` CRDs. Defaults to `default` This can be set via environment variable: ```shell BONNY_POD_NAMESPACE=prod # specific namespace # or BONNY_POD_NAMESPACE=__ALL__ # all namespaces iex -S mix ``` Or via config.exs: ``` config :bonny, namespace: "mynamespace" # specific namespace # or config :bonny; namespace: :all # all namespaces ``` Configuration via environment variable always takes precedence over config.exs. Bonny sets `BONNY_POD_NAMESPACE` on all Kubernetes deployments to the namespace the operator is deployed in. """ @spec namespace() :: binary def namespace() do case System.get_env("BONNY_POD_NAMESPACE") do nil -> Application.get_env(:bonny, :namespace, "default") "__ALL__" -> :all namespace -> namespace end end @doc """ `K8s.Cluster` name used for this operator. Defaults to `:default` """ @spec cluster_name() :: atom def cluster_name() do Application.get_env(:bonny, :cluster_name, :default) end end
24.082707
110
0.668436
f76cbc349a5cdbc25ece9d2c74342702bc514edc
1,118
exs
Elixir
test/concentrate/filter/gtfs/unzip_test.exs
paulswartz/concentrate
a69aa51c16071f2669932005be810da198f622c8
[ "MIT" ]
19
2018-01-22T18:39:20.000Z
2022-02-22T16:15:30.000Z
test/concentrate/filter/gtfs/unzip_test.exs
mbta/concentrate
bae6e05713ed079b7da53867a01dd007861fb656
[ "MIT" ]
216
2018-01-22T14:22:39.000Z
2022-03-31T10:30:31.000Z
test/concentrate/filter/gtfs/unzip_test.exs
paulswartz/concentrate
a69aa51c16071f2669932005be810da198f622c8
[ "MIT" ]
5
2018-01-22T14:18:15.000Z
2021-04-26T18:34:19.000Z
defmodule Concentrate.Filter.GTFS.UnzipTest do @moduledoc false use ExUnit.Case, async: true import Concentrate.Filter.GTFS.Unzip describe "parse/1" do test "returns the relevants bodies" do bodies = for name <- ~w(trips.txt stop_times.txt other) do {String.to_charlist(name), "#{name} body"} end # all the zip module arguments are charlists, hence the single quotes {:ok, {_, zip_file}} = :zip.create('gtfs.zip', bodies, [:memory]) assert is_binary(zip_file) parsed = parse(zip_file, []) assert find_body(parsed, "trips.txt") == "trips.txt body" assert find_body(parsed, "stop_times.txt") == "stop_times.txt body" assert find_body(parsed, "other") == nil end end describe "strip_bom/1" do test "does nothing when there's no BOM" do assert strip_bom("1234") == "1234" end test "strips a leading BOM" do assert strip_bom("\uFEFF1234") == "1234" end end defp find_body(files, file_name) do Enum.find_value(files, fn {^file_name, value} -> value _ -> nil end) end end
27.95
75
0.635957
f76cbfcd0356259d148a68bd3a0abfe2ed314271
2,211
ex
Elixir
clients/you_tube/lib/google_api/you_tube/v3/model/live_stream_snippet.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_stream_snippet.ex
kolorahl/elixir-google-api
46bec1e092eb84c6a79d06c72016cb1a13777fa6
[ "Apache-2.0" ]
null
null
null
clients/you_tube/lib/google_api/you_tube/v3/model/live_stream_snippet.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.YouTube.V3.Model.LiveStreamSnippet do @moduledoc """ ## Attributes * `channelId` (*type:* `String.t`, *default:* `nil`) - The ID that YouTube uses to uniquely identify the channel that is transmitting the stream. * `description` (*type:* `String.t`, *default:* `nil`) - The stream's description. The value cannot be longer than 10000 characters. * `isDefaultStream` (*type:* `boolean()`, *default:* `nil`) - * `publishedAt` (*type:* `String.t`, *default:* `nil`) - The date and time that the stream was created. The value is specified in <a href="//www.w3.org/TR/NOTE-datetime">ISO 8601</a> format. * `title` (*type:* `String.t`, *default:* `nil`) - The stream's title. The value must be between 1 and 128 characters long. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :channelId => String.t(), :description => String.t(), :isDefaultStream => boolean(), :publishedAt => String.t(), :title => String.t() } field(:channelId) field(:description) field(:isDefaultStream) field(:publishedAt) field(:title) end defimpl Poison.Decoder, for: GoogleApi.YouTube.V3.Model.LiveStreamSnippet do def decode(value, options) do GoogleApi.YouTube.V3.Model.LiveStreamSnippet.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.YouTube.V3.Model.LiveStreamSnippet do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.095238
133
0.691542
f76cf5fbbaf85369ef910b9458efb8bf17835c03
68
ex
Elixir
apps/massa_proxy/lib/massa_proxy/runtime/wasm/protocol/discovery/manager.ex
drowzy/massa
624cb02e0039b0624c534636f96fd157b1e34a95
[ "Apache-2.0" ]
20
2021-06-28T12:03:49.000Z
2022-03-28T22:35:56.000Z
apps/massa_proxy/lib/massa_proxy/runtime/wasm/protocol/discovery/manager.ex
drowzy/massa
624cb02e0039b0624c534636f96fd157b1e34a95
[ "Apache-2.0" ]
48
2021-03-19T12:01:38.000Z
2022-03-29T21:19:26.000Z
apps/massa_proxy/lib/massa_proxy/runtime/wasm/protocol/discovery/manager.ex
drowzy/massa
624cb02e0039b0624c534636f96fd157b1e34a95
[ "Apache-2.0" ]
5
2021-03-18T21:46:10.000Z
2021-10-01T17:39:05.000Z
defmodule MassaProxy.Runtime.Protocol.Wasm.Discovery.Manager do end
22.666667
63
0.867647
f76d2efb8fa39df3dbe0b867f96bce6fdd268919
4,182
ex
Elixir
lib/states_language/ast/default.ex
CityBaseInc/states_language
474b8a46f392b62d03c5ff5ed7f10f576b3166d7
[ "MIT" ]
67
2019-12-04T07:31:58.000Z
2020-04-02T21:52:44.000Z
lib/states_language/ast/default.ex
fpalluel/states_language
a5772b6ba700651078592c71d63bc46bfbdd19b9
[ "MIT" ]
5
2019-12-04T18:53:08.000Z
2020-04-02T19:02:34.000Z
lib/states_language/ast/default.ex
fpalluel/states_language
a5772b6ba700651078592c71d63bc46bfbdd19b9
[ "MIT" ]
7
2019-12-05T11:41:48.000Z
2020-04-02T14:08:27.000Z
# credo:disable-for-this-file defmodule StatesLanguage.AST.Default do @moduledoc false @behaviour StatesLanguage.AST @impl true def create(_) do quote location: :keep do defdelegate call(pid, event), to: :gen_statem defdelegate call(pid, event, timeout), to: :gen_statem defdelegate cast(pid, event), to: :gen_statem @impl true def handle_resource(_, _, _, data), do: {:ok, data, []} @impl true def handle_call(_, from, _, data), do: {:ok, data, {:reply, from, :ok}} @impl true def handle_cast(_, _, data), do: {:ok, data, []} @impl true def handle_info(_, _, data), do: {:ok, data, []} @impl true def handle_transition(_, _, data), do: {:ok, data, []} @impl true def handle_enter(_, _, data), do: {:ok, data, []} @impl true def handle_termination(_, _, data), do: :ok @impl true def handle_generic_timeout(_, _, data), do: {:ok, data, []} @impl true def handle_state_timeout(_, _, data), do: {:ok, data, []} @impl true def handle_event_timeout(_, _, data), do: {:ok, data, []} defoverridable handle_resource: 4, handle_call: 4, handle_cast: 3, handle_info: 3, handle_transition: 3, handle_enter: 3, handle_termination: 3, handle_generic_timeout: 3, handle_state_timeout: 3, handle_event_timeout: 3 @impl true def handle_event(:internal, na_event, na_state, %StatesLanguage{} = data) do Logger.warn("Unknown Event #{inspect(na_event)} while in state #{inspect(na_state)}") :keep_state_and_data end @impl true def handle_event(:enter, source, target, %StatesLanguage{} = data) do Logger.warn("Unknown enter event from #{inspect(source)} to #{inspect(target)}") :keep_state_and_data end @impl true def handle_event(:info, event, state, %StatesLanguage{} = data) do {:ok, data, actions} = handle_info(event, state, data) Logger.debug( "Handled info event: #{inspect(event)} in state #{state} with data #{inspect(data)}" ) {:keep_state, data, actions} end @impl true def handle_event({:call, from}, event, state, %StatesLanguage{} = data) do {:ok, data, actions} = handle_call(event, from, state, data) Logger.debug( "Handled call event: #{inspect(event)} in state #{state} with data #{inspect(data)}" ) {:keep_state, data, actions} end @impl true def handle_event(:cast, event, state, %StatesLanguage{} = data) do {:ok, data, actions} = handle_cast(event, state, data) Logger.debug( "Handled cast event: #{inspect(event)} in state #{state} with data #{inspect(data)}" ) {:keep_state, data, actions} end @impl true def handle_event({:timeout, :generic}, event, state, %StatesLanguage{} = data) do {:ok, data, actions} = handle_generic_timeout(event, state, data) Logger.debug( "Handled generic timeout event: #{inspect(event)} in state #{state} with data #{ inspect(data) }" ) {:keep_state, data, actions} end @impl true def handle_event(:state_timeout, event, state, %StatesLanguage{} = data) do {:ok, data, actions} = handle_state_timeout(event, state, data) Logger.debug( "Handled state timeout event: #{inspect(event)} in state #{state} with data #{ inspect(data) }" ) {:keep_state, data, actions} end @impl true def handle_event(:timeout, event, state, %StatesLanguage{} = data) do {:ok, data, actions} = handle_event_timeout(event, state, data) Logger.debug( "Handled event timeout event: #{inspect(event)} in state #{state} with data #{ inspect(data) }" ) {:keep_state, data, actions} end end end end
29.659574
94
0.566954
f76d670dc0ba11d5f4db33c562b8f847817fe7a7
23,426
exs
Elixir
lib/mix/test/mix/tasks/deps_test.exs
evalphobia/elixir
a07a2362e5827b09d8b27be2c1ad2980d25b9768
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/deps_test.exs
evalphobia/elixir
a07a2362e5827b09d8b27be2c1ad2980d25b9768
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/deps_test.exs
evalphobia/elixir
a07a2362e5827b09d8b27be2c1ad2980d25b9768
[ "Apache-2.0" ]
null
null
null
Code.require_file "../../test_helper.exs", __DIR__ defmodule Mix.Tasks.DepsTest do use MixTest.Case defmodule DepsApp do def project do [app: :deps, version: "0.1.0", deps: [ {:ok, "0.1.0", github: "elixir-lang/ok"}, {:invalidvsn, "0.2.0", path: "deps/invalidvsn"}, {:invalidapp, "0.1.0", path: "deps/invalidapp"}, {:noappfile, "0.1.0", path: "deps/noappfile"}, {:nosemver, "~> 0.1", path: "deps/nosemver"}, ]] end end defmodule SuccessfulDepsApp do def project do [app: :sample, version: "0.1.0", deps: [ {:ok, "0.1.0", path: "deps/ok"} ]] end end defmodule ReqDepsApp do def project do [app: :req_deps, version: "0.1.0", deps: [ {:ok, ">= 2.0.0", path: "deps/ok"}, {:noappfile, path: "deps/noappfile", app: false}, {:apppath, path: "deps/noappfile", app: "../deps/ok/ebin/ok.app"} ]] end end ## deps test "prints list of dependencies and their status" do Mix.Project.push DepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, ["* ok (https://github.com/elixir-lang/ok.git) (mix)"]} assert_received {:mix_shell, :info, [" the dependency is not available, run \"mix deps.get\""]} assert_received {:mix_shell, :info, ["* invalidvsn (deps/invalidvsn)"]} assert_received {:mix_shell, :info, [" the app file contains an invalid version: :ok"]} assert_received {:mix_shell, :info, ["* invalidapp (deps/invalidapp) (mix)"]} assert_received {:mix_shell, :info, [" the app file at _build/dev/lib/invalidapp/ebin/invalidapp.app is invalid"]} assert_received {:mix_shell, :info, ["* noappfile (deps/noappfile)"]} assert_received {:mix_shell, :info, [" could not find an app file at _build/dev/lib/noappfile/ebin/noappfile.app" <> _]} assert_received {:mix_shell, :info, ["* nosemver (deps/nosemver)"]} assert_received {:mix_shell, :info, [" the app file specified a non-Semantic Versioning format: \"0.7\"" <> _]} end end test "prints list of dependencies and their status, including req mismatches and custom apps" do Mix.Project.push ReqDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, ["* ok (deps/ok) (mix)"]} assert_received {:mix_shell, :info, [" the dependency does not match the requirement \">= 2.0.0\", got \"0.1.0\""]} assert_received {:mix_shell, :info, ["* noappfile (deps/noappfile)"]} assert_received {:mix_shell, :info, ["* apppath (deps/noappfile)"]} refute_received {:mix_shell, :info, [" could not find app file at _build/dev/lib/noappfile/ebin/apppath.app" <> _]} refute_received {:mix_shell, :info, [" could not find app file at _build/dev/lib/noappfile/ebin/noappfile.app" <> _]} end end test "prints Elixir req mismatches" do Mix.Project.push ReqDepsApp in_fixture "deps_status", fn -> File.write! "deps/ok/mix.exs", """ defmodule Deps.OkApp do use Mix.Project def project do [elixir: "~> 0.1.0", app: :ok, version: "2.0.0"] end end """ Mix.Tasks.Deps.Compile.run [:ok] msg = "warning: the dependency :ok requires Elixir \"~> 0.1.0\" " <> "but you are running on v#{System.version}" assert_received {:mix_shell, :error, [^msg]} Mix.Tasks.Deps.Compile.run [] end end test "prints list of dependencies and their lock status" do Mix.Project.push DepsApp in_fixture "deps_status", fn -> File.cd!("deps/ok", fn -> System.cmd("git", ["init"]) end) Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, ["* ok (https://github.com/elixir-lang/ok.git) (mix)"]} assert_received {:mix_shell, :info, [" the dependency is not locked (run \"mix deps.get\" to generate \"mix.lock\" file)"]} Mix.Dep.Lock.write %{ok: {:git, "https://github.com/elixir-lang/ok.git", "abcdefghi", []}} Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, ["* ok (https://github.com/elixir-lang/ok.git) (mix)"]} assert_received {:mix_shell, :info, [" locked at abcdefg"]} assert_received {:mix_shell, :info, [" lock mismatch: the dependency is out of date (run \"mix deps.get\" to fetch locked version)"]} Mix.Dep.Lock.write %{ok: {:git, "git://github.com/elixir-lang/another.git", "abcdefghi", []}} Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, ["* ok (https://github.com/elixir-lang/ok.git) (mix)"]} assert_received {:mix_shell, :info, [" lock outdated: the lock is outdated compared to the options in your mixfile (run \"mix deps.get\" to fetch locked version)"]} end end test "cleans and recompiles artifacts if --force given" do Mix.Project.push SuccessfulDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Compile.run [] File.touch! "_build/dev/lib/ok/clean-me" Mix.Tasks.Deps.Compile.run ["--force"] refute File.exists? "_build/dev/lib/ok/clean-me" end end ## deps.loadpaths test "checks list of dependencies and their status with success" do Mix.Project.push SuccessfulDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Loadpaths.run [] end end test "checks list of dependencies and their status on failure" do Mix.Project.push DepsApp in_fixture "deps_status", fn -> assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Loadpaths.run [] end assert_received {:mix_shell, :error, ["* ok (https://github.com/elixir-lang/ok.git)"]} assert_received {:mix_shell, :error, [" the dependency is not available, run \"mix deps.get\""]} assert_received {:mix_shell, :error, ["* invalidvsn (deps/invalidvsn)"]} assert_received {:mix_shell, :error, [" the app file contains an invalid version: :ok"]} assert_received {:mix_shell, :error, ["* invalidapp (deps/invalidapp)"]} assert_received {:mix_shell, :error, [" the app file at _build/dev/lib/invalidapp/ebin/invalidapp.app is invalid"]} # This one is compiled automatically refute_received {:mix_shell, :error, ["* noappfile (deps/noappfile)"]} refute_received {:mix_shell, :error, [" could not find an app file at _build/dev/lib/noappfile/ebin/noappfile.app" <> _]} end end test "compiles and prunes builds per environment" do Mix.Project.push SuccessfulDepsApp in_fixture "deps_status", fn -> # Start from scratch! File.rm_rf("_build") Mix.Tasks.Deps.Compile.run [] Mix.Tasks.Deps.Loadpaths.run [] assert File.exists?("_build/dev/lib/ok/ebin/ok.app") assert File.exists?("_build/dev/lib/ok/priv/sample") Mix.Tasks.Compile.run [] assert to_charlist(Path.expand("_build/dev/lib/ok/ebin/")) in :code.get_path assert File.exists?("_build/dev/lib/sample/ebin/sample.app") # Remove the deps but set build_path, deps won't be pruned, but load paths are Mix.ProjectStack.post_config [deps: [], build_path: "_build"] Mix.ProjectStack.clear_cache Mix.Project.pop Mix.Project.push SuccessfulDepsApp Mix.Tasks.Deps.Loadpaths.run [] refute to_charlist(Path.expand("_build/dev/lib/ok/ebin/")) in :code.get_path assert File.exists?("_build/dev/lib/ok/ebin/ok.app") assert File.exists?("_build/dev/lib/sample/ebin/sample.app") # Remove the deps without build_path, deps will be pruned Mix.ProjectStack.post_config [deps: []] Mix.ProjectStack.clear_cache Mix.Project.pop Mix.Project.push SuccessfulDepsApp Mix.Tasks.Deps.Loadpaths.run [] refute File.exists?("_build/dev/lib/ok/ebin/ok.app") assert File.exists?("_build/dev/lib/sample/ebin/sample.app") end end ## deps.unlock test "unlocks all deps", context do Mix.Project.push DepsApp in_tmp context.test, fn -> Mix.Dep.Lock.write %{git_repo: "abcdef"} assert Mix.Dep.Lock.read == %{git_repo: "abcdef"} Mix.Tasks.Deps.Unlock.run ["--all"] assert Mix.Dep.Lock.read == %{} end end test "unlocks unused deps", context do Mix.Project.push DepsApp in_tmp context.test, fn -> Mix.Dep.Lock.write %{whatever: "abcdef", ok: "abcdef"} assert Mix.Dep.Lock.read == %{whatever: "abcdef", ok: "abcdef"} Mix.Tasks.Deps.Unlock.run ["--unused"] assert Mix.Dep.Lock.read == %{ok: "abcdef"} end end test "unlocks specific deps", context do Mix.Project.push DepsApp in_tmp context.test, fn -> Mix.Dep.Lock.write %{git_repo: "abcdef", another: "hash"} Mix.Tasks.Deps.Unlock.run ["git_repo", "unknown"] assert Mix.Dep.Lock.read == %{another: "hash"} error = "warning: unknown dependency is not locked" assert_received {:mix_shell, :error, [^error]} end end test "unlocks filtered deps", context do Mix.Project.push DepsApp in_tmp context.test, fn -> Mix.Dep.Lock.write %{git_repo: "abcdef", another: "hash", another_one: "hash"} Mix.Tasks.Deps.Unlock.run ["--filter", "another"] assert Mix.Dep.Lock.read == %{git_repo: "abcdef"} output = """ Unlocked deps: * another * another_one """ assert_received {:mix_shell, :info, [^output]} end end test "fails with message on missing dependencies" do Mix.Project.push DepsApp assert_raise Mix.Error, ~r/"mix deps\.unlock" expects dependencies as arguments/, fn -> Mix.Tasks.Deps.Unlock.run [] end end ## Deps environment defmodule DepsEnvApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:raw_repo, "0.1.0", path: "custom/raw_repo"} ] ] end end defmodule CustomDepsEnvApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:raw_repo, "0.1.0", path: "custom/raw_repo", env: :dev} ] ] end end test "sets deps env to prod by default" do Mix.Project.push DepsEnvApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Update.run ["--all"] assert_received {:mix_shell, :info, [":raw_repo env is prod"]} end end test "can customize environment" do Mix.Project.push CustomDepsEnvApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Update.run ["--all"] assert_received {:mix_shell, :info, [":raw_repo env is dev"]} end end ## Nested dependencies defmodule ConflictDepsApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:git_repo, "0.1.0", path: "custom/raw_repo"}, {:bad_deps_repo, "0.1.0", path: "custom/bad_deps_repo"} ] ] end end defmodule DivergedDepsApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:deps_repo, "0.1.0", path: "custom/deps_repo"}, {:bad_deps_repo, "0.1.0", path: "custom/bad_deps_repo"} ] ] end end defmodule ConvergedDepsApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:deps_repo, "0.1.0", path: "custom/deps_repo"}, {:git_repo, ">= 0.1.0", git: MixTest.Case.fixture_path("git_repo")} ] ] end end defmodule OverriddenDepsApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:bad_deps_repo, "0.1.0", path: "custom/bad_deps_repo"}, {:git_repo, "0.1.0", git: MixTest.Case.fixture_path("git_repo"), override: true} ] ] end end defmodule NonOverriddenDepsApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:bad_deps_repo, "0.1.0", path: "custom/bad_deps_repo"}, {:git_repo, "0.1.0", git: MixTest.Case.fixture_path("git_repo")} ] ] end end test "fails on missing dependencies" do Mix.Project.push SuccessfulDepsApp in_fixture "deps_status", fn -> assert_raise Mix.Error, ~r/Unknown dependency invalid for environment dev/, fn -> Mix.Tasks.Deps.Update.run ["invalid"] end end end test "fails on diverged dependencies on get/update" do Mix.Project.push ConflictDepsApp in_fixture "deps_status", fn -> assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Loadpaths.run [] end assert_received {:mix_shell, :error, [" the dependency git_repo in mix.exs is overriding a child dependency" <> _]} assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Get.run [] end assert_received {:mix_shell, :error, [" the dependency git_repo in mix.exs is overriding a child dependency" <> _]} assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Update.run ["--all"] end assert_received {:mix_shell, :error, [" the dependency git_repo in mix.exs is overriding a child dependency" <> _]} end end test "fails on diverged dependencies on check" do Mix.Project.push DivergedDepsApp in_fixture "deps_status", fn -> assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Loadpaths.run [] end assert_received {:mix_shell, :error, [" different specs were given for the git_repo app:" <> _ = msg]} assert msg =~ "In custom/deps_repo/mix.exs:" assert msg =~ "{:git_repo, \"0.1.0\", [env: :prod, git: #{inspect fixture_path("git_repo")}]}" end end test "fails on diverged dependencies by requirement" do Mix.Project.push ConvergedDepsApp in_fixture "deps_status", fn -> File.write! "custom/deps_repo/mix.exs", """ defmodule DepsRepo do use Mix.Project def project do [ app: :deps_repo, version: "0.1.0", deps: [ {:git_repo, "0.2.0", git: MixTest.Case.fixture_path("git_repo")} ] ] end end """ assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Get.run [] Mix.Tasks.Deps.Loadpaths.run [] end assert_received {:mix_shell, :error, [" the dependency git_repo 0.1.0" <> _ = msg]} assert msg =~ "In custom/deps_repo/mix.exs:" assert msg =~ "{:git_repo, \"0.2.0\", [env: :prod, git: #{inspect fixture_path("git_repo")}]}" end end test "fails on diverged dependencies even when optional" do Mix.Project.push ConvergedDepsApp in_fixture "deps_status", fn -> File.write! "custom/deps_repo/mix.exs", """ defmodule DepsRepo do use Mix.Project def project do [ app: :deps_repo, version: "0.1.0", deps: [ {:git_repo, git: MixTest.Case.fixture_path("bad_git_repo"), branch: "omg"} ] ] end end """ assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Get.run [] Mix.Tasks.Deps.Loadpaths.run [] end assert_received {:mix_shell, :error, [" the dependency git_repo in mix.exs is overriding" <> _]} end end test "works with converged dependencies" do Mix.Project.push ConvergedDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Get.run [] message = "* Getting git_repo (#{fixture_path("git_repo")})" assert_received {:mix_shell, :info, [^message]} # Make sure retriever uses converger, # so the message appears just once refute_received {:mix_shell, :info, [^message]} Mix.Task.clear Mix.Tasks.Deps.Update.run ["--all"] message = "* Updating git_repo (#{fixture_path("git_repo")})" assert_received {:mix_shell, :info, [^message]} end after purge [GitRepo, GitRepo.Mixfile] end test "works with overridden dependencies" do Mix.Project.push OverriddenDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Get.run [] message = "* Getting git_repo (#{fixture_path("git_repo")})" assert_received {:mix_shell, :info, [^message]} # Make sure retriever uses converger, # so the message appears just once refute_received {:mix_shell, :info, [^message]} Mix.Task.clear Mix.Tasks.Deps.Update.run ["--all"] message = "* Updating git_repo (#{fixture_path("git_repo")})" assert_received {:mix_shell, :info, [^message]} end after purge [GitRepo, GitRepo.Mixfile] end test "converged dependencies errors if not overriding" do Mix.Project.push NonOverriddenDepsApp in_fixture "deps_status", fn -> assert_raise Mix.Error, fn -> Mix.Tasks.Deps.Loadpaths.run [] end receive do {:mix_shell, :error, [" the dependency git_repo in mix.exs" <> _ = msg]} -> assert msg =~ "In mix.exs:" assert msg =~ "{:git_repo, \"0.1.0\", [env: :prod, git: #{inspect fixture_path("git_repo")}]}" after 0 -> flunk "expected overriding error message" end end after purge [GitRepo, GitRepo.Mixfile] end test "checks if dependencies are using old Elixir version" do Mix.Project.push SuccessfulDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Compile.run [] Mix.Tasks.Deps.Loadpaths.run [] File.mkdir_p!("_build/dev/lib/ok/ebin") manifest_data = :erlang.term_to_binary({:v1, "the_future", :scm}) File.write!("_build/dev/lib/ok/.compile.elixir_scm", manifest_data) Mix.Task.clear msg = " the dependency was built with an out-of-date Elixir version, run \"mix deps.compile\"" Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, [^msg]} # deps.loadpaths will automatically recompile it Mix.Tasks.Deps.Loadpaths.run [] Mix.Tasks.Deps.run [] refute_received {:mix_shell, :info, [^msg]} end end test "checks if dependencies are using old scm version" do Mix.Project.push SuccessfulDepsApp in_fixture "deps_status", fn -> Mix.Tasks.Deps.Compile.run [] Mix.Tasks.Deps.Loadpaths.run [] File.mkdir_p!("_build/dev/lib/ok/ebin") manifest_data = :erlang.term_to_binary({:v1, System.version, :scm}) File.write!("_build/dev/lib/ok/.compile.elixir_scm", manifest_data) Mix.Task.clear msg = " the dependency was built with another SCM, run \"mix deps.compile\"" Mix.Tasks.Deps.run [] assert_received {:mix_shell, :info, [^msg]} # deps.loadpaths will automatically recompile it Mix.Tasks.Deps.Loadpaths.run [] Mix.Tasks.Deps.run [] refute_received {:mix_shell, :info, [^msg]} end end defmodule NonCompilingDeps do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:git_repo, "0.1.0", git: MixTest.Case.fixture_path("git_repo"), compile: false} ] ] end end test "does not compile deps that have explicit flag" do Mix.Project.push NonCompilingDeps in_fixture "deps_status", fn -> Mix.Tasks.Deps.Compile.run [] refute_received {:mix_shell, :info, ["==> git_repo"]} end end defmodule DupDeps do def project do [ app: :raw_sample, version: "0.1.0", deps: [ # Simulate dependencies gathered together from umbrella {:ok, "0.1.0", path: "deps/ok"}, {:ok, "0.1.0", path: "deps/ok"} ] ] end end test "warns and converges duplicated deps at the same level" do Mix.Project.push DupDeps in_fixture "deps_status", fn -> Mix.Tasks.Deps.run [] assert_received {:mix_shell, :error, ["warning: the dependency :ok is duplicated at the top level, " <> "please remove one of them"]} msg = "* ok 0.1.0 (deps/ok) (mix)" assert_received {:mix_shell, :info, [^msg]} refute_received {:mix_shell, :info, [^msg]} end end ## deps.clean defmodule CleanDepsApp do def project do [ app: :raw_sample, version: "0.1.0", deps: [ {:git_repo, ">= 0.1.0", git: MixTest.Case.fixture_path("git_repo")}, {:ok, ">= 2.0.0", path: "deps/ok"} ] ] end end test "cleans dependencies" do Mix.Project.push CleanDepsApp in_fixture "deps_status", fn -> File.mkdir_p!("_build/dev/lib/raw_sample") File.mkdir_p!("_build/dev/lib/git_repo") File.mkdir_p!("_build/test/lib/git_repo") File.mkdir_p!("_build/dev/lib/ok") File.mkdir_p!("_build/test/lib/ok") message = "\"mix deps.clean\" expects dependencies as arguments or " <> "a flag indicating which dependencies to clean. " <> "The --all option will clean all dependencies while " <> "the --unused option cleans unused dependencies" assert_raise Mix.Error, message, fn -> Mix.Tasks.Deps.Clean.run [] end Mix.Tasks.Deps.Clean.run ["--only", "dev", "--all"] refute File.exists?("_build/dev/lib/git_repo") refute File.exists?("_build/dev/lib/ok") assert File.exists?("_build/test/lib/git_repo") assert File.exists?("_build/dev/lib/raw_sample") Mix.Tasks.Deps.Clean.run ["--all"] refute File.exists?("_build/dev/lib/git_repo") refute File.exists?("_build/test/lib/git_repo") assert File.exists?("_build/dev/lib/raw_sample") end end test "cleans unused dependencies" do Mix.Project.push CleanDepsApp in_fixture "deps_status", fn -> File.mkdir_p!("_build/dev/lib/raw_sample") File.mkdir_p!("deps/git_repo") File.mkdir_p!("_build/dev/lib/git_repo") File.mkdir_p!("deps/git_repo_unused") File.mkdir_p!("_build/dev/lib/git_repo_unused") Mix.Tasks.Deps.Clean.run ["--unused"] assert File.exists?("deps/git_repo") assert File.exists?("_build/dev/lib/git_repo") refute File.exists?("deps/git_repo_unused") refute File.exists?("_build/dev/lib/git_repo_unused") assert File.exists?("_build/dev/lib/raw_sample") end end test "cleans dependencies build" do Mix.Project.push CleanDepsApp in_fixture "deps_status", fn -> File.mkdir_p!("deps/raw_sample") File.mkdir_p!("_build/dev/lib/raw_sample") Mix.Tasks.Deps.Clean.run ["raw_sample", "--build"] assert File.exists?("deps/raw_sample") refute File.exists?("_build/dev/lib/raw_sample") end end test "warns on invalid path on clean dependencies" do Mix.Project.push CleanDepsApp in_fixture "deps_status", fn -> File.mkdir_p!("deps/raw_sample") File.mkdir_p!("_build/dev/lib/raw_sample") Mix.Tasks.Deps.Clean.run ["raw_sample_with_a_typo"] assert File.exists?("deps/raw_sample") msg = "warning: the dependency raw_sample_with_a_typo is not present in the build directory" assert_received {:mix_shell, :error, [^msg]} end end test "does not remove dependency source when using :path" do Mix.Project.push CleanDepsApp in_fixture "deps_status", fn -> assert File.exists?("deps/ok") Mix.Tasks.Deps.Clean.run ["raw_sample", "--all"] refute File.exists?("_build/dev/lib/ok") refute File.exists?("_build/test/lib/ok") assert File.exists?("deps/ok") end end end
31.276368
171
0.616793
f76da3f96cd534839e4f881b77e07b8041a5463f
1,604
exs
Elixir
mix.exs
shinyscorpion/time_machinex
00a93c4329e269ff112edd0e464ebe1b0684d25e
[ "MIT" ]
6
2018-05-31T22:48:41.000Z
2021-03-03T17:22:48.000Z
mix.exs
shinyscorpion/time_machinex
00a93c4329e269ff112edd0e464ebe1b0684d25e
[ "MIT" ]
1
2019-12-19T08:18:39.000Z
2019-12-19T08:18:39.000Z
mix.exs
shinyscorpion/time_machinex
00a93c4329e269ff112edd0e464ebe1b0684d25e
[ "MIT" ]
1
2018-01-31T12:12:26.000Z
2018-01-31T12:12:26.000Z
defmodule TimeMachinex.MixProject do use Mix.Project @version "0.3.0" @description "Time machine clock to simplify time testing" def project do [ app: :time_machinex, version: @version, description: @description, elixir: "~> 1.9", start_permanent: Mix.env() == :prod, deps: deps(), package: package(), # Testing test_coverage: [tool: ExCoveralls], preferred_cli_env: [ coveralls: :test, "coveralls.detail": :test, "coveralls.post": :test, "coveralls.html": :test ], dialyzer: [ignore_warnings: ".dialyzer", plt_add_deps: true], # Docs name: "TimeMachinex", docs: [extras: ["README.md", "CHANGELOG.md", "LICENSE.md"]] ] end defp package do [ name: :time_machinex, files: [ # Project files "mix.exs", "README.md", "CHANGELOG.md", "LICENSE.md", # TimeMachinex "lib/time_machinex.ex", "lib/time_machinex" ], maintainers: [ "Antonio Sagliocco", "Elliott Hilaire", "Francesco Grammatico", "Ian Luites", "Ricardo Perez", "Tatsuya Ono" ], licenses: ["MIT"], links: %{"GitHub" => "https://github.com/shinyscorpion/time_machinex"} ] end def application do [ extra_applications: [:logger] ] end # Run "mix help deps" to learn about dependencies. defp deps do [ {:analyze, "~> 0.1", only: [:dev, :test], runtime: false}, {:utc_datetime, ">= 0.0.0"} ] end end
21.972603
76
0.546135
f76db934a88ff2a6765af1a8ad2a76517005295a
16,682
exs
Elixir
lib/mix/test/mix/tasks/xref_test.exs
fertapric/elixir
9df2216670493aa30f37681cc812f3192adfe55a
[ "Apache-2.0" ]
null
null
null
lib/mix/test/mix/tasks/xref_test.exs
fertapric/elixir
9df2216670493aa30f37681cc812f3192adfe55a
[ "Apache-2.0" ]
1
2019-04-25T12:52:49.000Z
2019-04-25T13:27:31.000Z
lib/mix/test/mix/tasks/xref_test.exs
fertapric/elixir
9df2216670493aa30f37681cc812f3192adfe55a
[ "Apache-2.0" ]
null
null
null
Code.require_file("../../test_helper.exs", __DIR__) defmodule Mix.Tasks.XrefTest do use MixTest.Case import ExUnit.CaptureIO setup_all do previous = Application.get_env(:elixir, :ansi_enabled, false) Application.put_env(:elixir, :ansi_enabled, false) on_exit(fn -> Application.put_env(:elixir, :ansi_enabled, previous) end) end setup do Mix.Project.push(MixTest.Case.Sample) :ok end test "calls: returns all function calls" do files = %{ "lib/a.ex" => """ defmodule A do def a, do: A.a() def a(arg), do: A.a(arg) def c, do: B.a() end """, "lib/b.ex" => """ defmodule B do def a, do: nil end """ } output = [ %{callee: {A, :a, 0}, caller_module: A, file: "lib/a.ex", line: 2}, %{callee: {A, :a, 1}, caller_module: A, file: "lib/a.ex", line: 3}, %{callee: {B, :a, 0}, caller_module: A, file: "lib/a.ex", line: 4}, %{callee: {Kernel, :def, 2}, caller_module: A, file: "lib/a.ex", line: 4}, %{callee: {Kernel, :def, 2}, caller_module: A, file: "lib/a.ex", line: 3}, %{callee: {Kernel, :def, 2}, caller_module: A, file: "lib/a.ex", line: 2}, %{callee: {Kernel, :defmodule, 2}, caller_module: A, file: "lib/a.ex", line: 1}, %{ callee: {Kernel.LexicalTracker, :read_cache, 2}, caller_module: A, file: "lib/a.ex", line: 1 }, %{callee: {Kernel, :def, 2}, caller_module: B, file: "lib/b.ex", line: 2}, %{callee: {Kernel, :defmodule, 2}, caller_module: B, file: "lib/b.ex", line: 1}, %{ callee: {Kernel.LexicalTracker, :read_cache, 2}, caller_module: B, file: "lib/b.ex", line: 1 } ] assert_all_calls(files, output) end test "calls: returns macro call" do files = %{ "lib/a.ex" => """ defmodule A do defmacro a_macro, do: :ok end """, "lib/b.ex" => """ defmodule B do require A def a, do: A.a_macro() end """ } output = [ %{callee: {A, :a_macro, 0}, caller_module: B, file: "lib/b.ex", line: 3}, %{callee: {Kernel, :def, 2}, caller_module: B, file: "lib/b.ex", line: 3}, %{callee: {Kernel, :defmodule, 2}, caller_module: B, file: "lib/b.ex", line: 1}, %{ callee: {Kernel.LexicalTracker, :read_cache, 2}, line: 1, caller_module: B, file: "lib/b.ex" }, %{callee: {Kernel, :defmacro, 2}, caller_module: A, file: "lib/a.ex", line: 2}, %{callee: {Kernel, :defmodule, 2}, caller_module: A, file: "lib/a.ex", line: 1}, %{ callee: {Kernel.LexicalTracker, :read_cache, 2}, line: 1, caller_module: A, file: "lib/a.ex" } ] assert_all_calls(files, output) end test "calls: returns function call inside macro" do files = %{ "lib/a.ex" => """ defmodule A do defmacro a_macro(x) do quote do A.b(unquote(x)) end end def b(x), do: x end """, "lib/b.ex" => """ defmodule B do require A def a, do: A.a_macro(1) end """ } output = [ %{callee: {A, :b, 1}, caller_module: B, file: "lib/b.ex", line: 3}, %{callee: {A, :a_macro, 1}, caller_module: B, file: "lib/b.ex", line: 3}, %{callee: {Kernel, :def, 2}, caller_module: B, file: "lib/b.ex", line: 3}, %{callee: {Kernel, :defmodule, 2}, caller_module: B, file: "lib/b.ex", line: 1}, %{ callee: {Kernel.LexicalTracker, :read_cache, 2}, caller_module: B, file: "lib/b.ex", line: 1 }, %{callee: {Kernel, :def, 2}, caller_module: A, file: "lib/a.ex", line: 8}, %{callee: {Kernel, :defmacro, 2}, caller_module: A, file: "lib/a.ex", line: 2}, %{callee: {Kernel, :defmodule, 2}, caller_module: A, file: "lib/a.ex", line: 1}, %{ callee: {Kernel.LexicalTracker, :read_cache, 2}, caller_module: A, file: "lib/a.ex", line: 1 } ] assert_all_calls(files, output) end defp assert_all_calls(files, expected) do in_fixture("no_mixfile", fn -> generate_files(files) Mix.Task.run("compile") assert Enum.sort(Mix.Tasks.Xref.calls()) == Enum.sort(expected) end) end ## Callers test "callers: prints callers of specified Module" do files = %{ "lib/a.ex" => """ defmodule A do def a, do: A.a() def a(arg), do: A.a(arg) def b, do: A.b() def c, do: B.a() @file "lib/external_source.ex" def d, do: A.a() end """ } output = """ Compiling 2 files (.ex) Generated sample app lib/a.ex:2: A.a/0 lib/external_source.ex:8: A.a/0 lib/a.ex:3: A.a/1 lib/a.ex:4: A.b/0 """ assert_callers("A", files, output) end test "callers: prints callers of specified Module.func" do files = %{ "lib/a.ex" => """ defmodule A do def a, do: A.a() def a(arg), do: A.a(arg) def b, do: A.b() def c, do: B.a() @file "lib/external_source.ex" def d, do: A.a() end """ } output = """ Compiling 2 files (.ex) Generated sample app lib/a.ex:2: A.a/0 lib/external_source.ex:8: A.a/0 lib/a.ex:3: A.a/1 """ assert_callers("A.a", files, output) end test "callers: prints callers of specified Module.func/arity" do files = %{ "lib/a.ex" => """ defmodule A do def a, do: A.a() def a(arg), do: A.a(arg) def b, do: A.b() def c, do: B.a() @file "lib/external_source.ex" def d, do: A.a() end """ } output = """ Compiling 2 files (.ex) Generated sample app lib/a.ex:2: A.a/0 lib/external_source.ex:8: A.a/0 """ assert_callers("A.a/0", files, output) end test "callers: lists compile calls and macros" do files = %{ "lib/a.ex" => """ defmodule A do defmacro a_macro, do: :ok def a, do: :ok end """, "lib/b.ex" => """ defmodule B do require A A.a_macro() A.a() @file "lib/external_source.ex" def b do A.a_macro() A.a() end end """ } output = """ Compiling 2 files (.ex) Generated sample app lib/b.ex:5: A.a/0 lib/external_source.ex:10: A.a/0 lib/b.ex:4: A.a_macro/0 lib/external_source.ex:9: A.a_macro/0 """ assert_callers("A", files, output) end test "callers: handles aliases" do files = %{ "lib/a.ex" => """ defmodule A do alias Enum, as: E E.map([], &E.flatten/1) def a(a, b), do: E.map(a, b) @file "lib/external_source.ex" def b() do alias Enum, as: EE EE.map([], &EE.flatten/1) end end """ } output = """ Compiling 2 files (.ex) Generated sample app lib/a.ex:4: Enum.flatten/1 lib/external_source.ex:11: Enum.flatten/1 lib/a.ex:4: Enum.map/2 lib/a.ex:6: Enum.map/2 lib/external_source.ex:11: Enum.map/2 """ assert_callers("Enum", files, output) end test "callers: handles imports" do files = %{ "lib/a.ex" => ~S""" defmodule A do import Integer &is_even/1 &parse/1 _ = is_even(Enum.random([1])) _ = parse("2") def a(a), do: is_even(a) def b(a), do: parse(a) _ = is_even(Enum.random([1])); def c(a), do: is_even(a) end """, "lib/b.ex" => ~S""" defmodule B do &Integer.parse/1 @file "lib/external_source.ex" def a(a) do import Integer parse(1) is_even(a) end end """ } output = """ Compiling 2 files (.ex) Generated sample app lib/a.ex:4: Integer.is_even/1 lib/a.ex:7: Integer.is_even/1 lib/a.ex:10: Integer.is_even/1 lib/a.ex:12: Integer.is_even/1 lib/external_source.ex:8: Integer.is_even/1 lib/a.ex:5: Integer.parse/1 lib/a.ex:8: Integer.parse/1 lib/a.ex:11: Integer.parse/1 lib/b.ex:2: Integer.parse/1 lib/external_source.ex:7: Integer.parse/1 """ assert_callers("Integer", files, output) end test "callers: no argument gives error" do in_fixture("no_mixfile", fn -> message = "xref doesn't support this command. For more information run \"mix help xref\"" assert_raise Mix.Error, message, fn -> assert Mix.Task.run("xref", ["callers"]) == :error end end) end test "callers: gives nice error for quotable but invalid callers spec" do in_fixture("no_mixfile", fn -> message = "xref callers CALLEE expects Module, Module.function, or Module.function/arity, got: Module.func(arg)" assert_raise Mix.Error, message, fn -> Mix.Task.run("xref", ["callers", "Module.func(arg)"]) end end) end test "callers: gives nice error for unquotable callers spec" do in_fixture("no_mixfile", fn -> message = "xref callers CALLEE expects Module, Module.function, or Module.function/arity, got: %" assert_raise Mix.Error, message, fn -> Mix.Task.run("xref", ["callers", "%"]) end end) end defp assert_callers(callee, files, expected) do in_fixture("no_mixfile", fn -> for {file, contents} <- files do File.write!(file, contents) end capture_io(:stderr, fn -> assert Mix.Task.run("xref", ["callers", callee]) == :ok end) assert ^expected = receive_until_no_messages([]) end) end ## Graph test "graph: basic usage" do assert_graph(""" lib/a.ex └── lib/b.ex └── lib/a.ex lib/b.ex lib/c.ex lib/d.ex └── lib/a.ex (compile) """) end test "graph: stats" do assert_graph(["--format", "stats"], """ Tracked files: 4 (nodes) Compile dependencies: 1 (edges) Structs dependencies: 0 (edges) Runtime dependencies: 2 (edges) Top 4 files with most outgoing dependencies: * lib/d.ex (1) * lib/b.ex (1) * lib/a.ex (1) * lib/c.ex (0) Top 2 files with most incoming dependencies: * lib/a.ex (2) * lib/b.ex (1) """) end test "graph: exclude many" do assert_graph(~w[--exclude lib/c.ex --exclude lib/b.ex], """ lib/a.ex lib/d.ex └── lib/a.ex (compile) """) end test "graph: exclude one" do assert_graph(~w[--exclude lib/d.ex], """ lib/a.ex └── lib/b.ex └── lib/a.ex lib/b.ex lib/c.ex """) end test "graph: source" do assert_graph(~w[--source lib/a.ex], """ lib/b.ex └── lib/a.ex └── lib/b.ex """) end test "graph: only nodes" do assert_graph(~w[--only-nodes], """ lib/a.ex lib/b.ex lib/c.ex lib/d.ex """) end test "graph: filter by compile label" do assert_graph(~w[--label compile], """ lib/a.ex lib/b.ex lib/c.ex lib/d.ex └── lib/a.ex (compile) """) end test "graph: filter by runtime label" do assert_graph(~w[--label runtime], """ lib/a.ex └── lib/b.ex └── lib/a.ex lib/b.ex lib/c.ex lib/d.ex """) end test "graph: invalid source" do assert_raise Mix.Error, "Source could not be found: lib/a2.ex", fn -> assert_graph(~w[--source lib/a2.ex], "") end end test "graph: sink" do assert_graph(~w[--sink lib/b.ex], """ lib/a.ex └── lib/b.ex └── lib/a.ex lib/d.ex └── lib/a.ex (compile) """) end test "graph: invalid sink" do assert_raise Mix.Error, "Sink could not be found: lib/b2.ex", fn -> assert_graph(~w[--sink lib/b2.ex], "") end end test "graph: sink and source is error" do assert_raise Mix.Error, "mix xref graph expects only one of --source and --sink", fn -> assert_graph(~w[--source lib/a.ex --sink lib/b.ex], "") end end test "graph: with dynamic module" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ B.define() """) File.write!("lib/b.ex", """ defmodule B do def define do defmodule A do end end end """) assert Mix.Task.run("xref", ["graph", "--format", "dot"]) == :ok assert File.read!("xref_graph.dot") === """ digraph "xref graph" { "lib/a.ex" "lib/a.ex" -> "lib/b.ex" [label="(compile)"] "lib/b.ex" } """ end) end test "graph: with struct" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def fun do %B{} end end """) File.write!("lib/b.ex", """ defmodule B do defstruct [] end """) assert Mix.Task.run("xref", ["graph", "--format", "dot"]) == :ok assert File.read!("xref_graph.dot") === """ digraph "xref graph" { "lib/a.ex" "lib/a.ex" -> "lib/b.ex" [label="(struct)"] "lib/b.ex" } """ end) end test "graph: with mixed cyclic dependencies" do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A.Behaviour do @callback foo :: :foo end defmodule A do B def foo do :foo end end """) File.write!("lib/b.ex", """ defmodule B do # Let's also test that we track literal atom behaviours @behaviour :"Elixir.A.Behaviour" def foo do A.foo end end """) assert Mix.Task.run("xref", ["graph", "--format", "dot"]) == :ok assert File.read!("xref_graph.dot") === """ digraph "xref graph" { "lib/a.ex" "lib/a.ex" -> "lib/b.ex" [label="(compile)"] "lib/b.ex" -> "lib/a.ex" [label="(compile)"] "lib/b.ex" } """ end) end defp assert_graph(opts \\ [], expected) do in_fixture("no_mixfile", fn -> File.write!("lib/a.ex", """ defmodule A do def a do B.a end def b, do: :ok end """) File.write!("lib/b.ex", """ defmodule B do def a do A.a B.a end end """) File.write!("lib/c.ex", """ defmodule C do end """) File.write!("lib/d.ex", """ defmodule :d do A.b end """) assert Mix.Task.run("xref", opts ++ ["graph"]) == :ok assert "Compiling 4 files (.ex)\nGenerated sample app\n" <> result = receive_until_no_messages([]) assert normalize_graph_output(result) == normalize_graph_output(expected) end) end defp normalize_graph_output(graph) do String.replace(graph, "└──", "`--") end describe "inside umbrellas" do test "generates reports considering siblings" do Mix.Project.pop() in_fixture("umbrella_dep/deps/umbrella", fn -> Mix.Project.in_project(:bar, "apps/bar", fn _ -> File.write!("lib/bar.ex", """ defmodule Bar do def bar do Foo.foo end end """) Mix.Task.run("compile") Mix.shell().flush() Mix.Tasks.Xref.run(["graph", "--format", "stats", "--include-siblings"]) assert receive_until_no_messages([]) == """ Tracked files: 2 (nodes) Compile dependencies: 0 (edges) Structs dependencies: 0 (edges) Runtime dependencies: 1 (edges) Top 2 files with most outgoing dependencies: * lib/bar.ex (1) * lib/foo.ex (0) Top 1 files with most incoming dependencies: * lib/foo.ex (1) """ Mix.Tasks.Xref.run(["callers", "Foo.foo"]) assert receive_until_no_messages([]) == """ lib/bar.ex:3: Foo.foo/0 """ end) end) end end ## Helpers defp receive_until_no_messages(acc) do receive do {:mix_shell, :info, [line]} -> receive_until_no_messages([acc, line | "\n"]) after 0 -> IO.iodata_to_binary(acc) end end defp generate_files(files) do for {file, contents} <- files do File.write!(file, contents) end end end
23.364146
110
0.513488
f76dd32f995e52a786b6b1853a9514c88ceb2cae
3,948
ex
Elixir
clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/api/projects.ex
kaaboaye/elixir-google-api
1896784c4342151fd25becd089a5beb323eff567
[ "Apache-2.0" ]
null
null
null
clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/api/projects.ex
kaaboaye/elixir-google-api
1896784c4342151fd25becd089a5beb323eff567
[ "Apache-2.0" ]
null
null
null
clients/firebase_hosting/lib/google_api/firebase_hosting/v1beta1/api/projects.ex
kaaboaye/elixir-google-api
1896784c4342151fd25becd089a5beb323eff567
[ "Apache-2.0" ]
null
null
null
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # NOTE: This file is auto generated by the elixir code generator program. # Do not edit this file manually. defmodule GoogleApi.FirebaseHosting.V1beta1.Api.Projects do @moduledoc """ API calls for all endpoints tagged `Projects`. """ alias GoogleApi.FirebaseHosting.V1beta1.Connection alias GoogleApi.Gax.{Request, Response} @library_version Mix.Project.config() |> Keyword.get(:version, "") @doc """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. ## Parameters * `connection` (*type:* `GoogleApi.FirebaseHosting.V1beta1.Connection.t`) - Connection to server * `name` (*type:* `String.t`) - The name of the operation resource. * `optional_params` (*type:* `keyword()`) - Optional parameters * `:"$.xgafv"` (*type:* `String.t`) - V1 error format. * `:access_token` (*type:* `String.t`) - OAuth access token. * `:alt` (*type:* `String.t`) - Data format for response. * `:callback` (*type:* `String.t`) - JSONP * `:fields` (*type:* `String.t`) - Selector specifying which fields to include in a partial response. * `:key` (*type:* `String.t`) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. * `:oauth_token` (*type:* `String.t`) - OAuth 2.0 token for the current user. * `:prettyPrint` (*type:* `boolean()`) - Returns response with indentations and line breaks. * `:quotaUser` (*type:* `String.t`) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. * `:uploadType` (*type:* `String.t`) - Legacy upload protocol for media (e.g. "media", "multipart"). * `:upload_protocol` (*type:* `String.t`) - Upload protocol for media (e.g. "raw", "multipart"). * `opts` (*type:* `keyword()`) - Call options ## Returns * `{:ok, %GoogleApi.FirebaseHosting.V1beta1.Model.Operation{}}` on success * `{:error, info}` on failure """ @spec firebasehosting_projects_operations_get( Tesla.Env.client(), String.t(), keyword(), keyword() ) :: {:ok, GoogleApi.FirebaseHosting.V1beta1.Model.Operation.t()} | {:ok, Tesla.Env.t()} | {:error, Tesla.Env.t()} def firebasehosting_projects_operations_get(connection, name, optional_params \\ [], opts \\ []) do optional_params_config = %{ :"$.xgafv" => :query, :access_token => :query, :alt => :query, :callback => :query, :fields => :query, :key => :query, :oauth_token => :query, :prettyPrint => :query, :quotaUser => :query, :uploadType => :query, :upload_protocol => :query } request = Request.new() |> Request.method(:get) |> Request.url("/v1beta1/{+name}", %{ "name" => URI.encode(name, &URI.char_unreserved?/1) }) |> Request.add_optional_params(optional_params_config, optional_params) |> Request.library_version(@library_version) connection |> Connection.execute(request) |> Response.decode(opts ++ [struct: %GoogleApi.FirebaseHosting.V1beta1.Model.Operation{}]) end end
42
196
0.650963
f76e0bd678d0f66655eee1f935aa593eabd6b6de
2,026
ex
Elixir
lib/api/graphql/input_types.ex
nunopolonia/psc-api
2e358503851cc04cdaa89201a3f56586f8746736
[ "MIT" ]
1
2017-09-10T23:51:40.000Z
2017-09-10T23:51:40.000Z
lib/api/graphql/input_types.ex
nunopolonia/psc-api
2e358503851cc04cdaa89201a3f56586f8746736
[ "MIT" ]
24
2018-03-14T18:17:00.000Z
2021-03-01T07:47:53.000Z
lib/api/graphql/input_types.ex
portosummerofcode/psc-api
2e358503851cc04cdaa89201a3f56586f8746736
[ "MIT" ]
null
null
null
defmodule Api.GraphQL.InputTypes do use Absinthe.Schema.Notation input_object :ai_competition_bot_input do field :title, non_null(:string) field :sdk, non_null(:string) field :source_code, non_null(:string) end input_object :competition_input do field :name, non_null(:string) field :status, non_null(:string) field :is_default, :boolean end input_object :team_input do field :name, non_null(:string) field :project_name, :string field :project_desc, :string field :technologies, :array field :applied, :boolean field :prize_preference, :string # stringified array end input_object :user_input do field :name, :string field :email, :string field :birthday, :date field :employment_status, :string field :company, :string field :college, :string field :github_handle, :string field :twitter_handle, :string field :linkedin_url, :string field :bio, :string field :role, :string field :tshirt_size, :string field :data_usage_consent, :boolean field :spam_consent, :boolean field :share_consent, :boolean end input_object :workshop_input do field :slug, non_null(:string) field :short_date, non_null(:string) field :short_speaker, non_null(:string) field :name, non_null(:string) field :summary, non_null(:string) field :description, non_null(:string) field :speaker, non_null(:string) field :participant_limit, non_null(:integer) field :year, non_null(:integer) field :speaker_image, :string field :banner_image, :string end input_object :flyby_input do field :name, non_null(:string) field :email, non_null(:string) field :time, non_null(:integer) end input_object :suffrage_input do field :name, non_null(:string) field :slug, non_null(:string) end input_object :email_input do field :name, non_null(:string) field :subject, non_null(:string) field :title, :string field :content, :string end end
27.013333
56
0.698914
f76e3aadfca3b869b31042814aaa370b7a882266
1,029
ex
Elixir
lib/accent/schemas/collaborator.ex
samuelnygaard/accent
db753badab1d885397b48a42ac3fb43024345467
[ "BSD-3-Clause" ]
1
2020-07-01T16:08:34.000Z
2020-07-01T16:08:34.000Z
lib/accent/schemas/collaborator.ex
samuelnygaard/accent
db753badab1d885397b48a42ac3fb43024345467
[ "BSD-3-Clause" ]
2
2021-09-28T05:37:00.000Z
2022-02-26T10:10:15.000Z
lib/accent/schemas/collaborator.ex
samuelnygaard/accent
db753badab1d885397b48a42ac3fb43024345467
[ "BSD-3-Clause" ]
null
null
null
defmodule Accent.Collaborator do use Accent.Schema require Accent.Role schema "collaborators" do field(:email, :string) field(:role, :string) belongs_to(:user, Accent.User) belongs_to(:assigner, Accent.User) belongs_to(:project, Accent.Project) timestamps() end @required_fields ~w(email assigner_id role project_id)a @optional_fields ~w(user_id)a @possible_roles Accent.Role.slugs() def create_changeset(model, params) do model |> cast(params, @required_fields ++ @optional_fields) |> validate_required(@required_fields) |> validate_format(:email, ~r/.+@.+/) |> downcase_email(params) |> validate_inclusion(:role, @possible_roles) end def update_changeset(model, params) do model |> cast(params, [:role]) |> validate_inclusion(:role, @possible_roles) end defp downcase_email(changeset, %{"email" => email}) do put_change(changeset, :email, String.downcase(email)) end defp downcase_email(changeset, _params), do: changeset end
24.5
57
0.699708
f76e4a325d2b24a75fc3fbce1323c6a092527535
68
exs
Elixir
test/bitflyex_doc_test.exs
piacere-ex/bitflyex
ba07ad1474021c20c1816a7e803c248dc2177a3c
[ "Apache-2.0" ]
3
2018-01-12T10:18:13.000Z
2018-07-28T15:58:43.000Z
test/bitflyex_doc_test.exs
piacerex/bitflyex
ba07ad1474021c20c1816a7e803c248dc2177a3c
[ "Apache-2.0" ]
null
null
null
test/bitflyex_doc_test.exs
piacerex/bitflyex
ba07ad1474021c20c1816a7e803c248dc2177a3c
[ "Apache-2.0" ]
1
2018-03-02T11:03:33.000Z
2018-03-02T11:03:33.000Z
defmodule BitFlyexDocTest do use PowerAssert doctest BitFlyex end
13.6
28
0.852941
f76e662f4d7fc177ff1b57a750251823c150e6a8
34,997
ex
Elixir
lib/elixir/lib/kernel/typespec.ex
paulswartz/elixir
921f17e21ddfc1a50eaa4ce49fc7cc0c93822e5c
[ "Apache-2.0" ]
1
2017-07-25T21:46:25.000Z
2017-07-25T21:46:25.000Z
lib/elixir/lib/kernel/typespec.ex
paulswartz/elixir
921f17e21ddfc1a50eaa4ce49fc7cc0c93822e5c
[ "Apache-2.0" ]
null
null
null
lib/elixir/lib/kernel/typespec.ex
paulswartz/elixir
921f17e21ddfc1a50eaa4ce49fc7cc0c93822e5c
[ "Apache-2.0" ]
1
2017-07-25T21:46:48.000Z
2017-07-25T21:46:48.000Z
defmodule Kernel.Typespec do @moduledoc false @doc """ Defines a type. This macro is responsible for handling the attribute `@type`. ## Examples @type my_type :: atom """ defmacro deftype(type) do pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.deftype(:type, unquote(Macro.escape(type, unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos)) end end @doc """ Defines an opaque type. This macro is responsible for handling the attribute `@opaque`. ## Examples @opaque my_type :: atom """ defmacro defopaque(type) do pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.deftype(:opaque, unquote(Macro.escape(type, unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos)) end end @doc """ Defines a private type. This macro is responsible for handling the attribute `@typep`. ## Examples @typep my_type :: atom """ defmacro deftypep(type) do pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.deftype(:typep, unquote(Macro.escape(type, unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos)) end end @doc """ Defines a spec. This macro is responsible for handling the attribute `@spec`. ## Examples @spec add(number, number) :: number """ defmacro defspec(spec) do pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.defspec(:spec, unquote(Macro.escape(spec, unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos)) end end @doc """ Defines a callback. This macro is responsible for handling the attribute `@callback`. ## Examples @callback add(number, number) :: number """ defmacro defcallback(spec) do pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.defspec(:callback, unquote(Macro.escape(spec, unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos)) end end @doc """ Defines a macro callback. This macro is responsible for handling the attribute `@macrocallback`. ## Examples @macrocallback add(number, number) :: Macro.t """ defmacro defmacrocallback(spec) do pos = :elixir_locals.cache_env(__CALLER__) %{line: line, file: file, module: module} = __CALLER__ quote do Kernel.Typespec.defspec(:macrocallback, unquote(Macro.escape(spec, unquote: true)), unquote(line), unquote(file), unquote(module), unquote(pos)) end end @doc """ Returns `true` if the current module defines a given type (private, opaque or not). This function is only available for modules being compiled. """ @spec defines_type?(module, atom, arity) :: boolean def defines_type?(module, name, arity) when is_atom(module) and is_atom(name) and arity in 0..255 do finder = fn {_kind, expr, _caller} -> type_to_signature(expr) == {name, arity} end :lists.any(finder, Module.get_attribute(module, :type)) or :lists.any(finder, Module.get_attribute(module, :opaque)) end @doc """ Returns `true` if the current module defines a given spec. This function is only available for modules being compiled. """ @spec defines_spec?(module, atom, arity) :: boolean def defines_spec?(module, name, arity) when is_atom(module) and is_atom(name) and arity in 0..255 do finder = fn {_kind, expr, _caller} -> spec_to_signature(expr) == {name, arity} end :lists.any(finder, Module.get_attribute(module, :spec)) end @doc """ Returns `true` if the current module defines a callback. This function is only available for modules being compiled. """ @spec defines_callback?(module, atom, arity) :: boolean def defines_callback?(module, name, arity) when is_atom(module) and is_atom(name) and arity in 0..255 do finder = fn {_kind, expr, _caller} -> spec_to_signature(expr) == {name, arity} end :lists.any(finder, Module.get_attribute(module, :callback)) end @doc """ Converts a spec clause back to Elixir AST. """ @spec spec_to_ast(atom, tuple) :: {atom, keyword, [Macro.t]} def spec_to_ast(name, spec) def spec_to_ast(name, {:type, line, :fun, [{:type, _, :product, args}, result]}) when is_atom(name) do meta = [line: line] body = {name, meta, Enum.map(args, &typespec_to_ast/1)} vars = args ++ [result] |> Enum.flat_map(&collect_vars/1) |> Enum.uniq |> Enum.map(&{&1, {:var, meta, nil}}) spec = {:::, meta, [body, typespec_to_ast(result)]} if vars == [] do spec else {:when, meta, [spec, vars]} end end def spec_to_ast(name, {:type, line, :fun, []}) when is_atom(name) do {:::, [line: line], [{name, [line: line], []}, quote(do: term)]} end def spec_to_ast(name, {:type, line, :bounded_fun, [{:type, _, :fun, [{:type, _, :product, args}, result]}, constraints]}) when is_atom(name) do guards = for {:type, _, :constraint, [{:atom, _, :is_subtype}, [{:var, _, var}, type]]} <- constraints do {var, typespec_to_ast(type)} end meta = [line: line] vars = args ++ [result] |> Enum.flat_map(&collect_vars/1) |> Enum.uniq |> Kernel.--(Keyword.keys(guards)) |> Enum.map(&{&1, {:var, meta, nil}}) args = for arg <- args, do: typespec_to_ast(arg) {:when, meta, [ {:::, meta, [{name, [line: line], args}, typespec_to_ast(result)]}, guards ++ vars ]} end @doc """ Converts a type clause back to Elixir AST. """ def type_to_ast(type) def type_to_ast({{:record, record}, fields, args}) when is_atom(record) do fields = for field <- fields, do: typespec_to_ast(field) args = for arg <- args, do: typespec_to_ast(arg) type = {:{}, [], [record | fields]} quote do: unquote(record)(unquote_splicing(args)) :: unquote(type) end def type_to_ast({name, type, args}) when is_atom(name) do args = for arg <- args, do: typespec_to_ast(arg) quote do: unquote(name)(unquote_splicing(args)) :: unquote(typespec_to_ast(type)) end @doc false # TODO: Remove on v2.0 def beam_typedocs(module) when is_atom(module) or is_binary(module) do IO.write :stderr, "Kernel.Typespec.beam_typedocs/1 is deprecated, please use Code.get_docs/2 instead\n" <> Exception.format_stacktrace if docs = Code.get_docs(module, :type_docs) do for {tuple, _, _, doc} <- docs, do: {tuple, doc} end end @doc """ Returns all types available from the module's BEAM code. The result is returned as a list of tuples where the first element is the type (`:typep`, `:type` and `:opaque`). The module must have a corresponding BEAM file which can be located by the runtime system. """ @spec beam_types(module | binary) :: [tuple] | nil def beam_types(module) when is_atom(module) or is_binary(module) do case abstract_code(module) do {:ok, abstract_code} -> exported_types = for {:attribute, _, :export_type, types} <- abstract_code, do: types exported_types = :lists.flatten(exported_types) for {:attribute, _, kind, {name, _, args} = type} <- abstract_code, kind in [:opaque, :type] do cond do kind == :opaque -> {:opaque, type} {name, length(args)} in exported_types -> {:type, type} true -> {:typep, type} end end _ -> nil end end @doc """ Returns all specs available from the module's BEAM code. The result is returned as a list of tuples where the first element is spec name and arity and the second is the spec. The module must have a corresponding BEAM file which can be located by the runtime system. """ @spec beam_specs(module | binary) :: [tuple] | nil def beam_specs(module) when is_atom(module) or is_binary(module) do from_abstract_code(module, :spec) end @doc """ Returns all callbacks available from the module's BEAM code. The result is returned as a list of tuples where the first element is spec name and arity and the second is the spec. The module must have a corresponding BEAM file which can be located by the runtime system. """ @spec beam_callbacks(module | binary) :: [tuple] | nil def beam_callbacks(module) when is_atom(module) or is_binary(module) do from_abstract_code(module, :callback) end defp from_abstract_code(module, kind) do case abstract_code(module) do {:ok, abstract_code} -> for {:attribute, _, abs_kind, value} <- abstract_code, kind == abs_kind, do: value :error -> nil end end defp abstract_code(module) do case :beam_lib.chunks(abstract_code_beam(module), [:abstract_code]) do {:ok, {_, [{:abstract_code, {_raw_abstract_v1, abstract_code}}]}} -> {:ok, abstract_code} _ -> :error end end defp abstract_code_beam(module) when is_atom(module) do case :code.get_object_code(module) do {^module, beam, _filename} -> beam :error -> module end end defp abstract_code_beam(binary) when is_binary(binary) do binary end ## Helpers @doc false def spec_to_signature({:when, _, [spec, _]}), do: type_to_signature(spec) def spec_to_signature(other), do: type_to_signature(other) @doc false def type_to_signature({:::, _, [{name, _, context}, _]}) when is_atom(name) and is_atom(context), do: {name, 0} def type_to_signature({:::, _, [{name, _, args}, _]}) when is_atom(name), do: {name, length(args)} def type_to_signature(_), do: :error ## Macro callbacks @doc false def defspec(kind, expr, line, file, module, pos) when kind in [:callback, :macrocallback] do case spec_to_signature(expr) do {name, arity} -> store_callbackdoc(line, file, module, kind, name, arity) :error -> :error end Module.store_typespec(module, kind, {kind, expr, pos}) end @doc false def defspec(kind, expr, _line, _file, module, pos) do Module.store_typespec(module, kind, {kind, expr, pos}) end defp store_callbackdoc(line, _file, module, kind, name, arity) do table = :elixir_module.data_table(module) {line, doc} = get_doc_info(table, :doc, line) :ets.insert(table, {{:callbackdoc, {name, arity}}, line, kind, doc}) end defp get_doc_info(table, attr, line) do case :ets.take(table, attr) do [{^attr, {line, doc}, _, _}] -> {line, doc} [] -> {line, nil} end end @doc false def deftype(kind, expr, line, file, module, pos) do case type_to_signature(expr) do {name, arity} -> store_typedoc(line, file, module, kind, name, arity) :error -> :error end Module.store_typespec(module, kind, {kind, expr, pos}) end defp store_typedoc(line, file, module, kind, name, arity) do table = :elixir_module.data_table(module) {line, doc} = get_doc_info(table, :typedoc, line) if kind == :typep && doc do :elixir_errors.warn(line, file, "type #{name}/#{arity} is private, " <> "@typedoc's are always discarded for private types") end :ets.insert(table, {{:typedoc, {name, arity}}, line, kind, doc}) end ## Translation from Elixir AST to typespec AST @doc false def translate_type(kind, {:::, _, [{name, _, args}, definition]}, pos) when is_atom(name) and name != ::: do caller = :elixir_locals.get_cached_env(pos) args = if is_atom(args) do [] else for(arg <- args, do: variable(arg)) end vars = for {:var, _, var} <- args, do: var spec = typespec(definition, vars, caller) vars = for {:var, _, _} = var <- args, do: var type = {name, spec, vars} arity = length(vars) {kind, export} = case kind do :type -> {:type, true} :typep -> {:type, false} :opaque -> {:opaque, true} end if builtin_type?(name, arity) do compile_error caller, "type #{name}/#{arity} is a builtin type and it cannot be redefined" end {{kind, {name, arity}, type}, caller.line, export} end def translate_type(_kind, other, pos) do caller = :elixir_locals.get_cached_env(pos) type_spec = Macro.to_string(other) compile_error caller, "invalid type specification: #{type_spec}" end defp builtin_type?(:as_boolean, 1), do: true defp builtin_type?(:struct, 0), do: true defp builtin_type?(:charlist, 0), do: true # TODO: Remove char_list type by 2.0 defp builtin_type?(:char_list, 0), do: true defp builtin_type?(:nonempty_charlist, 0), do: true defp builtin_type?(:keyword, 0), do: true defp builtin_type?(:keyword, 1), do: true defp builtin_type?(name, arity), do: :erl_internal.is_type(name, arity) @doc false def translate_spec(kind, {:when, _meta, [spec, guard]}, pos) do caller = :elixir_locals.get_cached_env(pos) translate_spec(kind, spec, guard, caller) end def translate_spec(kind, spec, pos) do caller = :elixir_locals.get_cached_env(pos) translate_spec(kind, spec, [], caller) end defp translate_spec(kind, {:::, meta, [{name, _, args}, return]}, guard, caller) when is_atom(name) and name != ::: do translate_spec(kind, meta, name, args, return, guard, caller) end defp translate_spec(_kind, {name, _meta, _args} = spec, _guard, caller) when is_atom(name) and name != ::: do spec = Macro.to_string(spec) compile_error caller, "type specification missing return type: #{spec}" end defp translate_spec(_kind, spec, _guard, caller) do spec = Macro.to_string(spec) compile_error caller, "invalid type specification: #{spec}" end defp translate_spec(kind, meta, name, args, return, guard, caller) when is_atom(args), do: translate_spec(kind, meta, name, [], return, guard, caller) defp translate_spec(kind, meta, name, args, return, guard, caller) do ensure_no_defaults!(args) unless Keyword.keyword?(guard) do compile_error caller, "expected keywords as guard in type specification, " <> "got: #{Macro.to_string(guard)}" end vars = Keyword.keys(guard) spec = {:type, line(meta), :fun, fn_args(meta, args, return, vars, caller)} spec = case guard_to_constraints(guard, vars, meta, caller) do [] -> spec constraints -> {:type, line(meta), :bounded_fun, [spec, constraints]} end arity = length(args) {{kind, {name, arity}, spec}, caller.line} end defp ensure_no_defaults!(args) do :lists.foreach fn {:::, _, [left, right]} -> ensure_not_default(left) ensure_not_default(right) left other -> ensure_not_default(other) other end, args end defp ensure_not_default({:\\, _, [_, _]}) do raise ArgumentError, "default arguments \\\\ not supported in type spec" end defp ensure_not_default(_), do: :ok defp guard_to_constraints(guard, vars, meta, caller) do line = line(meta) :lists.foldl(fn {_name, {:var, _, context}}, acc when is_atom(context) -> acc {name, type}, acc -> constraint = [{:atom, line, :is_subtype}, [{:var, line, name}, typespec(type, vars, caller)]] type = {:type, line, :constraint, constraint} [type | acc] end, [], guard) |> :lists.reverse end ## To AST conversion defp collect_vars({:ann_type, _line, args}) when is_list(args) do [] end defp collect_vars({:type, _line, _kind, args}) when is_list(args) do Enum.flat_map(args, &collect_vars/1) end defp collect_vars({:remote_type, _line, args}) when is_list(args) do Enum.flat_map(args, &collect_vars/1) end defp collect_vars({:typed_record_field, _line, type}) do collect_vars(type) end defp collect_vars({:paren_type, _line, [type]}) do collect_vars(type) end defp collect_vars({:var, _line, var}) do [erl_to_ex_var(var)] end defp collect_vars(_) do [] end defp typespec_to_ast({:user_type, line, name, args}) do typespec_to_ast({:type, line, name, args}) end defp typespec_to_ast({:type, line, :tuple, :any}) do {:tuple, [line: line], []} end defp typespec_to_ast({:type, line, :tuple, args}) do args = for arg <- args, do: typespec_to_ast(arg) {:{}, [line: line], args} end defp typespec_to_ast({:type, _line, :list, [{:type, _, :union, unions} = arg]}) do case unpack_typespec_kw(unions, []) do {:ok, ast} -> ast :error -> [typespec_to_ast(arg)] end end defp typespec_to_ast({:type, line, :list, []}) do {:list, [line: line], []} end defp typespec_to_ast({:type, _line, :list, [arg]}) do [typespec_to_ast(arg)] end defp typespec_to_ast({:type, line, :nonempty_list, []}) do [{:..., [line: line], nil}] end defp typespec_to_ast({:type, line, :nonempty_list, [arg]}) do [typespec_to_ast(arg), {:..., [line: line], nil}] end defp typespec_to_ast({:type, line, :map, :any}) do {:map, [line: line], []} end defp typespec_to_ast({:type, line, :map, fields}) do fields = Enum.map fields, fn {:type, _, :map_field_assoc, :any} -> {{:optional, [], [{:any, [], []}]}, {:any, [], []}} {:type, _, :map_field_exact, [{:atom, _, k}, v]} -> {k, typespec_to_ast(v)} {:type, _, :map_field_exact, [k, v]} -> {{:required, [], [typespec_to_ast(k)]}, typespec_to_ast(v)} {:type, _, :map_field_assoc, [k, v]} -> {{:optional, [], [typespec_to_ast(k)]}, typespec_to_ast(v)} end {struct, fields} = Keyword.pop(fields, :__struct__) map = {:%{}, [line: line], fields} if struct do {:%, [line: line], [struct, map]} else map end end defp typespec_to_ast({:type, line, :binary, [arg1, arg2]}) do [arg1, arg2] = for arg <- [arg1, arg2], do: typespec_to_ast(arg) case {typespec_to_ast(arg1), typespec_to_ast(arg2)} do {arg1, 0} -> quote line: line, do: <<_ :: unquote(arg1)>> {0, arg2} -> quote line: line, do: <<_ :: _ * unquote(arg2)>> {arg1, arg2} -> quote line: line, do: <<_ :: unquote(arg1), _ :: _ * unquote(arg2)>> end end defp typespec_to_ast({:type, line, :union, args}) do args = for arg <- args, do: typespec_to_ast(arg) Enum.reduce Enum.reverse(args), fn(arg, expr) -> {:|, [line: line], [arg, expr]} end end defp typespec_to_ast({:type, line, :fun, [{:type, _, :product, args}, result]}) do args = for arg <- args, do: typespec_to_ast(arg) [{:->, [line: line], [args, typespec_to_ast(result)]}] end defp typespec_to_ast({:type, line, :fun, [args, result]}) do [{:->, [line: line], [[typespec_to_ast(args)], typespec_to_ast(result)]}] end defp typespec_to_ast({:type, line, :fun, []}) do typespec_to_ast({:type, line, :fun, [{:type, line, :any}, {:type, line, :any, []}]}) end defp typespec_to_ast({:type, line, :range, [left, right]}) do {:.., [line: line], [typespec_to_ast(left), typespec_to_ast(right)]} end defp typespec_to_ast({:type, _line, nil, []}) do [] end defp typespec_to_ast({:type, line, name, args}) do args = for arg <- args, do: typespec_to_ast(arg) {name, [line: line], args} end defp typespec_to_ast({:var, line, var}) do {erl_to_ex_var(var), line, nil} end defp typespec_to_ast({:op, line, op, arg}) do {op, [line: line], [typespec_to_ast(arg)]} end # Special shortcut(s) # TODO: Remove char_list type by 2.0 defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, type}, []]}) when type in [:charlist, :char_list] do typespec_to_ast({:type, line, :charlist, []}) end defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, :nonempty_charlist}, []]}) do typespec_to_ast({:type, line, :nonempty_charlist, []}) end defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, :struct}, []]}) do typespec_to_ast({:type, line, :struct, []}) end defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]]}) do typespec_to_ast({:type, line, :as_boolean, [arg]}) end defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, :keyword}, args]}) do typespec_to_ast({:type, line, :keyword, args}) end defp typespec_to_ast({:remote_type, line, [mod, name, args]}) do args = for arg <- args, do: typespec_to_ast(arg) dot = {:., [line: line], [typespec_to_ast(mod), typespec_to_ast(name)]} {dot, [line: line], args} end defp typespec_to_ast({:ann_type, line, [var, type]}) do {:::, [line: line], [typespec_to_ast(var), typespec_to_ast(type)]} end defp typespec_to_ast({:typed_record_field, {:record_field, line, {:atom, line1, name}}, type}) do typespec_to_ast({:ann_type, line, [{:var, line1, name}, type]}) end defp typespec_to_ast({:type, _, :any}) do quote do: ... end defp typespec_to_ast({:paren_type, _, [type]}) do typespec_to_ast(type) end defp typespec_to_ast({t, _line, atom}) when is_atom(t) do atom end defp typespec_to_ast(other), do: other defp erl_to_ex_var(var) do case Atom.to_string(var) do <<"_", c::binary-1, rest::binary>> -> String.to_atom("_#{String.downcase(c)}#{rest}") <<c::binary-1, rest::binary>> -> String.to_atom("#{String.downcase(c)}#{rest}") end end ## To typespec conversion defp line(meta) do case :lists.keyfind(:line, 1, meta) do {:line, line} -> line false -> 0 end end # Handle unions defp typespec({:|, meta, [_, _]} = exprs, vars, caller) do exprs = collect_union(exprs) union = for e <- exprs, do: typespec(e, vars, caller) {:type, line(meta), :union, union} end # Handle binaries defp typespec({:<<>>, meta, []}, _, _) do {:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(meta), 0}]} end defp typespec({:<<>>, meta, [{:::, unit_meta, [{:_, _, ctx1}, {:*, _, [{:_, _, ctx2}, unit]}]}]}, _, _) when is_atom(ctx1) and is_atom(ctx2) and is_integer(unit) do {:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(unit_meta), unit}]} end defp typespec({:<<>>, meta, [{:::, size_meta, [{:_, _, ctx}, size]}]}, _, _) when is_atom(ctx) and is_integer(size) do {:type, line(meta), :binary, [{:integer, line(size_meta), size}, {:integer, line(meta), 0}]} end defp typespec({:<<>>, meta, [{:::, size_meta, [{:_, _, ctx1}, size]}, {:::, unit_meta, [{:_, _, ctx2}, {:*, _, [{:_, _, ctx3}, unit]}]}]}, _, _) when is_atom(ctx1) and is_atom(ctx2) and is_atom(ctx3) and is_integer(size) and is_integer(unit) do {:type, line(meta), :binary, [{:integer, line(size_meta), size}, {:integer, line(unit_meta), unit}]} end ## Handle maps and structs defp typespec({:map, meta, args}, _vars, _caller) when args == [] or is_atom(args) do {:type, line(meta), :map, :any} end defp typespec({:%{}, meta, fields} = map, vars, caller) do fields = :lists.map(fn {k, v} when is_atom(k) -> {:type, line(meta), :map_field_exact, [typespec(k, vars, caller), typespec(v, vars, caller)]} {{:required, meta2, [k]}, v} -> {:type, line(meta2), :map_field_exact, [typespec(k, vars, caller), typespec(v, vars, caller)]} {{:optional, meta2, [k]}, v} -> {:type, line(meta2), :map_field_assoc, [typespec(k, vars, caller), typespec(v, vars, caller)]} {k, v} -> # TODO: Warn on Elixir v1.8 (since v1.6 is the first version to support 19+) # warning = # "invalid map specification. %{foo => bar} is deprecated in favor of " <> # "%{required(foo) => bar} and %{optional(foo) => bar}." # :elixir_errors.warn(caller.line, caller.file, warning) {:type, line(meta), :map_field_assoc, [typespec(k, vars, caller), typespec(v, vars, caller)]} {:|, _, [_, _]} -> compile_error(caller, "invalid map specification. When using the | operator in the map key, " <> "make sure to wrap the key type in parentheses: #{Macro.to_string(map)}") _ -> compile_error(caller, "invalid map specification: #{Macro.to_string(map)}") end, fields) {:type, line(meta), :map, fields} end defp typespec({:%, _, [name, {:%{}, meta, fields}]}, vars, caller) do # We cannot set a function name to avoid tracking # as a compile time dependency, because for structs it actually is one. module = Macro.expand(name, caller) struct = if module == caller.module do Module.get_attribute(module, :struct) || compile_error(caller, "struct is not defined for #{Macro.to_string(name)}") else module.__struct__ end struct = struct |> Map.from_struct |> Map.to_list unless Keyword.keyword?(fields) do compile_error(caller, "expected key-value pairs in struct #{Macro.to_string(name)}") end types = :lists.map(fn {field, _} -> {field, Keyword.get(fields, field, quote(do: term()))} end, struct) :lists.foreach(fn {field, _} -> unless Keyword.has_key?(struct, field) do compile_error(caller, "undefined field #{field} on struct #{Macro.to_string(name)}") end end, fields) typespec({:%{}, meta, [__struct__: module] ++ types}, vars, caller) end # Handle records defp typespec({:record, meta, [atom]}, vars, caller) do typespec({:record, meta, [atom, []]}, vars, caller) end defp typespec({:record, meta, [atom, fields]}, vars, caller) do # We cannot set a function name to avoid tracking # as a compile time dependency because for records it actually is one. case Macro.expand({atom, [], [{atom, [], []}]}, caller) do keyword when is_list(keyword) -> types = :lists.map(fn {field, _} -> Keyword.get(fields, field, quote(do: term())) end, keyword) :lists.foreach(fn {field, _} -> unless Keyword.has_key?(keyword, field) do compile_error(caller, "undefined field #{field} on record #{inspect atom}") end end, fields) typespec({:{}, meta, [atom | types]}, vars, caller) _ -> compile_error(caller, "unknown record #{inspect atom}") end end # Handle ranges defp typespec({:.., meta, args}, vars, caller) do args = for arg <- args, do: typespec(arg, vars, caller) {:type, line(meta), :range, args} end # Handle special forms defp typespec({:__MODULE__, _, atom}, vars, caller) when is_atom(atom) do typespec(caller.module, vars, caller) end defp typespec({:__aliases__, _, _} = alias, vars, caller) do # We set a function name to avoid tracking # aliases in typespecs as compile time dependencies. atom = Macro.expand(alias, %{caller | function: {:typespec, 0}}) typespec(atom, vars, caller) end # Handle funs defp typespec([{:->, meta, [arguments, return]}], vars, caller) when is_list(arguments) do args = fn_args(meta, arguments, return, vars, caller) {:type, line(meta), :fun, args} end # Handle type operator defp typespec({:::, meta, [var, expr]}, vars, caller) do left = typespec(var, [elem(var, 0) | vars], caller) right = typespec(expr, vars, caller) {:ann_type, line(meta), [left, right]} end # Handle unary ops defp typespec({op, meta, [integer]}, _, _) when op in [:+, :-] and is_integer(integer) do {:op, line(meta), op, {:integer, line(meta), integer}} end # Handle remote calls in the form of @module_attribute.type. # These are not handled by the general remote type clause as calling # Macro.expand/2 on the remote does not expand module attributes (but expands # things like __MODULE__). defp typespec({{:., meta, [{:@, _, [{attr, _, _}]}, name]}, _, args} = orig, vars, caller) do remote = Module.get_attribute(caller.module, attr) unless is_atom(remote) and remote != nil do message = "invalid remote in typespec: #{Macro.to_string(orig)} (@#{attr} is #{inspect remote})" compile_error(caller, message) end remote_type({typespec(remote, vars, caller), meta, typespec(name, vars, caller), args}, vars, caller) end # Handle remote calls defp typespec({{:., meta, [remote, name]}, _, args} = orig, vars, caller) do # We set a function name to avoid tracking # aliases in typespecs as compile time dependencies. remote = Macro.expand(remote, %{caller | function: {:typespec, 0}}) unless is_atom(remote) do compile_error(caller, "invalid remote in typespec: #{Macro.to_string(orig)}") end remote_type({typespec(remote, vars, caller), meta, typespec(name, vars, caller), args}, vars, caller) end # Handle tuples defp typespec({:tuple, meta, args}, _vars, _caller) when args == [] or is_atom(args) do {:type, line(meta), :tuple, :any} end defp typespec({:{}, meta, t}, vars, caller) when is_list(t) do args = for e <- t, do: typespec(e, vars, caller) {:type, line(meta), :tuple, args} end defp typespec({left, right}, vars, caller) do typespec({:{}, [], [left, right]}, vars, caller) end # Handle blocks defp typespec({:__block__, _meta, [arg]}, vars, caller) do typespec(arg, vars, caller) end # Handle variables or local calls defp typespec({name, meta, atom}, vars, caller) when is_atom(atom) do if :lists.member(name, vars) do {:var, line(meta), name} else typespec({name, meta, []}, vars, caller) end end # Handle local calls defp typespec({:string, meta, arguments}, vars, caller) do :elixir_errors.warn caller.line, caller.file, "string() type use is discouraged. " <> "For character lists, use charlist() type, for strings, String.t()\n" <> Exception.format_stacktrace(Macro.Env.stacktrace(caller)) arguments = for arg <- arguments, do: typespec(arg, vars, caller) {:type, line(meta), :string, arguments} end defp typespec({:nonempty_string, meta, arguments}, vars, caller) do :elixir_errors.warn caller.line, caller.file, "nonempty_string() type use is discouraged. " <> "For non-empty character lists, use nonempty_charlist() type, for strings, String.t()\n" <> Exception.format_stacktrace(Macro.Env.stacktrace(caller)) arguments = for arg <- arguments, do: typespec(arg, vars, caller) {:type, line(meta), :nonempty_string, arguments} end # TODO: Remove char_list type by 2.0 defp typespec({type, _meta, []}, vars, caller) when type in [:charlist, :char_list] do if type == :char_list do :elixir_errors.warn caller.line, caller.file, "the char_list() type is deprecated, use charlist()" end typespec((quote do: :elixir.charlist()), vars, caller) end defp typespec({:nonempty_charlist, _meta, []}, vars, caller) do typespec((quote do: :elixir.nonempty_charlist()), vars, caller) end defp typespec({:struct, _meta, []}, vars, caller) do typespec((quote do: :elixir.struct()), vars, caller) end defp typespec({:as_boolean, _meta, [arg]}, vars, caller) do typespec((quote do: :elixir.as_boolean(unquote(arg))), vars, caller) end defp typespec({:keyword, _meta, args}, vars, caller) when length(args) <= 1 do typespec((quote do: :elixir.keyword(unquote_splicing(args))), vars, caller) end defp typespec({:fun, meta, args}, vars, caller) do args = for arg <- args, do: typespec(arg, vars, caller) {:type, line(meta), :fun, args} end defp typespec({name, meta, arguments}, vars, caller) do arguments = for arg <- arguments, do: typespec(arg, vars, caller) arity = length(arguments) type = if :erl_internal.is_type(name, arity), do: :type, else: :user_type {type, line(meta), name, arguments} end # Handle literals defp typespec(atom, _, _) when is_atom(atom) do {:atom, 0, atom} end defp typespec(integer, _, _) when is_integer(integer) do {:integer, 0, integer} end defp typespec([], vars, caller) do typespec({nil, [], []}, vars, caller) end defp typespec([{:..., _, atom}], vars, caller) when is_atom(atom) do typespec({:nonempty_list, [], []}, vars, caller) end defp typespec([spec, {:..., _, atom}], vars, caller) when is_atom(atom) do typespec({:nonempty_list, [], [spec]}, vars, caller) end defp typespec([spec], vars, caller) do typespec({:list, [], [spec]}, vars, caller) end defp typespec(list, vars, caller) when is_list(list) do [h | t] = :lists.reverse(list) union = :lists.foldl(fn(x, acc) -> {:|, [], [validate_kw(x, list, caller), acc]} end, validate_kw(h, list, caller), t) typespec({:list, [], [union]}, vars, caller) end defp typespec(other, _vars, caller) do compile_error(caller, "unexpected expression in typespec: #{Macro.to_string other}") end ## Helpers defp compile_error(caller, desc) do raise CompileError, file: caller.file, line: caller.line, description: desc end defp remote_type({remote, meta, name, arguments}, vars, caller) do arguments = for arg <- arguments, do: typespec(arg, vars, caller) {:remote_type, line(meta), [remote, name, arguments]} end defp collect_union({:|, _, [a, b]}), do: [a | collect_union(b)] defp collect_union(v), do: [v] defp validate_kw({key, _} = t, _, _caller) when is_atom(key), do: t defp validate_kw(_, original, caller) do compile_error(caller, "unexpected list in typespec: #{Macro.to_string original}") end defp fn_args(meta, args, return, vars, caller) do case [fn_args(meta, args, vars, caller), typespec(return, vars, caller)] do [{:type, _, :any}, {:type, _, :any, []}] -> [] x -> x end end defp fn_args(meta, [{:..., _, _}], _vars, _caller) do {:type, line(meta), :any} end defp fn_args(meta, args, vars, caller) do args = for arg <- args, do: typespec(arg, vars, caller) {:type, line(meta), :product, args} end defp variable({name, meta, _}) do {:var, line(meta), name} end defp unpack_typespec_kw([{:type, _, :tuple, [{:atom, _, atom}, type]} | t], acc) do unpack_typespec_kw(t, [{atom, typespec_to_ast(type)} | acc]) end defp unpack_typespec_kw([], acc) do {:ok, :lists.reverse(acc)} end defp unpack_typespec_kw(_, _acc) do :error end end
32.46475
146
0.624396
f76e71f37b1e92703df7d17792fb89d58c0dab69
5,266
exs
Elixir
integration_test/support/schemas.exs
victorsolis/ecto
6c0dbf1ee2afd9b5bdf1f3feee8d361c8197c99a
[ "Apache-2.0" ]
null
null
null
integration_test/support/schemas.exs
victorsolis/ecto
6c0dbf1ee2afd9b5bdf1f3feee8d361c8197c99a
[ "Apache-2.0" ]
null
null
null
integration_test/support/schemas.exs
victorsolis/ecto
6c0dbf1ee2afd9b5bdf1f3feee8d361c8197c99a
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Integration.Schema do defmacro __using__(_) do quote do use Ecto.Schema type = Application.get_env(:ecto, :primary_key_type) || raise ":primary_key_type not set in :ecto application" @primary_key {:id, type, autogenerate: true} @foreign_key_type type end end end defmodule Ecto.Integration.Post do @moduledoc """ This module is used to test: * Overall functionality * Overall types * Non-null timestamps * Relationships * Dependent callbacks """ use Ecto.Integration.Schema import Ecto.Changeset schema "posts" do field :counter, :id # Same as integer field :title, :string field :text, :binary field :temp, :string, default: "temp", virtual: true field :public, :boolean, default: true field :cost, :decimal field :visits, :integer field :intensity, :float field :bid, :binary_id field :uuid, Ecto.UUID, autogenerate: true field :meta, :map field :posted, Ecto.Date has_many :comments, Ecto.Integration.Comment, on_delete: :delete_all, on_replace: :delete has_one :permalink, Ecto.Integration.Permalink, on_delete: :delete_all, on_replace: :delete has_many :comments_authors, through: [:comments, :author] belongs_to :author, Ecto.Integration.User many_to_many :users, Ecto.Integration.User, join_through: "posts_users", on_delete: :delete_all, on_replace: :delete has_many :users_comments, through: [:users, :comments] timestamps end def changeset(model, params) do cast(model, params, [], ~w(counter title text temp public cost visits intensity bid uuid meta posted)) end end defmodule Ecto.Integration.PostUsecTimestamps do @moduledoc """ This module is used to test: * Usec timestamps """ use Ecto.Integration.Schema schema "posts" do field :title, :string timestamps usec: true end end defmodule Ecto.Integration.Comment do @moduledoc """ This module is used to test: * Optimistic lock * Relationships * Dependent callbacks """ use Ecto.Integration.Schema schema "comments" do field :text, :string field :lock_version, :integer, default: 1 belongs_to :post, Ecto.Integration.Post belongs_to :author, Ecto.Integration.User has_one :post_permalink, through: [:post, :permalink] end end defmodule Ecto.Integration.Permalink do @moduledoc """ This module is used to test: * Relationships * Dependent callbacks """ use Ecto.Integration.Schema schema "permalinks" do field :url, :string belongs_to :post, Ecto.Integration.Post, on_replace: :nilify belongs_to :user, Ecto.Integration.User has_many :post_comments_authors, through: [:post, :comments_authors] end end defmodule Ecto.Integration.UserPost do @moduledoc """ This module is used to test: * Many to many associations join_through with schema """ use Ecto.Integration.Schema schema "users_posts" do belongs_to :user, Ecto.Integration.User belongs_to :post, Ecto.Integration.Post timestamps end end defmodule Ecto.Integration.User do @moduledoc """ This module is used to test: * Timestamps * Relationships * Dependent callbacks """ use Ecto.Integration.Schema schema "users" do field :name, :string has_many :posts, Ecto.Integration.Post, foreign_key: :author_id, on_delete: :nothing, on_replace: :delete has_many :comments, Ecto.Integration.Comment, foreign_key: :author_id, on_delete: :nilify_all, on_replace: :nilify has_one :permalink, Ecto.Integration.Permalink, on_replace: :nilify belongs_to :custom, Ecto.Integration.Custom, references: :bid, type: :binary_id many_to_many :schema_posts, Ecto.Integration.Post, join_through: Ecto.Integration.UserPost timestamps end end defmodule Ecto.Integration.Custom do @moduledoc """ This module is used to test: * binary_id primary key * Tying another schemas to an existing model Due to the second item, it must be a subset of posts. """ use Ecto.Integration.Schema @primary_key {:bid, :binary_id, autogenerate: true} schema "customs" do field :uuid, Ecto.UUID end end defmodule Ecto.Integration.Barebone do @moduledoc """ This module is used to test: * A model wthout primary keys """ use Ecto.Integration.Schema @primary_key false schema "barebones" do field :num, :integer end end defmodule Ecto.Integration.Tag do @moduledoc """ This module is used to test: * The array type * Embedding many models (uses array) """ use Ecto.Integration.Schema schema "tags" do field :ints, {:array, :integer} field :uuids, {:array, Ecto.UUID} embeds_many :items, Ecto.Integration.Item end end defmodule Ecto.Integration.Item do @moduledoc """ This module is used to test: * Embedding """ use Ecto.Integration.Schema embedded_schema do field :price, :integer field :valid_at, Ecto.Date end end defmodule Ecto.Integration.Order do @moduledoc """ This module is used to test: * Embedding one model """ use Ecto.Integration.Schema schema "orders" do embeds_one :item, Ecto.Integration.Item end end
23.300885
118
0.696924
f76e7f093f7c85f982fb906551c3780ad28b67d1
1,041
ex
Elixir
lib/chat/application.ex
Zesky665/GradProject
dad0152de7be505338b1ddbbfcfa82fafe613b68
[ "Unlicense" ]
null
null
null
lib/chat/application.ex
Zesky665/GradProject
dad0152de7be505338b1ddbbfcfa82fafe613b68
[ "Unlicense" ]
null
null
null
lib/chat/application.ex
Zesky665/GradProject
dad0152de7be505338b1ddbbfcfa82fafe613b68
[ "Unlicense" ]
null
null
null
defmodule Chat.Application do use Application # See https://hexdocs.pm/elixir/Application.html # for more information on OTP Applications def start(_type, _args) do import Supervisor.Spec # Define workers and child supervisors to be supervised children = [ # Start the Ecto repository supervisor(Chat.Repo, []), # Start the endpoint when the application starts supervisor(ChatWeb.Endpoint, []), # Start your own worker by calling: Chat.Worker.start_link(arg1, arg2, arg3) # worker(Chat.Worker, [arg1, arg2, arg3]), supervisor(ChatWeb.Presence, []) ] # See https://hexdocs.pm/elixir/Supervisor.html # for other strategies and supported options opts = [strategy: :one_for_one, name: Chat.Supervisor] Supervisor.start_link(children, opts) end # Tell Phoenix to update the endpoint configuration # whenever the application is updated. def config_change(changed, _new, removed) do ChatWeb.Endpoint.config_change(changed, removed) :ok end end
31.545455
82
0.705091
f76edda2771c979d84026a6f902846ec162fda8d
472
ex
Elixir
lib/cadet/accounts/form/login.ex
jiachen247/cadet
4219acaa9ba1d3672b2220d9d1acb2cb671443a3
[ "MIT" ]
null
null
null
lib/cadet/accounts/form/login.ex
jiachen247/cadet
4219acaa9ba1d3672b2220d9d1acb2cb671443a3
[ "MIT" ]
null
null
null
lib/cadet/accounts/form/login.ex
jiachen247/cadet
4219acaa9ba1d3672b2220d9d1acb2cb671443a3
[ "MIT" ]
null
null
null
defmodule Cadet.Accounts.Form.Login do @moduledoc """ The Accounts.Form entity represents an entry from an accounts form. A login form comprises of an IVLE authentication token. """ use Ecto.Schema import Ecto.Changeset embedded_schema do field(:ivle_token, :string) end @required_fields ~w(ivle_token)a def changeset(login, params \\ %{}) do login |> cast(params, @required_fields) |> validate_required(@required_fields) end end
21.454545
69
0.713983
f76f08dac8a7392a07cfd84b8a9f65e236a6fc56
385
ex
Elixir
lib/banking/transaction/withdrawal_transaction.ex
murilosrg/banking-api
731a150d06d605958b53bfd27c4a1f6033527847
[ "MIT" ]
null
null
null
lib/banking/transaction/withdrawal_transaction.ex
murilosrg/banking-api
731a150d06d605958b53bfd27c4a1f6033527847
[ "MIT" ]
null
null
null
lib/banking/transaction/withdrawal_transaction.ex
murilosrg/banking-api
731a150d06d605958b53bfd27c4a1f6033527847
[ "MIT" ]
null
null
null
defmodule Banking.WithdrawalTransaction do @moduledoc """ Creating a withdrawal transaction """ import Ecto.Changeset alias Banking.{Repo, Transaction} def run(params) do %Transaction{type: 2} |> cast(params, [:amount, :account_from]) |> validate_required([:amount, :account_from]) |> foreign_key_constraint(:account_from) |> Repo.insert() end end
21.388889
50
0.693506
f76f3587d5a6cbbd59c791ce99109e431c06895a
86
exs
Elixir
elixir-intro/kode/eksempler/heiverden1.exs
kentdahl/nektar-nuby
03f6624c8bf8de41dd63a0adda5456639b256bc5
[ "MIT" ]
null
null
null
elixir-intro/kode/eksempler/heiverden1.exs
kentdahl/nektar-nuby
03f6624c8bf8de41dd63a0adda5456639b256bc5
[ "MIT" ]
null
null
null
elixir-intro/kode/eksempler/heiverden1.exs
kentdahl/nektar-nuby
03f6624c8bf8de41dd63a0adda5456639b256bc5
[ "MIT" ]
null
null
null
defmodule Verden do def si_hei do IO.puts "Hei verden!" end end Verden.si_hei
12.285714
25
0.709302
f76f539995de39b6a2b9d040d50bc65e41c4b987
1,850
ex
Elixir
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_operation.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
null
null
null
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_operation.ex
MasashiYokota/elixir-google-api
975dccbff395c16afcb62e7a8e411fbb58e9ab01
[ "Apache-2.0" ]
1
2020-12-18T09:25:12.000Z
2020-12-18T09:25:12.000Z
clients/apigee/lib/google_api/apigee/v1/model/google_cloud_apigee_v1_operation.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.Apigee.V1.Model.GoogleCloudApigeeV1Operation do @moduledoc """ Operation represents the pairing of REST resource path and the actions (verbs) allowed on the resource path. ## Attributes * `methods` (*type:* `list(String.t)`, *default:* `nil`) - methods refers to the REST verbs as in https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html. When none specified, all verb types are allowed. * `resource` (*type:* `String.t`, *default:* `nil`) - Required. resource represents REST resource path associated with the proxy/remote service. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :methods => list(String.t()), :resource => String.t() } field(:methods, type: :list) field(:resource) end defimpl Poison.Decoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1Operation do def decode(value, options) do GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1Operation.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.Apigee.V1.Model.GoogleCloudApigeeV1Operation do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
37
206
0.737838
f76f7c3aaeab5e614a3dd3a97d82ad12b7d0d815
658
ex
Elixir
lib/dynamodb/batch_get_item.ex
hirokazumiyaji/dynamodb
f8a3fdc64b954aae99e4281fc28c8ca6886e5876
[ "MIT" ]
1
2017-02-01T12:42:45.000Z
2017-02-01T12:42:45.000Z
lib/dynamodb/batch_get_item.ex
hirokazumiyaji/dynamodb-elixir
f8a3fdc64b954aae99e4281fc28c8ca6886e5876
[ "MIT" ]
null
null
null
lib/dynamodb/batch_get_item.ex
hirokazumiyaji/dynamodb-elixir
f8a3fdc64b954aae99e4281fc28c8ca6886e5876
[ "MIT" ]
null
null
null
defmodule DynamoDB.BatchGetItem do import DynamoDB.Utils defmacro __using__(_) do quote do def batch_get_item(config, request_items, parameters \\ %{}) do payload = %{ RequestItems: request_items } |> Dict.merge(parameters) case post(config, "BatchGetItem", payload) do {:ok, %{status: status, headers: headers, data: data}} -> data["Responses"] {:error, {type, message}} -> {:error, {type, message}} {:error, reason} -> {:error, reason} end end defoverridable Module.definitions_in(__MODULE__) end end end
25.307692
69
0.566869
f76f8682e32dcaa358d790ec302c8b62cf19f809
388
exs
Elixir
priv/repo/seeds.exs
kenforthewin/mentat
417ce989e13f2f08990b872027ce8dcb3a1e6e99
[ "MIT" ]
88
2018-06-17T17:36:56.000Z
2021-11-20T20:29:27.000Z
priv/repo/seeds.exs
kenforthewin/scalar
417ce989e13f2f08990b872027ce8dcb3a1e6e99
[ "MIT" ]
47
2018-05-12T00:12:37.000Z
2018-06-16T19:52:52.000Z
priv/repo/seeds.exs
kenforthewin/scalar
417ce989e13f2f08990b872027ce8dcb3a1e6e99
[ "MIT" ]
6
2018-06-17T17:37:11.000Z
2020-04-12T04:05:49.000Z
# Script for populating the database. You can run it as: # # mix run priv/repo/seeds.exs # # Inside the script, you can read and write to any of your # repositories directly: # # App.Repo.insert!(%App.SomeSchema{}) # # We recommend using the bang functions (`insert!`, `update!` # and so on) as they will fail if something goes wrong. App.Repo.insert!(%App.Team{name: "lobby"})
25.866667
61
0.693299
f76f9659c7bc146548e386e1663e3cd174230315
293
ex
Elixir
{{cookiecutter.app_name}}/lib/{{cookiecutter.app_name}}_web/plugs/auth.ex
StephaneRob/cookiecutter-phoenix
c71a01a582fe8d57999d646cea7cbd820a4c73ca
[ "BSD-2-Clause" ]
4
2018-01-16T15:40:04.000Z
2020-01-11T19:34:42.000Z
{{cookiecutter.app_name}}/lib/{{cookiecutter.app_name}}_web/plugs/auth.ex
StephaneRob/cookiecutter-phoenix
c71a01a582fe8d57999d646cea7cbd820a4c73ca
[ "BSD-2-Clause" ]
4
2018-03-10T14:18:37.000Z
2018-03-13T20:43:06.000Z
{{cookiecutter.app_name}}/lib/{{cookiecutter.app_name}}_web/plugs/auth.ex
StephaneRob/cookiecutter-phoenix
c71a01a582fe8d57999d646cea7cbd820a4c73ca
[ "BSD-2-Clause" ]
1
2019-10-11T20:52:31.000Z
2019-10-11T20:52:31.000Z
defmodule {{cookiecutter.app_name.split('_')|map('title')|join}}Web.Plug.Auth do import Plug.Conn def init(opts), do: opts def call(conn, _params) do assign(conn, :current_user, {{cookiecutter.app_name.split('_')|map('title')|join}}.Guardian.Plug.current_resource(conn)) end end
29.3
124
0.713311
f76fec52d30bc7ad8561bcbb31dfe3a62699cdeb
756
ex
Elixir
lib/cap_phoenix_react_webpack_web/gettext.ex
EBKH/cap-react-webpack
08638c4e4cc30e2cb35e0299a99a7c68a24f2128
[ "MIT" ]
null
null
null
lib/cap_phoenix_react_webpack_web/gettext.ex
EBKH/cap-react-webpack
08638c4e4cc30e2cb35e0299a99a7c68a24f2128
[ "MIT" ]
null
null
null
lib/cap_phoenix_react_webpack_web/gettext.ex
EBKH/cap-react-webpack
08638c4e4cc30e2cb35e0299a99a7c68a24f2128
[ "MIT" ]
null
null
null
defmodule CapPhoenixReactWebpackWeb.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 CapPhoenixReactWebpackWeb.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: :cap_phoenix_react_webpack end
30.24
72
0.701058
f76ffcb6291828130610c9b83e89e40380c49f16
695
ex
Elixir
samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex
chanjarster/openapi-generator
f92f8f1e58c59a429295509d8c5df32b100cde22
[ "Apache-2.0" ]
1
2022-01-11T15:49:34.000Z
2022-01-11T15:49:34.000Z
samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex
chanjarster/openapi-generator
f92f8f1e58c59a429295509d8c5df32b100cde22
[ "Apache-2.0" ]
9
2021-11-01T08:59:31.000Z
2022-03-31T08:31:57.000Z
samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex
chanjarster/openapi-generator
f92f8f1e58c59a429295509d8c5df32b100cde22
[ "Apache-2.0" ]
1
2022-03-20T14:46:48.000Z
2022-03-20T14:46:48.000Z
# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). # https://openapi-generator.tech # Do not edit the class manually. defmodule OpenapiPetstore.Model.AllOfWithSingleRef do @moduledoc """ """ @derive [Poison.Encoder] defstruct [ :"username", :"SingleRefType" ] @type t :: %__MODULE__{ :"username" => String.t | nil, :"SingleRefType" => SingleRefType | nil } end defimpl Poison.Decoder, for: OpenapiPetstore.Model.AllOfWithSingleRef do import OpenapiPetstore.Deserializer def decode(value, options) do value |> deserialize(:"SingleRefType", :struct, OpenapiPetstore.Model.SingleRefType, options) end end
23.166667
91
0.709353
f770139e252420e84aadb929064287eadd132f85
24,477
ex
Elixir
lib/ecto/schema.ex
lancehalvorsen/ecto
af1f80f2907c62da8abb6d0e4bdac98269a80339
[ "Apache-2.0" ]
null
null
null
lib/ecto/schema.ex
lancehalvorsen/ecto
af1f80f2907c62da8abb6d0e4bdac98269a80339
[ "Apache-2.0" ]
null
null
null
lib/ecto/schema.ex
lancehalvorsen/ecto
af1f80f2907c62da8abb6d0e4bdac98269a80339
[ "Apache-2.0" ]
null
null
null
defmodule Ecto.Schema do @moduledoc ~S""" Defines a schema for a model. A schema is a struct with associated metadata that is persisted to a repository. Every schema model is also a struct, that means that you work with models just like you would work with structs. ## Example defmodule User do use Ecto.Schema schema "users" do field :name, :string field :age, :integer, default: 0 has_many :posts, Post end end By default, a schema will generate both a primary key named `id` of type `:integer` and `belongs_to` associations will generate foreign keys of type `:integer` too. Those setting can be configured below. ## Schema attributes The schema supports some attributes to be set before hand, configuring the defined schema. Those attributes are: * `@primary_key` - configures the schema primary key. It expects a tuple with the primary key name, type and options. Defaults to `{:id, :integer, read_after_writes: true}`. When set to false, does not define a primary key in the model; * `@foreign_key_type` - configures the default foreign key type used by `belongs_to` associations. Defaults to `:integer`; * `@timestamps_opts` - configures the default timestamps type used by `timestamps`. Defaults to `[type: Ecto.DateTime, usec: false]`; * `@derive` - the same as `@derive` available in `Kernel.defstruct/1` as the schema defines a struct behind the scenes; The advantage of defining configure the schema via those attributes is that they can be set with a macro to configure application wide defaults. For example, if you would like to use `uuid`'s in all of your application models, you can do: # Define a module to be used as base defmodule MyApp.Model do defmacro __using__(_) do quote do use Ecto.Model @primary_key {:id, :uuid, []} @foreign_key_type :uuid end end end # Now use MyApp.Model to define new models defmodule MyApp.Comment do use MyApp.Model schema "comments" do belongs_to :post, MyApp.Post end end Any models using `MyApp.Model` will get the `:id` field with type `:uuid` as primary key. The `belongs_to` association on `MyApp.Comment` will also define a `:post_id` field with `:uuid` type that references the `:id` of the `MyApp.Post` model. ## Types and casting When defining the schema, types need to be given. Types are split in two categories, primitive types and custom types. ### Primitive types The primitive types are: Ecto type | Elixir type | Literal syntax in query :---------------------- | :---------------------- | :--------------------- `:integer` | `integer` | 1, 2, 3 `:float` | `float` | 1.0, 2.0, 3.0 `:boolean` | `boolean` | true, false `:string` | UTF-8 encoded `string` | "hello" `:binary` | `binary` | `<<int, int, int, ...>>` `:uuid` | 16 byte `binary` | `uuid(binary_or_string)` `{:array, inner_type}` | `list` | `[value, value, value, ...]` `:decimal` | [`Decimal`](https://github.com/ericmj/decimal) `:datetime` | `{{year, month, day}, {hour, min, sec}}` `:date` | `{year, month, day}` `:time` | `{hour, min, sec}` **Note:** Although Ecto provides `:date`, `:time` and `:datetime`, you likely want to use `Ecto.Date`, `Ecto.Time` and `Ecto.DateTime` respectively. See the Custom types sections below about types that enhance the primitive ones. ### Custom types Sometimes the primitive types in Ecto are too primitive. For example, `:uuid` relies on the underling binary representation instead of representing itself as a readable string. That's where `Ecto.UUID` comes in. `Ecto.UUID` is a custom type. A custom type is a module that implements the `Ecto.Type` behaviour. By default, Ecto provides the following custom types: Custom type | Ecto type | Elixir type :---------------------- | :---------------------- | :--------------------- `Ecto.DateTime` | `:datetime` | `%Ecto.DateTime{}` `Ecto.Date` | `:date` | `%Ecto.Date{}` `Ecto.Time` | `:time` | `%Ecto.Time{}` `Ecto.UUID` | `:uuid` | "uuid-string" Ecto allow developers to provide their own types too. Read the `Ecto.Type` documentation for more information. ### Casting When directly manipulating the struct, it is the responsibility of the developer to ensure the field values have the proper type. For example, you can create a weather struct with an invalid value for `temp_lo`: iex> weather = %Weather{temp_lo: "0"} iex> weather.temp_lo "0" However, if you attempt to persist the struct above, an error will be raised since Ecto validates the types when building the query. Therefore, when working and manipulating external data, it is recommended the usage of `Ecto.Changeset`'s that are able to filter and properly cast external data. In fact, `Ecto.Changeset` and custom types provide a powerful combination to extend Ecto types and queries. Finally, models can also have virtual fields by passing the `virtual: true` option. These fields are not persisted to the database and can optionally not be type checked by declaring type `:any`. ## Reflection Any schema module will generate the `__schema__` function that can be used for runtime introspection of the schema: * `__schema__(:source)` - Returns the source as given to `schema/2`; * `__schema__(:primary_key)` - Returns a list of the field that is the primary key or [] if there is none; * `__schema__(:fields)` - Returns a list of all non-virtual field names; * `__schema__(:field, field)` - Returns the type of the given non-virtual field; * `__schema__(:associations)` - Returns a list of all association field names; * `__schema__(:association, assoc)` - Returns the association reflection of the given assoc; * `__schema__(:read_after_writes)` - Non-virtual fields that must be read back from the database after every write (insert or update); * `__schema__(:load, source, idx, values)` - Loads a new model from a tuple of non-virtual field values starting at the given index. Typically used by adapter interfaces; Furthermore, both `__struct__` and `__changeset__` functions are defined so structs and changeset functionalities are available. """ defmodule Metadata do @moduledoc """ Stores metadata of a struct. The fields are: * `state` - the state in a struct's lifetime, e.g. :built, :loaded, :deleted * `source` - the database source of a model, which is the source specified in schema by default or custom source when building a assoc with the custom source. """ defstruct [:state, :source] end @doc false defmacro __using__(_) do quote do import Ecto.Schema, only: [schema: 2] @primary_key {:id, :integer, read_after_writes: true} @timestamps_opts [] @foreign_key_type :integer end end @doc """ Defines a schema with a source name and field definitions. """ defmacro schema(source, [do: block]) do quote do source = unquote(source) unless is_binary(source) do raise ArgumentError, "schema source must be a string, got: #{inspect source}" end Module.register_attribute(__MODULE__, :changeset_fields, accumulate: true) Module.register_attribute(__MODULE__, :struct_fields, accumulate: true) Module.register_attribute(__MODULE__, :ecto_fields, accumulate: true) Module.register_attribute(__MODULE__, :ecto_assocs, accumulate: true) Module.register_attribute(__MODULE__, :ecto_raw, accumulate: true) Module.put_attribute(__MODULE__, :struct_fields, {:__meta__, %Metadata{state: :built, source: source}}) primary_key_field = case @primary_key do false -> [] {name, type, opts} -> Ecto.Schema.field(name, type, opts) [name] other -> raise ArgumentError, "@primary_key must be false or {name, type, opts}" end try do import Ecto.Schema unquote(block) after :ok end fields = @ecto_fields |> Enum.reverse assocs = @ecto_assocs |> Enum.reverse Module.eval_quoted __MODULE__, [ Ecto.Schema.__struct__(@struct_fields), Ecto.Schema.__changeset__(@changeset_fields), Ecto.Schema.__source__(source), Ecto.Schema.__fields__(fields), Ecto.Schema.__assocs__(assocs), Ecto.Schema.__primary_key__(primary_key_field), Ecto.Schema.__load__(fields), Ecto.Schema.__read_after_writes__(@ecto_raw)] end end ## API @doc """ Defines a field on the model schema with given name and type. ## Options * `:default` - Sets the default value on the schema and the struct. The default value is calculated at compilation time, so don't use expressions like `Ecto.DateTime.local` or `Ecto.UUID.generate` as they would then be the same for all records * `:virtual` - When true, the field is not persisted to the database * `:read_after_writes` - When true, the field is always read back from the repository during inserts and updates. For relational databases, this means the RETURNING option of those statements are used. For this reason, MySQL does not support this option for any field besides the primary key (which must be of type serial). Setting this option to true for MySQL will cause the values to be ignored or, even worse, load invalid values from the database. """ defmacro field(name, type \\ :string, opts \\ []) do quote do Ecto.Schema.__field__(__MODULE__, unquote(name), unquote(type), unquote(opts)) end end @doc """ Generates `:inserted_at` and `:updated_at` timestamp fields. When using `Ecto.Model`, the fields generated by this macro will automatically be set to the current time when inserting and updating values in a repository. ## Options * `:type` - the timestamps type, defaults to `Ecto.DateTime`. * `:usec` - boolean, sets whether microseconds are used in timestamps. Microseconds will be 0 if false. Defaults to false. * `:inserted_at` - the name of the column for insertion times or `false` * `:updated_at` - the name of the column for update times or `false` All options can be pre-configured by setting `@timestamps_opts`. """ defmacro timestamps(opts \\ []) do quote bind_quoted: binding do timestamps = [inserted_at: :inserted_at, updated_at: :updated_at, type: Ecto.DateTime, usec: false] |> Keyword.merge(@timestamps_opts) |> Keyword.merge(opts) if inserted_at = Keyword.fetch!(timestamps, :inserted_at) do Ecto.Schema.field(inserted_at, Keyword.fetch!(timestamps, :type), []) end if updated_at = Keyword.fetch!(timestamps, :updated_at) do Ecto.Schema.field(updated_at, Keyword.fetch!(timestamps, :type), []) end @ecto_timestamps timestamps end end @doc """ Defines an association. This macro is used by `belongs_to/3`, `has_one/3` and `has_many/3` to define associations. However, custom association mechanisms can be provided by developers and hooked in via this macro. Read more about custom associations in `Ecto.Association`. """ defmacro association(cardinality, name, association, opts \\ []) do quote do Ecto.Schema.__association__(__MODULE__, unquote(cardinality), unquote(name), unquote(association), unquote(opts)) end end @doc ~S""" Indicates a one-to-many association with another model. The current model has zero or more records of the other model. The other model often has a `belongs_to` field with the reverse association. ## Options * `:foreign_key` - Sets the foreign key, this should map to a field on the other model, defaults to the underscored name of the current model suffixed by `_id` * `:references` - Sets the key on the current model to be used for the association, defaults to the primary key on the model * `:through` - If this association must be defined in terms of existing associations. Read below for more information ## Examples defmodule Post do use Ecto.Model schema "posts" do has_many :comments, Comment end end # Get all comments for a given post post = Repo.get(Post, 42) comments = Repo.all assoc(post, :comments) # The comments can come preloaded on the post struct [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments)) post.comments #=> [%Comment{...}, ...] ## has_many/has_one :through Ecto also supports defining associations in terms of other associations via the `:through` option. Let's see an example: defmodule Post do use Ecto.Model schema "posts" do has_many :comments, Comment has_one :permalink, Permalink has_many :comments_authors, through: [:comments, :author] # Specify the association with custom source has_many :tags, {"posts_tags", Tag} end end defmodule Comment do use Ecto.Model schema "comments" do belongs_to :author, Author belongs_to :post, Post has_one :post_permalink, through: [:post, :permalink] end end In the example above, we have defined a `has_many :through` association named `:comments_authors`. A `:through` association always expect a list and the first element of the list must be a previously defined association in the current module. For example, `:comments_authors` first points to `:comments` in the same module (Post), which then points to `:author` in the next model `Comment`. This `:through` associations will return all authors for all comments that belongs to that post: # Get all comments for a given post post = Repo.get(Post, 42) authors = Repo.all assoc(post, :comments_authors) `:through` associations are read-only as they are useful to avoid repetition allowing the developer to easily retrieve data that is often seem together but stored across different tables. `:through` associations can also be preloaded. In such cases, not only the `:through` association is preloaded but all intermediate steps are preloaded too: [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :comments_authors)) post.comments_authors #=> [%Author{...}, ...] # The comments for each post will be preloaded too post.comments #=> [%Comment{...}, ...] # And the author for each comment too hd(post.comments).authors #=> [%Author{...}, ...] Finally, `:through` can be used with multiple associations (not only 2) and with associations of any kind, including `belongs_to` and others `:through` associations. When the `:through` association is expected to return one or no item, `has_one :through` should be used instead, as in the example at the beginning of this section: # How we defined the association above has_one :post_permalink, through: [:post, :permalink] # Get a preloaded comment [comment] = Repo.all(Comment) |> Repo.preload(:post_permalink) comment.post_permalink #=> %Permalink{...} """ defmacro has_many(name, queryable, opts \\ []) do quote bind_quoted: binding() do if is_list(queryable) and Keyword.has_key?(queryable, :through) do association(:many, name, Ecto.Association.HasThrough, queryable) else association(:many, name, Ecto.Association.Has, [queryable: queryable] ++ opts) end end end @doc ~S""" Indicates a one-to-one association with another model. The current model has zero or one records of the other model. The other model often has a `belongs_to` field with the reverse association. ## Options * `:foreign_key` - Sets the foreign key, this should map to a field on the other model, defaults to the underscored name of the current model suffixed by `_id` * `:references` - Sets the key on the current model to be used for the association, defaults to the primary key on the model * `:through` - If this association must be defined in terms of existing associations. Read the section in `has_many/3` for more information ## Examples defmodule Post do use Ecto.Model schema "posts" do has_one :permalink, Permalink # Specify the association with custom source has_one :category, {"posts_categories", Category} end end # The permalink can come preloaded on the post struct [post] = Repo.all(from(p in Post, where: p.id == 42, preload: :permalink)) post.permalink #=> %Permalink{...} """ defmacro has_one(name, queryable, opts \\ []) do quote bind_quoted: binding() do if is_list(queryable) and Keyword.has_key?(queryable, :through) do association(:one, name, Ecto.Association.HasThrough, queryable) else association(:one, name, Ecto.Association.Has, [queryable: queryable] ++ opts) end end end @doc ~S""" Indicates a one-to-one association with another model. The current model belongs to zero or one records of the other model. The other model often has a `has_one` or a `has_many` field with the reverse association. You should use `belongs_to` in the table that contains the foreign key. Imagine a company <-> manager relationship. If the company contains the `manager_id` in the underlying database table, we say the company belongs to manager. In fact, when you invoke this macro, a field with the name of foreign key is automatically defined in the schema for you. ## Options * `:foreign_key` - Sets the foreign key field name, defaults to the name of the association suffixed by `_id`. For example, `belongs_to :company` will define foreign key of `:company_id` * `:references` - Sets the key on the other model to be used for the association, defaults to: `:id` * `:auto_field` - When false, does not automatically define a `:foreign_key` field, implying the user is defining the field manually elsewhere * `:type` - Sets the type of automatically defined `:foreign_key`. Defaults to: `:integer` and be set per schema via `@foreign_key_type` All other options are forwarded to the underlying foreign key definition and therefore accept the same options as `field/3`. ## Examples defmodule Comment do use Ecto.Model schema "comments" do # This automatically defines a post_id field too belongs_to :post, Post # Specify the association with custom source belongs_to :author, {"posts_authors", Author} end end # The post can come preloaded on the comment record [comment] = Repo.all(from(c in Comment, where: c.id == 42, preload: :post)) comment.post #=> %Post{...} """ defmacro belongs_to(name, queryable, opts \\ []) do quote bind_quoted: binding() do opts = Keyword.put_new(opts, :foreign_key, :"#{name}_id") foreign_key_type = opts[:type] || @foreign_key_type if Keyword.get(opts, :auto_field, true) do field(opts[:foreign_key], foreign_key_type, opts) end association(:one, name, Ecto.Association.BelongsTo, [queryable: queryable] ++ opts) end end ## Callbacks @doc false def __field__(mod, name, type, opts) do check_type!(type, opts[:virtual]) check_default!(type, opts[:default]) Module.put_attribute(mod, :changeset_fields, {name, type}) put_struct_field(mod, name, opts[:default]) unless opts[:virtual] do if opts[:read_after_writes] do Module.put_attribute(mod, :ecto_raw, name) end Module.put_attribute(mod, :ecto_fields, {name, type}) end end @doc false def __association__(mod, cardinality, name, association, opts) do not_loaded = %Ecto.Association.NotLoaded{__owner__: mod, __field__: name, __cardinality__: cardinality} put_struct_field(mod, name, not_loaded) opts = [cardinality: cardinality] ++ opts Module.put_attribute(mod, :ecto_assocs, {name, association.struct(mod, name, opts)}) end @doc false def __load__(struct, source, fields, idx, values) do loaded = do_load(struct, fields, idx, values) loaded = Map.put(loaded, :__meta__, %Metadata{state: :loaded, source: source}) Ecto.Model.Callbacks.__apply__(struct.__struct__, :after_load, loaded) end defp do_load(struct, fields, idx, values) when is_integer(idx) and is_tuple(values) do Enum.reduce(fields, {struct, idx}, fn {field, type}, {acc, idx} -> value = Ecto.Type.load!(type, elem(values, idx)) {Map.put(acc, field, value), idx + 1} end) |> elem(0) end ## Quoted callbacks @doc false def __changeset__(changeset_fields) do map = changeset_fields |> Enum.into(%{}) |> Macro.escape() quote do def __changeset__, do: unquote(map) end end @doc false def __struct__(struct_fields) do quote do defstruct unquote(Macro.escape(struct_fields)) end end @doc false def __source__(source) do quote do def __schema__(:source), do: unquote(Macro.escape(source)) end end @doc false def __fields__(fields) do quoted = Enum.map(fields, fn {name, type} -> quote do def __schema__(:field, unquote(name)), do: unquote(type) end end) field_names = Enum.map(fields, &elem(&1, 0)) quoted ++ [quote do def __schema__(:field, _), do: nil def __schema__(:fields), do: unquote(field_names) end] end @doc false def __assocs__(assocs) do quoted = Enum.map(assocs, fn {name, refl} -> quote do def __schema__(:association, unquote(name)) do unquote(Macro.escape(refl)) end end end) assoc_names = Enum.map(assocs, &elem(&1, 0)) quote do def __schema__(:associations), do: unquote(assoc_names) unquote(quoted) def __schema__(:association, _), do: nil end end @doc false def __primary_key__(primary_key) do quote do def __schema__(:primary_key), do: unquote(primary_key) end end @doc false def __load__(fields) do quote do def __schema__(:load, source, idx, values) do Ecto.Schema.__load__(__struct__(), source, unquote(fields), idx, values) end end end @doc false def __read_after_writes__(fields) do quote do def __schema__(:read_after_writes), do: unquote(Enum.reverse(fields)) end end ## Private defp put_struct_field(mod, name, assoc) do fields = Module.get_attribute(mod, :struct_fields) if List.keyfind(fields, name, 0) do raise ArgumentError, "field/association `#{name}` is already set on schema" end Module.put_attribute(mod, :struct_fields, {name, assoc}) end defp check_type!(type, virtual?) do cond do type == :any and not virtual? -> raise ArgumentError, "only virtual fields can have type :any" Ecto.Type.primitive?(type) -> true is_atom(type) -> if Code.ensure_compiled?(type) and function_exported?(type, :type, 0) do type else raise ArgumentError, "invalid or unknown field type `#{inspect type}`" end true -> raise ArgumentError, "invalid field type `#{inspect type}`" end end defp check_default!(type, default) do case Ecto.Type.dump(type, default) do {:ok, _} -> :ok :error -> raise ArgumentError, "invalid default argument `#{inspect default}` for `#{inspect type}`" end end end
33.995833
98
0.65392
f7704fc423390c3c550145b20d8145c8dab45a32
527
ex
Elixir
lib/todo_app/views/comment_view.ex
Angarsk8/todoapp_cowboy_elixir
38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd
[ "MIT" ]
134
2017-03-28T14:47:37.000Z
2021-11-25T10:40:15.000Z
lib/todo_app/views/comment_view.ex
Angarsk8/todoapp_cowboy_elixir
38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd
[ "MIT" ]
5
2017-03-30T05:56:55.000Z
2018-01-17T09:22:51.000Z
lib/todo_app/views/comment_view.ex
Angarsk8/todoapp_cowboy_elixir
38a4b4420e3c8cbd5f77178aa1cd4b292bd1c4fd
[ "MIT" ]
14
2017-03-28T17:04:31.000Z
2021-08-07T07:09:21.000Z
defmodule TodoApp.CommentView do use TodoApp.BaseView def render(:index, %{comments: comments}) do %{ data: Enum.map(comments, & render(:comment, %{comment: &1})) } end def render(:show, %{comment: comment}) do %{ data: render(:comment, %{comment: comment}) } end def render(:comment, %{comment: comment}) do %{ id: comment.id, text: comment.text, insertedAt: comment.inserted_at, updatedAt: comment.updated_at, todoId: comment.todo_id } end end
21.958333
66
0.612903
f770664a26bdc9eee53256579357b57838fdeada
2,182
ex
Elixir
web/models/user.ex
koenighotze/callforpaper
3ca57abc0cd8d857dedf20e70bce841264d0fe30
[ "MIT" ]
1
2017-01-25T21:34:37.000Z
2017-01-25T21:34:37.000Z
web/models/user.ex
koenighotze/callforpaper
3ca57abc0cd8d857dedf20e70bce841264d0fe30
[ "MIT" ]
40
2017-02-09T07:22:25.000Z
2020-10-28T13:43:12.000Z
web/models/user.ex
koenighotze/callforpaper
3ca57abc0cd8d857dedf20e70bce841264d0fe30
[ "MIT" ]
null
null
null
defmodule Callforpapers.User do use Callforpapers.Web, :model alias Callforpapers.Talk schema "users" do field :name, :string field :email, :string field :bio, :string field :picture, :string field :password, :string, virtual: true field :password_hash, :string field :role, :string, default: "presenter" has_many :talks, Callforpapers.Talk has_many :conferences, Callforpapers.Conference timestamps() end def filter_on_presesenters(query) do query # todo end def is_organizer?(user) do user.role == "organizer" end def is_presenter?(user) do user.role == "presenter" end def talks_by_presenter(user) do assoc(user, :talks) end def alphabetical(query) do from q in query, order_by: q.name end def names_and_ids(query) do from q in query, select: {q.name, q.id} end def changeset(struct, params \\ %{}) do struct |> cast(params, [:name, :email, :bio, :picture, :role]) |> validate_required([:name, :email, :bio, :role]) |> Validators.validate_enum(:role, ["presenter", "organizer"]) |> unique_constraint(:email) end def registration_changeset(model, params \\ :empty) do model |> changeset(params) |> cast(params, ~w(password)) |> validate_length(:password, min: 8, max: 20) |> put_pass_hash() end def put_pass_hash(changeset) do case changeset do %Ecto.Changeset{valid?: true, changes: %{password: pw}} -> put_change(changeset, :password_hash, Comeonin.Bcrypt.hashpwsalt(pw)) _ -> changeset end end def add_talk(user, talk_params) do user |> build_assoc(:talks) |> Talk.changeset(talk_params) |> validate_unique_title(user) end def validate_unique_title(changeset, user) do validate_change(changeset, :title, fn _, title -> talk = Talk.talk_with_title(user, title) |> Callforpapers.Repo.one if nil == talk do [] else [{:title, "is already taken."}] end end) end end
23.978022
134
0.604491
f7706f8c50691545f6dbdb4af2eba4988d600f7a
1,004
ex
Elixir
lib/chess_app/web/views/error_helpers.ex
leobessa/exchess
289819d183f3001dddf56810c36298fa669c3a06
[ "MIT" ]
3
2017-06-02T20:47:07.000Z
2018-05-25T11:17:12.000Z
lib/chess_app/web/views/error_helpers.ex
leobessa/exchess
289819d183f3001dddf56810c36298fa669c3a06
[ "MIT" ]
null
null
null
lib/chess_app/web/views/error_helpers.ex
leobessa/exchess
289819d183f3001dddf56810c36298fa669c3a06
[ "MIT" ]
null
null
null
defmodule ChessApp.Web.ErrorHelpers do @moduledoc """ Conveniences for translating and building error messages. """ @doc """ Translates an error message using gettext. """ def translate_error({msg, opts}) do # Because error messages were defined within Ecto, we must # call the Gettext module passing our Gettext backend. We # also use the "errors" domain as translations are placed # in the errors.po file. # Ecto will pass the :count keyword if the error message is # meant to be pluralized. # On your own code and templates, depending on whether you # need the message to be pluralized or not, this could be # written simply as: # # dngettext "errors", "1 file", "%{count} files", count # dgettext "errors", "is invalid" # if count = opts[:count] do Gettext.dngettext(ChessApp.Web.Gettext, "errors", msg, msg, count, opts) else Gettext.dgettext(ChessApp.Web.Gettext, "errors", msg, opts) end end end
33.466667
78
0.671315
f7707d82d83b9e59e0a2a9be2dfbc1e7a1b38b58
1,637
exs
Elixir
config/dev.exs
tagonzalez/qa-api
10d3ff2ee7fe21c4cca84683f93a3111f7c415e6
[ "MIT" ]
null
null
null
config/dev.exs
tagonzalez/qa-api
10d3ff2ee7fe21c4cca84683f93a3111f7c415e6
[ "MIT" ]
null
null
null
config/dev.exs
tagonzalez/qa-api
10d3ff2ee7fe21c4cca84683f93a3111f7c415e6
[ "MIT" ]
null
null
null
use Mix.Config # Configure your database config :qa_api, QaApi.Repo, username: "postgres", password: "postgres", database: "qa_api_dev", hostname: "db", show_sensitive_data_on_connection_error: true, pool_size: 10 # For development, we disable any cache and enable # debugging and code reloading. # # The watchers configuration can be used to run external # watchers to your application. For example, we use it # with webpack to recompile .js and .css sources. config :qa_api, QaApiWeb.Endpoint, http: [port: 4000], debug_errors: true, code_reloader: true, check_origin: false, watchers: [] # ## SSL Support # # In order to use HTTPS in development, a self-signed # certificate can be generated by running the following # Mix task: # # mix phx.gen.cert # # Note that this task requires Erlang/OTP 20 or later. # Run `mix help phx.gen.cert` for more information. # # The `http:` config above can be replaced with: # # https: [ # port: 4001, # cipher_suite: :strong, # keyfile: "priv/cert/selfsigned_key.pem", # certfile: "priv/cert/selfsigned.pem" # ], # # If desired, both `http:` and `https:` keys can be # configured to run both http and https servers on # different ports. # Do not include metadata nor timestamps in development logs config :logger, :console, format: "[$level] $message\n" # Set a higher stacktrace during development. Avoid configuring such # in production as building large stacktraces may be expensive. config :phoenix, :stacktrace_depth, 20 # Initialize plugs at runtime for faster development compilation config :phoenix, :plug_init_mode, :runtime
28.224138
68
0.723885
f7708a363108b6aa1867ae8d10a787c394d8dcf9
67
exs
Elixir
Chapter13/todo_release/config/dev.exs
benjamindburke/elixir-studies
65231b5af83dcf701041cae2879107c3bd3e5078
[ "Unlicense" ]
null
null
null
Chapter13/todo_release/config/dev.exs
benjamindburke/elixir-studies
65231b5af83dcf701041cae2879107c3bd3e5078
[ "Unlicense" ]
null
null
null
Chapter13/todo_release/config/dev.exs
benjamindburke/elixir-studies
65231b5af83dcf701041cae2879107c3bd3e5078
[ "Unlicense" ]
null
null
null
use Mix.Config config :todo, todo_item_expiry: :timer.seconds(10)
16.75
50
0.776119
f7708a7615b18a690b3704d2cf76aa04e5357088
958
ex
Elixir
lib/scaffolding/common/schema/metadata/ecto_metadata.ex
noizu-labs/advanced_elixir_scaffolding
9e7a1199a4b25fcc16fc5a795104b926d2f238df
[ "MIT" ]
null
null
null
lib/scaffolding/common/schema/metadata/ecto_metadata.ex
noizu-labs/advanced_elixir_scaffolding
9e7a1199a4b25fcc16fc5a795104b926d2f238df
[ "MIT" ]
null
null
null
lib/scaffolding/common/schema/metadata/ecto_metadata.ex
noizu-labs/advanced_elixir_scaffolding
9e7a1199a4b25fcc16fc5a795104b926d2f238df
[ "MIT" ]
null
null
null
#------------------------------------------------------------------------------- # Author: Keith Brings <[email protected]> # Copyright (C) 2021 Noizu Labs Inc. All rights reserved. #------------------------------------------------------------------------------- defmodule Noizu.AdvancedScaffolding.Schema.Metadata.Ecto do @moduledoc """ The Scaffolding library requires Ecto.Repo modules (if used within scaffolding) to include a metadata() method that returns this struct. @example ``` defmodule MyAppSchema.MySQL.Repo do use Ecto.Repo, otp_app: :my_app, adapter: Ecto.Adapters.MyXQL def metadata(), do: %Noizu.Scaffolding.V3.Schema.EctoMetadata{repo: __MODULE__, database: MyAppSchema.MySQL} end ``` """ @vsn 1.0 @type t :: %__MODULE__{ database: atom, repo: atom, vsn: float } defstruct [ database: nil, repo: nil, vsn: @vsn ] end
25.210526
125
0.535491
f77091303866f4dc0d4010d5078a43fae56809d8
417
ex
Elixir
lib/json_rpc/json.ex
hrzndhrn/json_rpc
c9a1d70b92abbf59260be6394bb5ecc41229a599
[ "MIT" ]
null
null
null
lib/json_rpc/json.ex
hrzndhrn/json_rpc
c9a1d70b92abbf59260be6394bb5ecc41229a599
[ "MIT" ]
null
null
null
lib/json_rpc/json.ex
hrzndhrn/json_rpc
c9a1d70b92abbf59260be6394bb5ecc41229a599
[ "MIT" ]
null
null
null
defmodule JsonRPC.Json do @moduledoc false @spec encode!(term()) :: String.t() def encode!(input) do parser().encode!(input) end @spec decode(iodata()) :: {:ok, map()} | {:error, {:parse_error, Exception.t()}} def decode(json) do with {:error, error} <- parser().decode(json) do {:error, {:parse_error, error}} end end defp parser, do: Application.get_env(:json_rpc, :parser) end
23.166667
82
0.625899
f7709df2bb69deac57a459d389d2e167b82392bf
1,779
ex
Elixir
clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/extended_source_context.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2021-12-20T03:40:53.000Z
2021-12-20T03:40:53.000Z
clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/extended_source_context.ex
pojiro/elixir-google-api
928496a017d3875a1929c6809d9221d79404b910
[ "Apache-2.0" ]
1
2020-08-18T00:11:23.000Z
2020-08-18T00:44:16.000Z
clients/cloud_debugger/lib/google_api/cloud_debugger/v2/model/extended_source_context.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.CloudDebugger.V2.Model.ExtendedSourceContext do @moduledoc """ An ExtendedSourceContext is a SourceContext combined with additional details describing the context. ## Attributes * `context` (*type:* `GoogleApi.CloudDebugger.V2.Model.SourceContext.t`, *default:* `nil`) - Any source context. * `labels` (*type:* `map()`, *default:* `nil`) - Labels with user defined metadata. """ use GoogleApi.Gax.ModelBase @type t :: %__MODULE__{ :context => GoogleApi.CloudDebugger.V2.Model.SourceContext.t() | nil, :labels => map() | nil } field(:context, as: GoogleApi.CloudDebugger.V2.Model.SourceContext) field(:labels, type: :map) end defimpl Poison.Decoder, for: GoogleApi.CloudDebugger.V2.Model.ExtendedSourceContext do def decode(value, options) do GoogleApi.CloudDebugger.V2.Model.ExtendedSourceContext.decode(value, options) end end defimpl Poison.Encoder, for: GoogleApi.CloudDebugger.V2.Model.ExtendedSourceContext do def encode(value, options) do GoogleApi.Gax.ModelBase.encode(value, options) end end
35.58
116
0.740304
f770df1c0c786b4d1d30a9ecc1a776fe2b408b0e
774
ex
Elixir
apps/definition_dictionary/lib/dictionary/type/float.ex
kennyatpillar/hindsight
e90e2150a14218e5d6fdf5874f57eb055fd2dd07
[ "Apache-2.0" ]
null
null
null
apps/definition_dictionary/lib/dictionary/type/float.ex
kennyatpillar/hindsight
e90e2150a14218e5d6fdf5874f57eb055fd2dd07
[ "Apache-2.0" ]
null
null
null
apps/definition_dictionary/lib/dictionary/type/float.ex
kennyatpillar/hindsight
e90e2150a14218e5d6fdf5874f57eb055fd2dd07
[ "Apache-2.0" ]
null
null
null
defmodule Dictionary.Type.Float do use Definition, schema: Dictionary.Type.Float.V1 use Dictionary.JsonEncoder defstruct version: 1, name: nil, description: "" defimpl Dictionary.Type.Normalizer, for: __MODULE__ do def normalize(_field, value) when is_integer(value) or is_float(value) do Ok.ok(value / 1) end def normalize(_field, value) do case Float.parse(value) do {parsed_value, _} -> Ok.ok(parsed_value) :error -> Ok.error(:invalid_float) end end end end defmodule Dictionary.Type.Float.V1 do use Definition.Schema @impl true def s do schema(%Dictionary.Type.Float{ version: version(1), name: required_string(), description: string() }) end end
22.114286
77
0.653747
f770e6062d02c0de83d4788f6ba02406a0f42152
1,202
exs
Elixir
mix.exs
mathieuprog/redirect
bc60bfd265a4b46234fd6f980ae6270ff7c471e6
[ "Apache-2.0" ]
12
2019-12-04T07:18:49.000Z
2022-01-22T03:20:18.000Z
mix.exs
mathieuprog/redirect
bc60bfd265a4b46234fd6f980ae6270ff7c471e6
[ "Apache-2.0" ]
2
2020-01-03T14:48:25.000Z
2021-06-23T09:50:58.000Z
mix.exs
mathieuprog/redirect
bc60bfd265a4b46234fd6f980ae6270ff7c471e6
[ "Apache-2.0" ]
1
2020-10-27T11:30:04.000Z
2020-10-27T11:30:04.000Z
defmodule Redirect.MixProject do use Mix.Project @version "0.3.0" def project do [ app: :redirect, elixir: "~> 1.9", deps: deps(), elixirc_paths: elixirc_paths(Mix.env()), # Hex version: @version, package: package(), description: "Router macro for redirecting a request at a given path to another", # ExDoc name: "Redirect", source_url: "https://github.com/mathieuprog/redirect", docs: docs() ] end def application do [ extra_applications: [:logger] ] end defp deps do [ {:phoenix, "~> 1.4", runtime: false}, {:plug, "~> 1.8.3 or ~> 1.9"}, {:ex_doc, "~> 0.21", only: :dev}, {:inch_ex, "~> 2.0", only: :dev}, {:dialyxir, "~> 0.5", only: :dev} ] end defp elixirc_paths(:test), do: ["lib", "test/support"] defp elixirc_paths(_), do: ["lib"] defp package do [ licenses: ["Apache 2.0"], maintainers: ["Mathieu Decaffmeyer"], links: %{"GitHub" => "https://github.com/mathieuprog/redirect"} ] end defp docs do [ main: "readme", extras: ["README.md"], source_ref: "v#{@version}" ] end end
20.033333
87
0.540765
f770ef717ba5144811fb63deb3e16bfbcd3d6cbc
268
exs
Elixir
priv/repo/migrations/20180405055546_create_elm_types.exs
HenkPoley/ellie
045212b56142341fc95b79659c3ca218b0d5d282
[ "BSD-3-Clause" ]
377
2018-04-05T03:36:00.000Z
2022-03-30T19:12:44.000Z
priv/repo/migrations/20180405055546_create_elm_types.exs
HenkPoley/ellie
045212b56142341fc95b79659c3ca218b0d5d282
[ "BSD-3-Clause" ]
91
2018-05-24T21:56:06.000Z
2022-02-26T03:54:04.000Z
priv/repo/migrations/20180405055546_create_elm_types.exs
HenkPoley/ellie
045212b56142341fc95b79659c3ca218b0d5d282
[ "BSD-3-Clause" ]
34
2018-05-29T03:54:35.000Z
2022-01-13T07:12:46.000Z
defmodule Ellie.Repo.Migrations.CreateUsers do use Ecto.Migration def up do Elm.Ecto.Version.up() Elm.Ecto.Name.up() Elm.Ecto.Package.up() end def down do Elm.Ecto.Package.down() Elm.Ecto.Name.down() Elm.Ecto.Version.down() end end
16.75
46
0.664179
f770fbcbd390d481f4c1e8d95c7ad7debe067a82
1,277
ex
Elixir
lib/octet.ex
kiennt/octet
27c4aad5b75725a9013aa2ce9aa7f6d8f9150673
[ "MIT" ]
2
2016-03-15T18:36:08.000Z
2016-05-01T15:09:27.000Z
lib/octet.ex
kiennt/octet
27c4aad5b75725a9013aa2ce9aa7f6d8f9150673
[ "MIT" ]
null
null
null
lib/octet.ex
kiennt/octet
27c4aad5b75725a9013aa2ce9aa7f6d8f9150673
[ "MIT" ]
null
null
null
defmodule Octet do @moduledoc """ Elixir converter to convert octet string to string and vise versa """ @doc """ Convert octet string to binary ## Examples iex> Octet.string_to_bin("aa09ab") <<170, 9, 171>> iex> Octet.string_to_bin("ffddaa") <<255, 221, 170>> """ @spec string_to_bin(string) :: binary def string_to_bin(string) do do_string_to_bin(string, <<>>) end @doc """ Convert binary list to octet string ## Examples iex> Octet.bin_to_string(<<170, 9, 171>>) "aa09ab" iex> Octet.bin_to_string(<<255, 221, 170>>) "ffddaa" """ @spec bin_to_string(binary) :: string def bin_to_string(bin) do do_bin_to_string(bin, "") end # Private function @chars [?0, ?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?a, ?b, ?c, ?d, ?e, ?f] |> Enum.with_index defp do_string_to_bin(<<>>, acc), do: acc defp do_bin_to_string(<<>>, acc), do: acc for {a, i} <- @chars, {b, j} <- @chars, value = i * 16 + j do defp do_string_to_bin(<<unquote(a), unquote(b), remain::binary>>, acc), do: do_string_to_bin(remain, acc <> <<unquote(value)>>) defp do_bin_to_string(<<unquote(value), remain::binary>>, acc), do: do_bin_to_string(remain, acc <> <<unquote(a), unquote(b)>>) end end
25.54
92
0.60141
f77135ab801d0b2323a5907382e360597a65b978
648
ex
Elixir
lib/pigeon/http2_client/chatterbox.ex
elixir-twister/pigeon
9ec9b9773b4a459d5b9743a55f03b61699650d20
[ "MIT" ]
null
null
null
lib/pigeon/http2_client/chatterbox.ex
elixir-twister/pigeon
9ec9b9773b4a459d5b9743a55f03b61699650d20
[ "MIT" ]
null
null
null
lib/pigeon/http2_client/chatterbox.ex
elixir-twister/pigeon
9ec9b9773b4a459d5b9743a55f03b61699650d20
[ "MIT" ]
null
null
null
defmodule Pigeon.Http2.Client.Chatterbox do @behaviour Pigeon.Http2.Client def connect(uri, scheme, opts) do :h2_client.start_link(scheme, uri, opts) end def send_request(pid, headers, data) do :h2_client.send_request(pid, headers, data) end def send_ping(pid) do :h2_client.send_ping(pid) end def handle_end_stream({:END_STREAM, stream}, state) do {:ok, {headers, body}} = :h2_client.get_response(state.apns_socket, stream) body = IO.iodata_to_binary(body) {:ok, %Pigeon.Http2.Stream{id: stream, headers: headers, body: body}} end def handle_end_stream(msg, _state) do IO.inspect(msg) end end
25.92
79
0.709877
f7713b6d2c536f364dcbdbf21eedcda4cdbab0e9
978
ex
Elixir
test/support/channel_case.ex
sdost/game_service
d3dc16ceec2c414cbc10839db19d325d45f4ca04
[ "MIT" ]
1
2017-06-26T23:38:47.000Z
2017-06-26T23:38:47.000Z
test/support/channel_case.ex
sdost/game_service
d3dc16ceec2c414cbc10839db19d325d45f4ca04
[ "MIT" ]
null
null
null
test/support/channel_case.ex
sdost/game_service
d3dc16ceec2c414cbc10839db19d325d45f4ca04
[ "MIT" ]
null
null
null
defmodule GameService.ChannelCase do @moduledoc """ This module defines the test case to be used by channel tests. Such tests rely on `Phoenix.ChannelTest` 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 channels use Phoenix.ChannelTest alias GameService.Repo import Ecto import Ecto.Changeset import Ecto.Query, only: [from: 1, from: 2] # The default endpoint for testing @endpoint GameService.Endpoint end end setup tags do unless tags[:async] do Ecto.Adapters.SQL.restart_test_transaction(GameService.Repo, []) end :ok end end
23.285714
70
0.705521
f7713cf4b206bd942ebd8c4a7b051499743edcf1
874
exs
Elixir
test/himamo/sim_test.exs
mfilej/himamo
78d10964d2f2557d9ddf8f8e8f22aeece59fb7c5
[ "MIT" ]
2
2017-09-25T07:24:26.000Z
2019-08-23T19:55:10.000Z
test/himamo/sim_test.exs
mfilej/himamo
78d10964d2f2557d9ddf8f8e8f22aeece59fb7c5
[ "MIT" ]
null
null
null
test/himamo/sim_test.exs
mfilej/himamo
78d10964d2f2557d9ddf8f8e8f22aeece59fb7c5
[ "MIT" ]
null
null
null
defmodule Himamo.SimTest do use ExUnit.Case alias Himamo.{Sim, Model} doctest Sim def a do import Model.A, only: [new: 1, put: 3] new(3) |> put({0, 0}, 0.0) |> put({0, 1}, 1.0) |> put({0, 2}, 0.0) |> put({1, 0}, 0.0) |> put({1, 1}, 0.0) |> put({1, 2}, 1.0) |> put({2, 0}, 1.0) |> put({2, 1}, 0.0) |> put({2, 2}, 0.0) end def b do import Model.B, only: [new: 1, put: 3] new(n: 3, m: 3) |> put({0, 0}, 1.0) |> put({0, 1}, 0.0) |> put({0, 2}, 0.0) |> put({1, 0}, 0.0) |> put({1, 1}, 1.0) |> put({1, 2}, 0.0) |> put({2, 0}, 0.0) |> put({2, 1}, 0.0) |> put({2, 2}, 1.0) end def model, do: %Model{ a: a, b: b, pi: Model.Pi.new([1.0, 0.0, 0.0]), n: 3, m: 3, } test "generates sequence of words according to a deterministic HMM" do assert Sim.simulate(model, 6) == [0, 1, 2, 0, 1, 2] end end
25.705882
72
0.461098
f7716b9b80a6364f383a469cda2e5af38e9696dd
2,820
exs
Elixir
test/player_test.exs
LeviSchuck/madness
2914f012bd4f40cef2ad39a6d0344a97baf35c79
[ "MIT" ]
null
null
null
test/player_test.exs
LeviSchuck/madness
2914f012bd4f40cef2ad39a6d0344a97baf35c79
[ "MIT" ]
null
null
null
test/player_test.exs
LeviSchuck/madness
2914f012bd4f40cef2ad39a6d0344a97baf35c79
[ "MIT" ]
null
null
null
defmodule PlayerTest do use ExUnit.Case doctest Madness.Player test "Steps" do story_sup_pid = Madness.Stories.Supervisor.whereis {:ok, story_uuid} = Madness.Stories.Supervisor.add_story story_sup_pid story_pid = Madness.Story.whereis story_uuid {:ok, area1_uuid} = Madness.Story.add_area story_pid {:ok, area2_uuid} = Madness.Story.add_area story_pid :ok = Madness.Story.set_initial(story_pid, area1_uuid) area1_pid = Madness.Story.Area.whereis area1_uuid area2_pid = Madness.Story.Area.whereis area2_uuid :ok = Madness.Story.Area.add_condition(area1_pid, "B", :eq, {:b, true}) :ok = Madness.Story.Area.add_condition(area1_pid, "^B", :neq, {:b, true}) :ok = Madness.Story.Area.add_condition(area2_pid, "B", :eq, {:b, true}) Madness.Story.Area.add_say(area1_pid, :plain, "ABC") Madness.Story.Area.add_say(area1_pid, "B", :plain, "DEF") Madness.Story.Area.add_say(area1_pid, :plain, "GHI") Madness.Story.Area.add_say(area2_pid, :plain, "123") Madness.Story.Area.add_say(area2_pid, "B", :plain, "456") Madness.Story.Area.add_say(area2_pid, :plain, "789") Madness.Story.Area.add_step(area1_pid, "^B", "test1", "Test A") Madness.Story.Area.add_transition_command(area1_pid, "test1", area2_uuid) Madness.Story.Area.add_state_command_set(area1_pid, "test1", :b, true) Madness.Story.Area.add_step(area2_pid, "test2", "Test B") Madness.Story.Area.add_transition_command(area2_pid, "test2", area1_uuid) Madness.Story.Area.add_step(area1_pid, "B", "test3", "Test C") Madness.Story.Area.add_state_command_set(area1_pid, "test3", :b, false) player_sup_pid = Madness.Players.Supervisor.whereis {:ok, player_uuid} = Madness.Players.Supervisor.add_player(player_sup_pid) player_pid = Madness.Player.whereis(player_uuid) assert is_pid(player_pid) :ok = Madness.Player.add_story(player_pid, story_uuid) :ok = Madness.Player.set_story(player_pid, story_uuid) story = Madness.Player.get_story(player_pid) assert story == story_uuid choices = Madness.Player.get_choices(player_pid) assert choices == [{"test1", "Test A"}] says = Madness.Player.say_story(player_pid) assert says == [{:plain, "ABC"}, {:plain, "GHI"}] :ok = Madness.Player.make_choice(player_pid, "test1") choices = Madness.Player.get_choices(player_pid) assert choices == [{"test2", "Test B"}] says = Madness.Player.say_story(player_pid) assert says == [{:plain, "123"}, {:plain, "456"}, {:plain, "789"}] :ok = Madness.Player.make_choice(player_pid, "test2") choices = Madness.Player.get_choices(player_pid) assert choices == [{"test3", "Test C"}] says = Madness.Player.say_story(player_pid) assert says == [{:plain, "ABC"}, {:plain, "DEF"}, {:plain, "GHI"}] end end
43.384615
78
0.697518